diff --git a/API_CLIP/clip_prs/.gitignore b/API_CLIP/clip_prs/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..9538023f6050298dfcfdca406c61e225c691236f --- /dev/null +++ b/API_CLIP/clip_prs/.gitignore @@ -0,0 +1,6 @@ +.ipynb_checkpoints/ +__pycache__/ +*/*.mat +utils/__pycache__ +imagenet_seg/ +run/ \ No newline at end of file diff --git a/API_CLIP/clip_prs/LICENSE.txt b/API_CLIP/clip_prs/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..fdd1be61996623799869b25e05046e89f4321c11 --- /dev/null +++ b/API_CLIP/clip_prs/LICENSE.txt @@ -0,0 +1,400 @@ + +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. \ No newline at end of file diff --git a/API_CLIP/clip_prs/README.md b/API_CLIP/clip_prs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5af872e89a6dea01c80d020e49e817f11a186932 --- /dev/null +++ b/API_CLIP/clip_prs/README.md @@ -0,0 +1,104 @@ +## Interpreting CLIP's Image Representation via Text-Based Decomposition +Official PyTorch Implementation + +### [Paper](https://arxiv.org/abs/2310.05916) | [Project Page](https://yossigandelsman.github.io/clip_decomposition/) + +[Yossi Gandelsman](https://yossigandelsman.github.io/), [Alexei A. Efros](https://people.eecs.berkeley.edu/~efros/) and [Jacob Steinhardt](https://jsteinhardt.stat.berkeley.edu/) + +![Teaser](images/teaser.png) + +### Setup +We provide an [`environment.yml`](environment.yml) file that can be used to create a Conda environment: + +```bash +conda env create -f environment.yml +conda activate prsclip +``` +### Preprocessing +To obtain the projected residual stream components for the ImageNet validation set, including the contributions from multi-head attentions and MLPs, please run one of the following instructions: + +```bash +python compute_prs.py --dataset imagenet --device cuda:0 --model ViT-H-14 --pretrained laion2b_s32b_b79k --data_path +python compute_prs.py --dataset imagenet --device cuda:0 --model ViT-L-14 --pretrained laion2b_s32b_b82k --data_path +python compute_prs.py --dataset imagenet --device cuda:0 --model ViT-B-16 --pretrained laion2b_s34b_b88k --data_path +``` + +To obtain the precomputed text representations of the ImageNet classes, please run: +```bash +python compute_text_projection.py --dataset imagenet --device cuda:0 --model ViT-H-14 --pretrained laion2b_s32b_b79k +python compute_text_projection.py --dataset imagenet --device cuda:0 --model ViT-L-14 --pretrained laion2b_s32b_b82k +python compute_text_projection.py --dataset imagenet --device cuda:0 --model ViT-B-16 --pretrained laion2b_s34b_b88k +``` + +### Mean-ablations +To verify that the MLPs and the attention from the class token to itself can be mean-ablated, please run: + +```bash +python compute_ablations.py --model ViT-H-14 +python compute_ablations.py --model ViT-L-14 +python compute_ablations.py --model ViT-B-16 +``` + +### Convert text labels to represntation +To convert the text labels for TextSpan to CLIP text representations, please run: + +```bash +python compute_text_set_projection.py --device cuda:0 --model ViT-L-14 --pretrained laion2b_s32b_b82k --data_path text_descriptions/google_3498_english.txt +python compute_text_set_projection.py --device cuda:0 --model ViT-L-14 --pretrained laion2b_s32b_b82k --data_path text_descriptions/image_descriptions_general.txt +``` + +### ImageNet segmentation +Please download the dataset from [here](http://calvin-vision.net/bigstuff/proj-imagenet/data/gtsegs_ijcv.mat): + +```bash +mkdir imagenet_seg +cd imagenet_seg +wget http://calvin-vision.net/bigstuff/proj-imagenet/data/gtsegs_ijcv.mat +``` + +To get the evaluation results, please run: + +```bash +python compute_segmentations.py --device cuda:0 --model ViT-H-14 --pretrained laion2b_s32b_b79k --data_path imagenet_seg/gtsegs_ijcv.mat --save_img +python compute_segmentations.py --device cuda:0 --model ViT-L-14 --pretrained laion2b_s32b_b82k --data_path imagenet_seg/gtsegs_ijcv.mat --save_img +python compute_segmentations.py --device cuda:0 --model ViT-B-16 --pretrained laion2b_s34b_b88k --data_path imagenet_seg/gtsegs_ijcv.mat --save_img +``` +Save the results with the `--save_img` flag. + + +### TextSpan + +To find meaningful directions for all the attenion heads, run: +```bash +python compute_complete_text_set.py --device cuda:0 --model ViT-B-16 --texts_per_head 20 --num_of_last_layers 4 --text_descriptions image_descriptions_general +python compute_complete_text_set.py --device cuda:0 --model ViT-L-14 --texts_per_head 20 --num_of_last_layers 4 --text_descriptions image_descriptions_general +python compute_complete_text_set.py --device cuda:0 --model ViT-H-14 --texts_per_head 20 --num_of_last_layers 4 --text_descriptions image_descriptions_general +``` + +### Other datasets +To download the Waterbirds datasets, run: +```bash +wget https://nlp.stanford.edu/data/dro/waterbird_complete95_forest2water2.tar.gz +tar -xf waterbird_complete95_forest2water2.tar.gz +``` +To compute the overall accuracy, run: +```bash +python compute_text_projection.py --dataset binary_waterbirds --device cuda:0 --model ViT-L-14 --pretrained laion2b_s32b_b82k +python compute_use_specific_heads.py --model ViT-L-14 --dataset binary_waterbirds +``` + +### Spatial decomposition +Please see a demo for the spatial decomposition of CLIP in `demo.ipynb`. + +### BibTeX + +```bibtex +@misc{gandelsman2023interpreting, + title={Interpreting CLIP's Image Representation via Text-Based Decomposition}, + author={Yossi Gandelsman and Alexei A. Efros and Jacob Steinhardt}, + year={2023}, + eprint={2310.05916}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` diff --git a/API_CLIP/clip_prs/environment.yml b/API_CLIP/clip_prs/environment.yml new file mode 100644 index 0000000000000000000000000000000000000000..a8049685ac15405c9b30cd0a70790f17d89569fd --- /dev/null +++ b/API_CLIP/clip_prs/environment.yml @@ -0,0 +1,19 @@ +name: prsclip +channels: + - pytorch + - nvidia +dependencies: + - python >= 3.8 + - pytorch >= 1.13 + - torchvision + - pytorch-cuda=11.7 + - pip: + - timm + - einops + - ftfy + - scipy + - imageio + - h5py + - scikit-image + - scikit-learn + - opencv-python \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/__init__.py b/API_CLIP/clip_prs/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1984d3129eea85988b7561e8c035a10bc0eb66d5 --- /dev/null +++ b/API_CLIP/clip_prs/utils/__init__.py @@ -0,0 +1,10 @@ +import sys +sys.path.append('API_CLIP/clip_prs') +from utils.constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD +from utils.factory import create_model, create_model_and_transforms, create_model_from_pretrained, get_tokenizer, create_loss +from utils.factory import list_models, add_model_config, get_model_config, load_checkpoint +from utils.pretrained import list_pretrained, list_pretrained_models_by_tag, list_pretrained_tags_by_model, \ + get_pretrained_url, download_pretrained_from_url, is_pretrained_cfg, get_pretrained_cfg, download_pretrained +from utils.tokenizer import SimpleTokenizer, tokenize, decode +from utils.transform import image_transform, AugmentationCfg +from utils.openai_templates import OPENAI_IMAGENET_TEMPLATES \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/binary_waterbirds.py b/API_CLIP/clip_prs/utils/binary_waterbirds.py new file mode 100644 index 0000000000000000000000000000000000000000..2d0a37e4fdcf79ec4260275dd97e45b1d9b183cc --- /dev/null +++ b/API_CLIP/clip_prs/utils/binary_waterbirds.py @@ -0,0 +1,52 @@ +import os +import os.path +from typing import Any, Callable, cast, Dict, List, Optional, Tuple +from typing import Union + +from PIL import Image +import pandas as pd +from torchvision.datasets import VisionDataset +import torch + + +def pil_loader(path: str) -> Image.Image: + # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835) + with open(path, "rb") as f: + img = Image.open(f) + return img.convert("RGB") + +class BinaryWaterbirds(VisionDataset): + def __init__( + self, + root: str, + split: str, + loader: Callable[[str], Any] = pil_loader, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + + self.loader = loader + csv = pd.read_csv(os.path.join(root, 'metadata.csv')) + split = {'test': 2, 'valid': 1, 'train': 0}[split] + csv = csv[csv['split'] == split] + self.samples = [(os.path.join(root, csv.iloc[i]['img_filename']), csv.iloc[i]['y']) for i in range(len(csv))] + + def __getitem__(self, index: int) -> Tuple[Any, Any]: + """ + Args: + index (int): Index + Returns: + tuple: (sample, target) where target is class_index of the target class. + """ + path, target = self.samples[index] + sample = self.loader(path) + if self.transform is not None: + sample = self.transform(sample) + if self.target_transform is not None: + target = self.target_transform(target) + + return sample, target + + def __len__(self) -> int: + return len(self.samples) diff --git a/API_CLIP/clip_prs/utils/constants.py b/API_CLIP/clip_prs/utils/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..bdd90dc5ff9139d62345aabf611b1f4861b66de5 --- /dev/null +++ b/API_CLIP/clip_prs/utils/constants.py @@ -0,0 +1,2 @@ +OPENAI_DATASET_MEAN = (0.48145466, 0.4578275, 0.40821073) +OPENAI_DATASET_STD = (0.26862954, 0.26130258, 0.27577711) \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/cub_classes.py b/API_CLIP/clip_prs/utils/cub_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..b27ebcd4ae0af5152411933797499dc092adaace --- /dev/null +++ b/API_CLIP/clip_prs/utils/cub_classes.py @@ -0,0 +1,2 @@ +cub_classes = ['Black footed Albatross', 'Laysan Albatross', 'Sooty Albatross', 'Groove billed Ani', 'Crested Auklet', 'Least Auklet', 'Parakeet Auklet', 'Rhinoceros Auklet', 'Brewer Blackbird', 'Red winged Blackbird', 'Rusty Blackbird', 'Yellow headed Blackbird', 'Bobolink', 'Indigo Bunting', 'Lazuli Bunting', 'Painted Bunting', 'Cardinal', 'Spotted Catbird', 'Gray Catbird', 'Yellow breasted Chat', 'Eastern Towhee', 'Chuck will Widow', 'Brandt Cormorant', 'Red faced Cormorant', 'Pelagic Cormorant', 'Bronzed Cowbird', 'Shiny Cowbird', 'Brown Creeper', 'American Crow', 'Fish Crow', 'Black billed Cuckoo', 'Mangrove Cuckoo', 'Yellow billed Cuckoo', 'Gray crowned Rosy Finch', 'Purple Finch', 'Northern Flicker', 'Acadian Flycatcher', 'Great Crested Flycatcher', 'Least Flycatcher', 'Olive sided Flycatcher', 'Scissor tailed Flycatcher', 'Vermilion Flycatcher', 'Yellow bellied Flycatcher', 'Frigatebird', 'Northern Fulmar', 'Gadwall', 'American Goldfinch', 'European Goldfinch', 'Boat tailed Grackle', 'Eared Grebe', 'Horned Grebe', 'Pied billed Grebe', 'Western Grebe', 'Blue Grosbeak', 'Evening Grosbeak', 'Pine Grosbeak', 'Rose breasted Grosbeak', 'Pigeon Guillemot', 'California Gull', 'Glaucous winged Gull', 'Heermann Gull', 'Herring Gull', 'Ivory Gull', 'Ring billed Gull', 'Slaty backed Gull', 'Western Gull', 'Anna Hummingbird', 'Ruby throated Hummingbird', 'Rufous Hummingbird', 'Green Violetear', 'Long tailed Jaeger', 'Pomarine Jaeger', 'Blue Jay', 'Florida Jay', 'Green Jay', 'Dark eyed Junco', 'Tropical Kingbird', 'Gray Kingbird', 'Belted Kingfisher', 'Green Kingfisher', 'Pied Kingfisher', 'Ringed Kingfisher', 'White breasted Kingfisher', 'Red legged Kittiwake', 'Horned Lark', 'Pacific Loon', 'Mallard', 'Western Meadowlark', 'Hooded Merganser', 'Red breasted Merganser', 'Mockingbird', 'Nighthawk', 'Clark Nutcracker', 'White breasted Nuthatch', 'Baltimore Oriole', 'Hooded Oriole', 'Orchard Oriole', 'Scott Oriole', 'Ovenbird', 'Brown Pelican', 'White Pelican', 'Western Wood Pewee', 'Sayornis', 'American Pipit', 'Whip poor Will', 'Horned Puffin', 'Common Raven', 'White necked Raven', 'American Redstart', 'Geococcyx', 'Loggerhead Shrike', 'Great Grey Shrike', 'Baird Sparrow', 'Black throated Sparrow', 'Brewer Sparrow', 'Chipping Sparrow', 'Clay colored Sparrow', 'House Sparrow', 'Field Sparrow', 'Fox Sparrow', 'Grasshopper Sparrow', 'Harris Sparrow', 'Henslow Sparrow', 'Le Conte Sparrow', 'Lincoln Sparrow', 'Nelson Sharp tailed Sparrow', 'Savannah Sparrow', 'Seaside Sparrow', 'Song Sparrow', 'Tree Sparrow', 'Vesper Sparrow', 'White crowned Sparrow', 'White throated Sparrow', 'Cape Glossy Starling', 'Bank Swallow', 'Barn Swallow', 'Cliff Swallow', 'Tree Swallow', 'Scarlet Tanager', 'Summer Tanager', 'Artic Tern', 'Black Tern', 'Caspian Tern', 'Common Tern', 'Elegant Tern', 'Forsters Tern', 'Least Tern', 'Green tailed Towhee', 'Brown Thrasher', 'Sage Thrasher', 'Black capped Vireo', 'Blue headed Vireo', 'Philadelphia Vireo', 'Red eyed Vireo', 'Warbling Vireo', 'White eyed Vireo', 'Yellow throated Vireo', 'Bay breasted Warbler', 'Black and white Warbler', 'Black throated Blue Warbler', 'Blue winged Warbler', 'Canada Warbler', 'Cape May Warbler', 'Cerulean Warbler', 'Chestnut sided Warbler', 'Golden winged Warbler', 'Hooded Warbler', 'Kentucky Warbler', 'Magnolia Warbler', 'Mourning Warbler', 'Myrtle Warbler', 'Nashville Warbler', 'Orange crowned Warbler', 'Palm Warbler', 'Pine Warbler', 'Prairie Warbler', 'Prothonotary Warbler', 'Swainson Warbler', 'Tennessee Warbler', 'Wilson Warbler', 'Worm eating Warbler', 'Yellow Warbler', 'Northern Waterthrush', 'Louisiana Waterthrush', 'Bohemian Waxwing', 'Cedar Waxwing', 'American Three toed Woodpecker', 'Pileated Woodpecker', 'Red bellied Woodpecker', 'Red cockaded Woodpecker', 'Red headed Woodpecker', 'Downy Woodpecker', 'Bewick Wren', 'Cactus Wren', 'Carolina Wren', 'House Wren', 'Marsh Wren', 'Rock Wren', 'Winter Wren', 'Common Yellowthroat'] +waterbird_classes = ['landbird', 'waterbird'] \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/factory.py b/API_CLIP/clip_prs/utils/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..bdd90c1c12c0d901173806eef1dc4346d9a6f7a9 --- /dev/null +++ b/API_CLIP/clip_prs/utils/factory.py @@ -0,0 +1,382 @@ +import json +import logging +import os +import pathlib +import re +from copy import deepcopy +from pathlib import Path +from typing import Any, Dict, Optional, Tuple, Union + +import torch + +from utils.constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD +from utils.model import CLIP, convert_to_custom_text_state_dict,\ + resize_pos_embed, get_cast_dtype +from utils.openai_models import load_openai_model +from utils.pretrained import is_pretrained_cfg, get_pretrained_cfg, download_pretrained,\ + list_pretrained_tags_by_model, download_pretrained_from_hf +from utils.transform import image_transform, AugmentationCfg +from utils.tokenizer import HFTokenizer, tokenize + + +HF_HUB_PREFIX = 'hf-hub:' +_MODEL_CONFIG_PATHS = [Path(__file__).parent / f"model_configs/"] +_MODEL_CONFIGS = {} # directory (model_name: config) of model architecture configs + + +def _natural_key(string_): + return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())] + + +def _rescan_model_configs(): + global _MODEL_CONFIGS + + config_ext = ('.json',) + config_files = [] + for config_path in _MODEL_CONFIG_PATHS: + if config_path.is_file() and config_path.suffix in config_ext: + config_files.append(config_path) + elif config_path.is_dir(): + for ext in config_ext: + config_files.extend(config_path.glob(f'*{ext}')) + + for cf in config_files: + with open(cf, 'r') as f: + model_cfg = json.load(f) + if all(a in model_cfg for a in ('embed_dim', 'vision_cfg', 'text_cfg')): + _MODEL_CONFIGS[cf.stem] = model_cfg + + _MODEL_CONFIGS = {k: v for k, v in sorted(_MODEL_CONFIGS.items(), key=lambda x: _natural_key(x[0]))} + + +_rescan_model_configs() # initial populate of model config registry + + +def list_models(): + """ enumerate available model architectures based on config files """ + return list(_MODEL_CONFIGS.keys()) + + +def add_model_config(path): + """ add model config path or file and update registry """ + if not isinstance(path, Path): + path = Path(path) + _MODEL_CONFIG_PATHS.append(path) + _rescan_model_configs() + + +def get_model_config(model_name): + if model_name in _MODEL_CONFIGS: + return deepcopy(_MODEL_CONFIGS[model_name]) + else: + return None + + +def get_tokenizer(model_name): + if model_name.startswith(HF_HUB_PREFIX): + tokenizer = HFTokenizer(model_name[len(HF_HUB_PREFIX):]) + else: + config = get_model_config(model_name) + tokenizer = HFTokenizer( + config['text_cfg']['hf_tokenizer_name']) if 'hf_tokenizer_name' in config['text_cfg'] else tokenize + return tokenizer + + +def load_state_dict(checkpoint_path: str, map_location='cpu'): + checkpoint = torch.load(checkpoint_path, map_location=map_location) + if isinstance(checkpoint, dict) and 'state_dict' in checkpoint: + state_dict = checkpoint['state_dict'] + else: + state_dict = checkpoint + if next(iter(state_dict.items()))[0].startswith('module'): + state_dict = {k[7:]: v for k, v in state_dict.items()} + return state_dict + + +def load_checkpoint(model, checkpoint_path, strict=True): + state_dict = load_state_dict(checkpoint_path) + # detect old format and make compatible with new format + if 'positional_embedding' in state_dict and not hasattr(model, 'positional_embedding'): + state_dict = convert_to_custom_text_state_dict(state_dict) + resize_pos_embed(state_dict, model) + incompatible_keys = model.load_state_dict(state_dict, strict=strict) + return incompatible_keys + + +def create_model( + model_name: str, + pretrained: Optional[str] = None, + precision: str = 'fp32', + device: Union[str, torch.device] = 'cpu', + jit: bool = False, + force_quick_gelu: bool = False, + force_custom_text: bool = False, + force_patch_dropout: Optional[float] = None, + force_image_size: Optional[Union[int, Tuple[int, int]]] = None, + pretrained_image: bool = False, + pretrained_hf: bool = True, + cache_dir: Optional[str] = None, + output_dict: Optional[bool] = None, + require_pretrained: bool = False, +): + has_hf_hub_prefix = model_name.startswith(HF_HUB_PREFIX) + if has_hf_hub_prefix: + model_id = model_name[len(HF_HUB_PREFIX):] + checkpoint_path = download_pretrained_from_hf(model_id, cache_dir=cache_dir) + config_path = download_pretrained_from_hf(model_id, filename='open_clip_config.json', cache_dir=cache_dir) + + with open(config_path, 'r', encoding='utf-8') as f: + config = json.load(f) + pretrained_cfg = config['preprocess_cfg'] + model_cfg = config['model_cfg'] + else: + model_name = model_name.replace('/', '-') # for callers using old naming with / in ViT names + checkpoint_path = None + pretrained_cfg = {} + model_cfg = None + + if isinstance(device, str): + device = torch.device(device) + + if pretrained and pretrained.lower() == 'openai': + logging.info(f'Loading pretrained {model_name} from OpenAI.') + model = load_openai_model( + model_name, + precision=precision, + device=device, + cache_dir=cache_dir, + ) + else: + model_cfg = model_cfg or get_model_config(model_name) + if model_cfg is not None: + logging.info(f'Loaded {model_name} model config.') + else: + logging.error(f'Model config for {model_name} not found; available models {list_models()}.') + raise RuntimeError(f'Model config for {model_name} not found.') + + if force_quick_gelu: + # override for use of QuickGELU on non-OpenAI transformer models + model_cfg["quick_gelu"] = True + + if force_patch_dropout is not None: + # override the default patch dropout value + model_cfg["vision_cfg"]["patch_dropout"] = force_patch_dropout + + if force_image_size is not None: + # override model config's image size + model_cfg["vision_cfg"]["image_size"] = force_image_size + + is_timm_model = 'timm_model_name' in model_cfg.get('vision_cfg', {}) + if pretrained_image: + if is_timm_model: + # pretrained weight loading for timm models set via vision_cfg + model_cfg['vision_cfg']['timm_model_pretrained'] = True + else: + assert False, 'pretrained image towers currently only supported for timm models' + + # cast_dtype set for fp16 and bf16 (manual mixed-precision), not set for 'amp' or 'pure' modes + cast_dtype = get_cast_dtype(precision) + is_hf_model = 'hf_model_name' in model_cfg.get('text_cfg', {}) + custom_text = model_cfg.pop('custom_text', False) or force_custom_text or is_hf_model + + if custom_text: + if is_hf_model: + model_cfg['text_cfg']['hf_model_pretrained'] = pretrained_hf + if "coca" in model_name: + raise ValueError('Coca is not implemented') + model = CoCa(**model_cfg, cast_dtype=cast_dtype) + else: + raise ValueError('CustomTextCLIP is not implemented') + model = CustomTextCLIP(**model_cfg, cast_dtype=cast_dtype) + else: + model = CLIP(**model_cfg, cast_dtype=cast_dtype) + + if precision in ("fp16", "bf16"): + dtype = torch.float16 if 'fp16' in precision else torch.bfloat16 + # manual mixed precision that matches original OpenAI behaviour + if is_timm_model: + # FIXME this is a bit janky, create timm based model in low-precision and + # then cast only LayerNormFp32 instances back to float32 so they don't break. + # Why? The convert_weights_to_lp fn only works with native models. + model.to(device=device, dtype=dtype) + from transformer import LayerNormFp32 + def _convert_ln(m): + if isinstance(m, LayerNormFp32): + m.weight.data = m.weight.data.to(torch.float32) + m.bias.data = m.bias.data.to(torch.float32) + model.apply(_convert_ln) + else: + model.to(device=device) + convert_weights_to_lp(model, dtype=dtype) + elif precision in ("pure_fp16", "pure_bf16"): + dtype = torch.float16 if 'fp16' in precision else torch.bfloat16 + model.to(device=device, dtype=dtype) + else: + model.to(device=device) + + pretrained_loaded = False + if pretrained: + checkpoint_path = '' + pretrained_cfg = get_pretrained_cfg(model_name, pretrained) + if pretrained_cfg: + checkpoint_path = download_pretrained(pretrained_cfg, cache_dir=cache_dir) + elif os.path.exists(pretrained): + checkpoint_path = pretrained + + if checkpoint_path: + logging.info(f'Loading pretrained {model_name} weights ({pretrained}).') + load_checkpoint(model, checkpoint_path) + else: + error_str = ( + f'Pretrained weights ({pretrained}) not found for model {model_name}.' + f'Available pretrained tags ({list_pretrained_tags_by_model(model_name)}.') + logging.warning(error_str) + raise RuntimeError(error_str) + pretrained_loaded = True + elif has_hf_hub_prefix: + logging.info(f'Loading pretrained {model_name} weights ({pretrained}).') + load_checkpoint(model, checkpoint_path) + pretrained_loaded = True + + if require_pretrained and not pretrained_loaded: + # callers of create_model_from_pretrained always expect pretrained weights + raise RuntimeError( + f'Pretrained weights were required for (model: {model_name}, pretrained: {pretrained}) but not loaded.') + + # set image / mean metadata from pretrained_cfg if available, or use default + model.visual.image_mean = pretrained_cfg.get('mean', None) or OPENAI_DATASET_MEAN + model.visual.image_std = pretrained_cfg.get('std', None) or OPENAI_DATASET_STD + + if output_dict and hasattr(model, "output_dict"): + model.output_dict = True + + if jit: + model = torch.jit.script(model) + + return model + + +def create_loss(args): + if args.distill: + return DistillClipLoss( + local_loss=args.local_loss, + gather_with_grad=args.gather_with_grad, + cache_labels=True, + rank=args.rank, + world_size=args.world_size, + use_horovod=args.horovod, + ) + elif "coca" in args.model.lower(): + return CoCaLoss( + caption_loss_weight=args.coca_caption_loss_weight, + clip_loss_weight=args.coca_contrastive_loss_weight, + local_loss=args.local_loss, + gather_with_grad=args.gather_with_grad, + cache_labels=True, + rank=args.rank, + world_size=args.world_size, + use_horovod=args.horovod, + ) + return ClipLoss( + local_loss=args.local_loss, + gather_with_grad=args.gather_with_grad, + cache_labels=True, + rank=args.rank, + world_size=args.world_size, + use_horovod=args.horovod, + ) + + +def create_model_and_transforms( + model_name: str, + pretrained: Optional[str] = None, + precision: str = 'fp32', + device: Union[str, torch.device] = 'cpu', + jit: bool = False, + force_quick_gelu: bool = False, + force_custom_text: bool = False, + force_patch_dropout: Optional[float] = None, + force_image_size: Optional[Union[int, Tuple[int, int]]] = None, + pretrained_image: bool = False, + pretrained_hf: bool = True, + image_mean: Optional[Tuple[float, ...]] = None, + image_std: Optional[Tuple[float, ...]] = None, + aug_cfg: Optional[Union[Dict[str, Any], AugmentationCfg]] = None, + cache_dir: Optional[str] = None, + output_dict: Optional[bool] = None, +): + model = create_model( + model_name, + pretrained, + precision=precision, + device=device, + jit=jit, + force_quick_gelu=force_quick_gelu, + force_custom_text=force_custom_text, + force_patch_dropout=force_patch_dropout, + force_image_size=force_image_size, + pretrained_image=pretrained_image, + pretrained_hf=pretrained_hf, + cache_dir=cache_dir, + output_dict=output_dict, + ) + + image_mean = image_mean or getattr(model.visual, 'image_mean', None) + image_std = image_std or getattr(model.visual, 'image_std', None) + preprocess_train = image_transform( + model.visual.image_size, + is_train=True, + mean=image_mean, + std=image_std, + aug_cfg=aug_cfg, + ) + preprocess_val = image_transform( + model.visual.image_size, + is_train=False, + mean=image_mean, + std=image_std, + ) + + return model, preprocess_train, preprocess_val + + +def create_model_from_pretrained( + model_name: str, + pretrained: Optional[str] = None, + precision: str = 'fp32', + device: Union[str, torch.device] = 'cpu', + jit: bool = False, + force_quick_gelu: bool = False, + force_custom_text: bool = False, + force_image_size: Optional[Union[int, Tuple[int, int]]] = None, + return_transform: bool = True, + image_mean: Optional[Tuple[float, ...]] = None, + image_std: Optional[Tuple[float, ...]] = None, + cache_dir: Optional[str] = None, +): + model = create_model( + model_name, + pretrained, + precision=precision, + device=device, + jit=jit, + force_quick_gelu=force_quick_gelu, + force_custom_text=force_custom_text, + force_image_size=force_image_size, + cache_dir=cache_dir, + require_pretrained=True, + ) + + if not return_transform: + return model + + image_mean = image_mean or getattr(model.visual, 'image_mean', None) + image_std = image_std or getattr(model.visual, 'image_std', None) + preprocess = image_transform( + model.visual.image_size, + is_train=False, + mean=image_mean, + std=image_std, + ) + + return model, preprocess \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/hook.py b/API_CLIP/clip_prs/utils/hook.py new file mode 100644 index 0000000000000000000000000000000000000000..760cacff08b8d79ec0c4a0010adfc989da23552d --- /dev/null +++ b/API_CLIP/clip_prs/utils/hook.py @@ -0,0 +1,91 @@ +from typing import Dict, Text, Callable, List +from collections import defaultdict + + +class HookManager(object): + def __init__(self, hook_dict: Dict[Text, List[Callable]] = None): + self.hook_dict = hook_dict or defaultdict(list) + self.called = defaultdict(int) + self.forks = dict() + + def register(self, name: Text, func: Callable): + assert name + found_successor = False + for header, d in self.forks.items(): + if name.startswith(header.split('.')[0]+'.'): + next_ = name[len(header.split('.')[0]+'.'):].split('.')[0] + prev_ = header.split('.')[0] + if next_.isnumeric(): + if prev_ + '.' + next_ == header: + d.register(name[len(header)+1:], func) + found_successor = True + else: + if next_ == '*': + d.register(name[len(prev_ + '.*')+1:], func) + found_successor = True + else: + d.register(name[len(header)+1:], func) + found_successor = True + if not found_successor: + self.hook_dict[name].append(func) + + def unregister(self, name: Text, func: Callable): + assert name + found_successor = False + for header, d in self.forks.items(): + if name.startswith(header.split('.')[0]+'.'): + next_ = name[len(header.split('.')[0]+'.'):].split('.')[0] + prev_ = header.split('.')[0] + if next_.isnumeric() and prev_ + '.' + next_ == header: + d.register(name[len(header)+1:], func) + elif next_ == '*': + d.register(name[len(prev_ + '.*')+1:], func) + else: + d.register(name[len(header)+1:], func) + found_successor = True + if not found_successor and func in self.hook_dict[name]: + self.hook_dict[name].remove(func) + + def __call__(self, name: Text, **kwargs): + if name in self.hook_dict: + self.called[name] += 1 + for function in self.hook_dict[name]: + ret = function(**kwargs) + if len(self.hook_dict[name]) > 1: + last = self.hook_dict[name][-1] + print(f'The last returned value comes from func {last}') + return ret + else: + return kwargs['ret'] + + def fork(self, name): + if name in self.forks: + raise ValueError(f'Forking with the same name is not allowed. Already forked with {name}.') + filtered_hooks = [(k[len(name)+1:], v) for k, v in self.hook_dict.items() if k.startswith(name+'.')] + filtered_hooks_d = defaultdict(list) + for i, j in filtered_hooks: + if isinstance(j, list): + filtered_hooks_d[i].extend(j) + else: + filtered_hooks_d[i].append(j) + new_hook = HookManager(filtered_hooks_d) + self.forks[name] = new_hook + return new_hook + + def fork_iterative(self, name, iteration): + filtered_hooks = [(k[len(name+'.'+str(iteration))+1:], v) for k, v in self.hook_dict.items() if k.startswith(name+'.'+str(iteration)+'.')] + filtered_hooks += [(k[len(name+'.*')+1:], v) for k, v in self.hook_dict.items() if k.startswith(name+'.*.')] + filtered_hooks_d = defaultdict(list) + for i, j in filtered_hooks: + if isinstance(j, list): + filtered_hooks_d[i].extend(j) + else: + filtered_hooks_d[i].append(j) + new_hook = HookManager(filtered_hooks_d) + self.forks[name+'.'+str(iteration)] = new_hook + return new_hook + + def finalize(self): + for name in self.hook_dict.keys(): + if self.called[name] == 0: + raise ValueError(f'Hook {name} was registered but never used!') \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/imagenet_classes.py b/API_CLIP/clip_prs/utils/imagenet_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..1d34f838cd365ba63e55396e878d470f49b0478d --- /dev/null +++ b/API_CLIP/clip_prs/utils/imagenet_classes.py @@ -0,0 +1 @@ +imagenet_classes = ["tench", "goldfish", "great white shark", "tiger shark", "hammerhead shark", "electric ray", "stingray", "rooster", "hen", "ostrich", "brambling", "goldfinch", "house finch", "junco", "indigo bunting", "American robin", "bulbul", "jay", "magpie", "chickadee", "American dipper", "kite (bird of prey)", "bald eagle", "vulture", "great grey owl", "fire salamander", "smooth newt", "newt", "spotted salamander", "axolotl", "American bullfrog", "tree frog", "tailed frog", "loggerhead sea turtle", "leatherback sea turtle", "mud turtle", "terrapin", "box turtle", "banded gecko", "green iguana", "Carolina anole", "desert grassland whiptail lizard", "agama", "frilled-necked lizard", "alligator lizard", "Gila monster", "European green lizard", "chameleon", "Komodo dragon", "Nile crocodile", "American alligator", "triceratops", "worm snake", "ring-necked snake", "eastern hog-nosed snake", "smooth green snake", "kingsnake", "garter snake", "water snake", "vine snake", "night snake", "boa constrictor", "African rock python", "Indian cobra", "green mamba", "sea snake", "Saharan horned viper", "eastern diamondback rattlesnake", "sidewinder rattlesnake", "trilobite", "harvestman", "scorpion", "yellow garden spider", "barn spider", "European garden spider", "southern black widow", "tarantula", "wolf spider", "tick", "centipede", "black grouse", "ptarmigan", "ruffed grouse", "prairie grouse", "peafowl", "quail", "partridge", "african grey parrot", "macaw", "sulphur-crested cockatoo", "lorikeet", "coucal", "bee eater", "hornbill", "hummingbird", "jacamar", "toucan", "duck", "red-breasted merganser", "goose", "black swan", "tusker", "echidna", "platypus", "wallaby", "koala", "wombat", "jellyfish", "sea anemone", "brain coral", "flatworm", "nematode", "conch", "snail", "slug", "sea slug", "chiton", "chambered nautilus", "Dungeness crab", "rock crab", "fiddler crab", "red king crab", "American lobster", "spiny lobster", "crayfish", "hermit crab", "isopod", "white stork", "black stork", "spoonbill", "flamingo", "little blue heron", "great egret", "bittern bird", "crane bird", "limpkin", "common gallinule", "American coot", "bustard", "ruddy turnstone", "dunlin", "common redshank", "dowitcher", "oystercatcher", "pelican", "king penguin", "albatross", "grey whale", "killer whale", "dugong", "sea lion", "Chihuahua", "Japanese Chin", "Maltese", "Pekingese", "Shih Tzu", "King Charles Spaniel", "Papillon", "toy terrier", "Rhodesian Ridgeback", "Afghan Hound", "Basset Hound", "Beagle", "Bloodhound", "Bluetick Coonhound", "Black and Tan Coonhound", "Treeing Walker Coonhound", "English foxhound", "Redbone Coonhound", "borzoi", "Irish Wolfhound", "Italian Greyhound", "Whippet", "Ibizan Hound", "Norwegian Elkhound", "Otterhound", "Saluki", "Scottish Deerhound", "Weimaraner", "Staffordshire Bull Terrier", "American Staffordshire Terrier", "Bedlington Terrier", "Border Terrier", "Kerry Blue Terrier", "Irish Terrier", "Norfolk Terrier", "Norwich Terrier", "Yorkshire Terrier", "Wire Fox Terrier", "Lakeland Terrier", "Sealyham Terrier", "Airedale Terrier", "Cairn Terrier", "Australian Terrier", "Dandie Dinmont Terrier", "Boston Terrier", "Miniature Schnauzer", "Giant Schnauzer", "Standard Schnauzer", "Scottish Terrier", "Tibetan Terrier", "Australian Silky Terrier", "Soft-coated Wheaten Terrier", "West Highland White Terrier", "Lhasa Apso", "Flat-Coated Retriever", "Curly-coated Retriever", "Golden Retriever", "Labrador Retriever", "Chesapeake Bay Retriever", "German Shorthaired Pointer", "Vizsla", "English Setter", "Irish Setter", "Gordon Setter", "Brittany dog", "Clumber Spaniel", "English Springer Spaniel", "Welsh Springer Spaniel", "Cocker Spaniel", "Sussex Spaniel", "Irish Water Spaniel", "Kuvasz", "Schipperke", "Groenendael dog", "Malinois", "Briard", "Australian Kelpie", "Komondor", "Old English Sheepdog", "Shetland Sheepdog", "collie", "Border Collie", "Bouvier des Flandres dog", "Rottweiler", "German Shepherd Dog", "Dobermann", "Miniature Pinscher", "Greater Swiss Mountain Dog", "Bernese Mountain Dog", "Appenzeller Sennenhund", "Entlebucher Sennenhund", "Boxer", "Bullmastiff", "Tibetan Mastiff", "French Bulldog", "Great Dane", "St. Bernard", "husky", "Alaskan Malamute", "Siberian Husky", "Dalmatian", "Affenpinscher", "Basenji", "pug", "Leonberger", "Newfoundland dog", "Great Pyrenees dog", "Samoyed", "Pomeranian", "Chow Chow", "Keeshond", "brussels griffon", "Pembroke Welsh Corgi", "Cardigan Welsh Corgi", "Toy Poodle", "Miniature Poodle", "Standard Poodle", "Mexican hairless dog (xoloitzcuintli)", "grey wolf", "Alaskan tundra wolf", "red wolf or maned wolf", "coyote", "dingo", "dhole", "African wild dog", "hyena", "red fox", "kit fox", "Arctic fox", "grey fox", "tabby cat", "tiger cat", "Persian cat", "Siamese cat", "Egyptian Mau", "cougar", "lynx", "leopard", "snow leopard", "jaguar", "lion", "tiger", "cheetah", "brown bear", "American black bear", "polar bear", "sloth bear", "mongoose", "meerkat", "tiger beetle", "ladybug", "ground beetle", "longhorn beetle", "leaf beetle", "dung beetle", "rhinoceros beetle", "weevil", "fly", "bee", "ant", "grasshopper", "cricket insect", "stick insect", "cockroach", "praying mantis", "cicada", "leafhopper", "lacewing", "dragonfly", "damselfly", "red admiral butterfly", "ringlet butterfly", "monarch butterfly", "small white butterfly", "sulphur butterfly", "gossamer-winged butterfly", "starfish", "sea urchin", "sea cucumber", "cottontail rabbit", "hare", "Angora rabbit", "hamster", "porcupine", "fox squirrel", "marmot", "beaver", "guinea pig", "common sorrel horse", "zebra", "pig", "wild boar", "warthog", "hippopotamus", "ox", "water buffalo", "bison", "ram (adult male sheep)", "bighorn sheep", "Alpine ibex", "hartebeest", "impala (antelope)", "gazelle", "arabian camel", "llama", "weasel", "mink", "European polecat", "black-footed ferret", "otter", "skunk", "badger", "armadillo", "three-toed sloth", "orangutan", "gorilla", "chimpanzee", "gibbon", "siamang", "guenon", "patas monkey", "baboon", "macaque", "langur", "black-and-white colobus", "proboscis monkey", "marmoset", "white-headed capuchin", "howler monkey", "titi monkey", "Geoffroy's spider monkey", "common squirrel monkey", "ring-tailed lemur", "indri", "Asian elephant", "African bush elephant", "red panda", "giant panda", "snoek fish", "eel", "silver salmon", "rock beauty fish", "clownfish", "sturgeon", "gar fish", "lionfish", "pufferfish", "abacus", "abaya", "academic gown", "accordion", "acoustic guitar", "aircraft carrier", "airliner", "airship", "altar", "ambulance", "amphibious vehicle", "analog clock", "apiary", "apron", "trash can", "assault rifle", "backpack", "bakery", "balance beam", "balloon", "ballpoint pen", "Band-Aid", "banjo", "baluster / handrail", "barbell", "barber chair", "barbershop", "barn", "barometer", "barrel", "wheelbarrow", "baseball", "basketball", "bassinet", "bassoon", "swimming cap", "bath towel", "bathtub", "station wagon", "lighthouse", "beaker", "military hat (bearskin or shako)", "beer bottle", "beer glass", "bell tower", "baby bib", "tandem bicycle", "bikini", "ring binder", "binoculars", "birdhouse", "boathouse", "bobsleigh", "bolo tie", "poke bonnet", "bookcase", "bookstore", "bottle cap", "hunting bow", "bow tie", "brass memorial plaque", "bra", "breakwater", "breastplate", "broom", "bucket", "buckle", "bulletproof vest", "high-speed train", "butcher shop", "taxicab", "cauldron", "candle", "cannon", "canoe", "can opener", "cardigan", "car mirror", "carousel", "tool kit", "cardboard box / carton", "car wheel", "automated teller machine", "cassette", "cassette player", "castle", "catamaran", "CD player", "cello", "mobile phone", "chain", "chain-link fence", "chain mail", "chainsaw", "storage chest", "chiffonier", "bell or wind chime", "china cabinet", "Christmas stocking", "church", "movie theater", "cleaver", "cliff dwelling", "cloak", "clogs", "cocktail shaker", "coffee mug", "coffeemaker", "spiral or coil", "combination lock", "computer keyboard", "candy store", "container ship", "convertible", "corkscrew", "cornet", "cowboy boot", "cowboy hat", "cradle", "construction crane", "crash helmet", "crate", "infant bed", "Crock Pot", "croquet ball", "crutch", "cuirass", "dam", "desk", "desktop computer", "rotary dial telephone", "diaper", "digital clock", "digital watch", "dining table", "dishcloth", "dishwasher", "disc brake", "dock", "dog sled", "dome", "doormat", "drilling rig", "drum", "drumstick", "dumbbell", "Dutch oven", "electric fan", "electric guitar", "electric locomotive", "entertainment center", "envelope", "espresso machine", "face powder", "feather boa", "filing cabinet", "fireboat", "fire truck", "fire screen", "flagpole", "flute", "folding chair", "football helmet", "forklift", "fountain", "fountain pen", "four-poster bed", "freight car", "French horn", "frying pan", "fur coat", "garbage truck", "gas mask or respirator", "gas pump", "goblet", "go-kart", "golf ball", "golf cart", "gondola", "gong", "gown", "grand piano", "greenhouse", "radiator grille", "grocery store", "guillotine", "hair clip", "hair spray", "half-track", "hammer", "hamper", "hair dryer", "hand-held computer", "handkerchief", "hard disk drive", "harmonica", "harp", "combine harvester", "hatchet", "holster", "home theater", "honeycomb", "hook", "hoop skirt", "gymnastic horizontal bar", "horse-drawn vehicle", "hourglass", "iPod", "clothes iron", "carved pumpkin", "jeans", "jeep", "T-shirt", "jigsaw puzzle", "rickshaw", "joystick", "kimono", "knee pad", "knot", "lab coat", "ladle", "lampshade", "laptop computer", "lawn mower", "lens cap", "letter opener", "library", "lifeboat", "lighter", "limousine", "ocean liner", "lipstick", "slip-on shoe", "lotion", "music speaker", "loupe magnifying glass", "sawmill", "magnetic compass", "messenger bag", "mailbox", "tights", "one-piece bathing suit", "manhole cover", "maraca", "marimba", "mask", "matchstick", "maypole", "maze", "measuring cup", "medicine cabinet", "megalith", "microphone", "microwave oven", "military uniform", "milk can", "minibus", "miniskirt", "minivan", "missile", "mitten", "mixing bowl", "mobile home", "ford model t", "modem", "monastery", "monitor", "moped", "mortar and pestle", "graduation cap", "mosque", "mosquito net", "vespa", "mountain bike", "tent", "computer mouse", "mousetrap", "moving van", "muzzle", "metal nail", "neck brace", "necklace", "baby pacifier", "notebook computer", "obelisk", "oboe", "ocarina", "odometer", "oil filter", "pipe organ", "oscilloscope", "overskirt", "bullock cart", "oxygen mask", "product packet / packaging", "paddle", "paddle wheel", "padlock", "paintbrush", "pajamas", "palace", "pan flute", "paper towel", "parachute", "parallel bars", "park bench", "parking meter", "railroad car", "patio", "payphone", "pedestal", "pencil case", "pencil sharpener", "perfume", "Petri dish", "photocopier", "plectrum", "Pickelhaube", "picket fence", "pickup truck", "pier", "piggy bank", "pill bottle", "pillow", "ping-pong ball", "pinwheel", "pirate ship", "drink pitcher", "block plane", "planetarium", "plastic bag", "plate rack", "farm plow", "plunger", "Polaroid camera", "pole", "police van", "poncho", "pool table", "soda bottle", "plant pot", "potter's wheel", "power drill", "prayer rug", "printer", "prison", "missile", "projector", "hockey puck", "punching bag", "purse", "quill", "quilt", "race car", "racket", "radiator", "radio", "radio telescope", "rain barrel", "recreational vehicle", "fishing casting reel", "reflex camera", "refrigerator", "remote control", "restaurant", "revolver", "rifle", "rocking chair", "rotisserie", "eraser", "rugby ball", "ruler measuring stick", "sneaker", "safe", "safety pin", "salt shaker", "sandal", "sarong", "saxophone", "scabbard", "weighing scale", "school bus", "schooner", "scoreboard", "CRT monitor", "screw", "screwdriver", "seat belt", "sewing machine", "shield", "shoe store", "shoji screen / room divider", "shopping basket", "shopping cart", "shovel", "shower cap", "shower curtain", "ski", "balaclava ski mask", "sleeping bag", "slide rule", "sliding door", "slot machine", "snorkel", "snowmobile", "snowplow", "soap dispenser", "soccer ball", "sock", "solar thermal collector", "sombrero", "soup bowl", "keyboard space bar", "space heater", "space shuttle", "spatula", "motorboat", "spider web", "spindle", "sports car", "spotlight", "stage", "steam locomotive", "through arch bridge", "steel drum", "stethoscope", "scarf", "stone wall", "stopwatch", "stove", "strainer", "tram", "stretcher", "couch", "stupa", "submarine", "suit", "sundial", "sunglasses", "sunglasses", "sunscreen", "suspension bridge", "mop", "sweatshirt", "swim trunks / shorts", "swing", "electrical switch", "syringe", "table lamp", "tank", "tape player", "teapot", "teddy bear", "television", "tennis ball", "thatched roof", "front curtain", "thimble", "threshing machine", "throne", "tile roof", "toaster", "tobacco shop", "toilet seat", "torch", "totem pole", "tow truck", "toy store", "tractor", "semi-trailer truck", "tray", "trench coat", "tricycle", "trimaran", "tripod", "triumphal arch", "trolleybus", "trombone", "hot tub", "turnstile", "typewriter keyboard", "umbrella", "unicycle", "upright piano", "vacuum cleaner", "vase", "vaulted or arched ceiling", "velvet fabric", "vending machine", "vestment", "viaduct", "violin", "volleyball", "waffle iron", "wall clock", "wallet", "wardrobe", "military aircraft", "sink", "washing machine", "water bottle", "water jug", "water tower", "whiskey jug", "whistle", "hair wig", "window screen", "window shade", "Windsor tie", "wine bottle", "airplane wing", "wok", "wooden spoon", "wool", "split-rail fence", "shipwreck", "sailboat", "yurt", "website", "comic book", "crossword", "traffic or street sign", "traffic light", "dust jacket", "menu", "plate", "guacamole", "consomme", "hot pot", "trifle", "ice cream", "popsicle", "baguette", "bagel", "pretzel", "cheeseburger", "hot dog", "mashed potatoes", "cabbage", "broccoli", "cauliflower", "zucchini", "spaghetti squash", "acorn squash", "butternut squash", "cucumber", "artichoke", "bell pepper", "cardoon", "mushroom", "Granny Smith apple", "strawberry", "orange", "lemon", "fig", "pineapple", "banana", "jackfruit", "cherimoya (custard apple)", "pomegranate", "hay", "carbonara", "chocolate syrup", "dough", "meatloaf", "pizza", "pot pie", "burrito", "red wine", "espresso", "tea cup", "eggnog", "mountain", "bubble", "cliff", "coral reef", "geyser", "lakeshore", "promontory", "sandbar", "beach", "valley", "volcano", "baseball player", "bridegroom", "scuba diver", "rapeseed", "daisy", "yellow lady's slipper", "corn", "acorn", "rose hip", "horse chestnut seed", "coral fungus", "agaric", "gyromitra", "stinkhorn mushroom", "earth star fungus", "hen of the woods mushroom", "bolete", "corn cob", "toilet paper"] \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/imagenet_segmentation.py b/API_CLIP/clip_prs/utils/imagenet_segmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..50501fa8da3f5a6c531640b21f2ab747c8de9f6c --- /dev/null +++ b/API_CLIP/clip_prs/utils/imagenet_segmentation.py @@ -0,0 +1,50 @@ +import os +import torch +import torch.utils.data as data +import numpy as np + +from torchvision.datasets import ImageNet + +from PIL import Image, ImageFilter +import h5py +from glob import glob + + +class ImagenetSegmentation(data.Dataset): + CLASSES = 2 + + def __init__(self, + path, + transform=None, + target_transform=None): + self.path = path + self.transform = transform + self.target_transform = target_transform + self.h5py = None + tmp = h5py.File(path, 'r') + self.data_length = len(tmp['/value/img']) + tmp.close() + del tmp + + def __getitem__(self, index): + + if self.h5py is None: + self.h5py = h5py.File(self.path, 'r') + + img = np.array(self.h5py[self.h5py['/value/img'][index, 0]]).transpose((2, 1, 0)) + target = np.array(self.h5py[self.h5py[self.h5py['/value/gt'][index, 0]][0, 0]]).transpose((1, 0)) + + img = Image.fromarray(img).convert('RGB') + target = Image.fromarray(target) + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = np.array(self.target_transform(target)).astype('int32') + target = torch.from_numpy(target).long() + + return img, target + + def __len__(self): + return self.data_length diff --git a/API_CLIP/clip_prs/utils/misc.py b/API_CLIP/clip_prs/utils/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..515e352282201079e7545f1993d05a2bf401b1ac --- /dev/null +++ b/API_CLIP/clip_prs/utils/misc.py @@ -0,0 +1,114 @@ +from itertools import repeat +import collections.abc + +import torch +from torch import nn as nn +from torchvision.ops.misc import FrozenBatchNorm2d + + +def freeze_batch_norm_2d(module, module_match={}, name=''): + """ + Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`. If `module` is + itself an instance of either `BatchNorm2d` or `SyncBatchNorm`, it is converted into `FrozenBatchNorm2d` and + returned. Otherwise, the module is walked recursively and submodules are converted in place. + + Args: + module (torch.nn.Module): Any PyTorch module. + module_match (dict): Dictionary of full module names to freeze (all if empty) + name (str): Full module name (prefix) + + Returns: + torch.nn.Module: Resulting module + + Inspired by https://github.com/pytorch/pytorch/blob/a5895f85be0f10212791145bfedc0261d364f103/torch/nn/modules/batchnorm.py#L762 + """ + res = module + is_match = True + if module_match: + is_match = name in module_match + if is_match and isinstance(module, (nn.modules.batchnorm.BatchNorm2d, nn.modules.batchnorm.SyncBatchNorm)): + res = FrozenBatchNorm2d(module.num_features) + res.num_features = module.num_features + res.affine = module.affine + if module.affine: + res.weight.data = module.weight.data.clone().detach() + res.bias.data = module.bias.data.clone().detach() + res.running_mean.data = module.running_mean.data + res.running_var.data = module.running_var.data + res.eps = module.eps + else: + for child_name, child in module.named_children(): + full_child_name = '.'.join([name, child_name]) if name else child_name + new_child = freeze_batch_norm_2d(child, module_match, full_child_name) + if new_child is not child: + res.add_module(child_name, new_child) + return res + + +# From PyTorch internals +def _ntuple(n): + def parse(x): + if isinstance(x, collections.abc.Iterable): + return x + return tuple(repeat(x, n)) + return parse + + +to_1tuple = _ntuple(1) +to_2tuple = _ntuple(2) +to_3tuple = _ntuple(3) +to_4tuple = _ntuple(4) +to_ntuple = lambda n, x: _ntuple(n)(x) + +# Replaces all linear layers with linear_replacement +# TODO: add int8 support for other linear layers including attn and convnets +def replace_linear(model, linear_replacement, include_modules=['c_fc', 'c_proj'], copy_weights=True): + for name, module in model.named_children(): + if len(list(module.children())) > 0: + replace_linear(module, linear_replacement, include_modules, copy_weights) + + if isinstance(module, torch.nn.Linear) and name in include_modules: + old_module = model._modules[name] + model._modules[name] = linear_replacement( + module.in_features, + module.out_features, + module.bias is not None, + ) + if copy_weights: + model._modules[name].weight.data.copy_(old_module.weight.data) + if model._modules[name].bias is not None: + model._modules[name].bias.data.copy_(old_module.bias) + + return model + +def convert_int8_model_to_inference_mode(model): + for m in model.modules(): + if hasattr(m, 'prepare_for_eval'): + int8_original_dtype = m.weight.dtype + m.prepare_for_eval() + m.int8_original_dtype = int8_original_dtype + + +def accuracy(output, target, topk=(1,)): + """ + Compute top-k accuracy + + output: torch.Tensor + shape (N, C) where N is the number of examples, C the number of classes. + these are the logits. + + target: torch.Tensor + shape (N,) where N is the number of examples. Groundtruth class id of each example. + + topk: tuple + which topk to compute, e.g., topk=(1,5) will compute top-1 and top-5 accuracies + + Returns + ------- + + list of top-k accuracies in the same order as `topk` + """ + pred = output.topk(max(topk), 1, True, True)[1].t() + correct = pred.eq(target.view(1, -1).expand_as(pred)) + n = len(target) + return [float(correct[:k].reshape(-1).float().sum(0, keepdim=True).cpu().numpy()) / n for k in topk] diff --git a/API_CLIP/clip_prs/utils/model.py b/API_CLIP/clip_prs/utils/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f484ebbec9766addb34c0c182c9a2874615af1fa --- /dev/null +++ b/API_CLIP/clip_prs/utils/model.py @@ -0,0 +1,407 @@ +""" CLIP Model + +Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. +""" +from dataclasses import dataclass +import logging +import math +from typing import Optional, Tuple, Union, Text + +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn +from torch.utils.checkpoint import checkpoint + + +from utils.modified_resnet import ModifiedResNet +from utils.timm_model import TimmModel +from utils.transformer import LayerNorm, QuickGELU, VisionTransformer, TextTransformer, Attention +from utils.misc import to_2tuple +from utils.hook import HookManager + + +@dataclass +class CLIPVisionCfg: + layers: Union[Tuple[int, int, int, int], int] = 12 + width: int = 768 + head_width: int = 64 + mlp_ratio: float = 4.0 + patch_size: int = 16 + image_size: Union[Tuple[int, int], int] = 224 + + ls_init_value: Optional[float] = None # layer scale initial value + patch_dropout: float = 0. # what fraction of patches to dropout during training (0 would mean disabled and no patches dropped) - 0.5 to 0.75 recommended in the paper for optimal results + input_patchnorm: bool = False # whether to use dual patchnorm - would only apply the input layernorm on each patch, as post-layernorm already exist in original clip vit design + global_average_pool: bool = False # whether to global average pool the last embedding layer, instead of using CLS token (https://arxiv.org/abs/2205.01580) + attentional_pool: bool = False # whether to use attentional pooler in the last embedding layer + n_queries: int = 256 # n_queries for attentional pooler + attn_pooler_heads: int = 8 # n heads for attentional_pooling + output_tokens: bool = False + + timm_model_name: str = None # a valid model name overrides layers, width, patch_size + timm_model_pretrained: bool = False # use (imagenet) pretrained weights for named model + timm_pool: str = 'avg' # feature pooling for timm model ('abs_attn', 'rot_attn', 'avg', '') + timm_proj: str = 'linear' # linear projection for timm model output ('linear', 'mlp', '') + timm_proj_bias: bool = False # enable bias final projection + timm_drop: float = 0. # head dropout + timm_drop_path: Optional[float] = None # backbone stochastic depth + + + + +def convert_weights_to_lp(model: nn.Module, dtype=torch.float16): + """Convert applicable model parameters to low-precision (bf16 or fp16)""" + + def _convert_weights(l): + if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)): + l.weight.data = l.weight.data.to(dtype) + if l.bias is not None: + l.bias.data = l.bias.data.to(dtype) + + if isinstance(l, (nn.MultiheadAttention, Attention)): + for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]: + tensor = getattr(l, attr) + if tensor is not None: + tensor.data = tensor.data.to(dtype) + + if isinstance(l, (CLIP, TextTransformer)): + # convert text nn.Parameter projections + attr = getattr(l, "text_projection", None) + if attr is not None: + attr.data = attr.data.to(dtype) + + if isinstance(l, VisionTransformer): + # convert vision nn.Parameter projections + attr = getattr(l, "proj", None) + if attr is not None: + attr.data = attr.data.to(dtype) + + model.apply(_convert_weights) + +convert_weights_to_fp16 = convert_weights_to_lp # backwards compat + + +@dataclass +class CLIPTextCfg: + context_length: int = 77 + vocab_size: int = 49408 + width: int = 512 + heads: int = 8 + layers: int = 12 + ls_init_value: Optional[float] = None # layer scale initial value + hf_model_name: str = None + hf_tokenizer_name: str = None + hf_model_pretrained: bool = True + proj: str = 'mlp' + pooler_type: str = 'mean_pooler' + embed_cls: bool = False + pad_id: int = 0 + output_tokens: bool = False + + +def get_cast_dtype(precision: str): + cast_dtype = None + if precision == 'bf16': + cast_dtype = torch.bfloat16 + elif precision == 'fp16': + cast_dtype = torch.float16 + return cast_dtype + + +def get_input_dtype(precision: str): + input_dtype = None + if precision in ('bf16', 'pure_bf16'): + input_dtype = torch.bfloat16 + elif precision in ('fp16', 'pure_fp16'): + input_dtype = torch.float16 + return input_dtype + + +def _build_vision_tower( + embed_dim: int, + vision_cfg: CLIPVisionCfg, + quick_gelu: bool = False, + cast_dtype: Optional[torch.dtype] = None, + hook: Optional[HookManager]= None, +): + if isinstance(vision_cfg, dict): + vision_cfg = CLIPVisionCfg(**vision_cfg) + + # OpenAI models are pretrained w/ QuickGELU but native nn.GELU is both faster and more + # memory efficient in recent PyTorch releases (>= 1.10). + # NOTE: timm models always use native GELU regardless of quick_gelu flag. + act_layer = QuickGELU if quick_gelu else nn.GELU + + if vision_cfg.timm_model_name: + visual = TimmModel( + vision_cfg.timm_model_name, + pretrained=vision_cfg.timm_model_pretrained, + pool=vision_cfg.timm_pool, + proj=vision_cfg.timm_proj, + proj_bias=vision_cfg.timm_proj_bias, + drop=vision_cfg.timm_drop, + drop_path=vision_cfg.timm_drop_path, + patch_drop=vision_cfg.patch_dropout if vision_cfg.patch_dropout > 0 else None, + embed_dim=embed_dim, + image_size=vision_cfg.image_size, + hook=hook, + ) + elif isinstance(vision_cfg.layers, (tuple, list)): + vision_heads = vision_cfg.width * 32 // vision_cfg.head_width + visual = ModifiedResNet( + layers=vision_cfg.layers, + output_dim=embed_dim, + heads=vision_heads, + image_size=vision_cfg.image_size, + width=vision_cfg.width, + hook=hook, + ) + else: + vision_heads = vision_cfg.width // vision_cfg.head_width + norm_layer = LayerNormFp32 if cast_dtype in (torch.float16, torch.bfloat16) else LayerNorm + visual = VisionTransformer( + image_size=vision_cfg.image_size, + patch_size=vision_cfg.patch_size, + width=vision_cfg.width, + layers=vision_cfg.layers, + heads=vision_heads, + mlp_ratio=vision_cfg.mlp_ratio, + ls_init_value=vision_cfg.ls_init_value, + patch_dropout=vision_cfg.patch_dropout, + input_patchnorm=vision_cfg.input_patchnorm, + global_average_pool=vision_cfg.global_average_pool, + attentional_pool=vision_cfg.attentional_pool, + n_queries=vision_cfg.n_queries, + attn_pooler_heads=vision_cfg.attn_pooler_heads, + output_tokens=vision_cfg.output_tokens, + output_dim=embed_dim, + act_layer=act_layer, + norm_layer=norm_layer, + hook=hook, + ) + + return visual + + +def _build_text_tower( + embed_dim: int, + text_cfg: CLIPTextCfg, + quick_gelu: bool = False, + cast_dtype: Optional[torch.dtype] = None, + hook: Optional[HookManager] = None, +): + if isinstance(text_cfg, dict): + text_cfg = CLIPTextCfg(**text_cfg) + + if text_cfg.hf_model_name: + from hf_model import HFTextEncoder + text = HFTextEncoder( + text_cfg.hf_model_name, + output_dim=embed_dim, + proj=text_cfg.proj, + pooler_type=text_cfg.pooler_type, + pretrained=text_cfg.hf_model_pretrained, + output_tokens=text_cfg.output_tokens, + ) + else: + act_layer = QuickGELU if quick_gelu else nn.GELU + norm_layer = LayerNormFp32 if cast_dtype in (torch.float16, torch.bfloat16) else LayerNorm + + text = TextTransformer( + context_length=text_cfg.context_length, + vocab_size=text_cfg.vocab_size, + width=text_cfg.width, + heads=text_cfg.heads, + layers=text_cfg.layers, + ls_init_value=text_cfg.ls_init_value, + output_dim=embed_dim, + embed_cls=text_cfg.embed_cls, + output_tokens=text_cfg.output_tokens, + pad_id=text_cfg.pad_id, + act_layer=act_layer, + norm_layer=norm_layer, + ) + return text + + +class CLIP(nn.Module): + output_dict: torch.jit.Final[bool] + + def __init__( + self, + embed_dim: int, + vision_cfg: CLIPVisionCfg, + text_cfg: CLIPTextCfg, + quick_gelu: bool = False, + cast_dtype: Optional[torch.dtype] = None, + output_dict: bool = False, + hook: Optional[HookManager] = None, + ): + super().__init__() + self.hook_manager = hook or HookManager() + self.output_dict = output_dict + self.visual = _build_vision_tower(embed_dim, vision_cfg, quick_gelu, cast_dtype, self.hook_manager.fork('visual')) + + text = _build_text_tower(embed_dim, text_cfg, quick_gelu, cast_dtype, self.hook_manager.fork('textual')) + self.transformer = text.transformer + self.context_length = text.context_length + self.vocab_size = text.vocab_size + self.token_embedding = text.token_embedding + self.positional_embedding = text.positional_embedding + self.ln_final = text.ln_final + self.text_projection = text.text_projection + self.register_buffer('attn_mask', text.attn_mask, persistent=False) + + self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.visual.set_grad_checkpointing(enable) + self.transformer.grad_checkpointing = enable + + def encode_image(self, image, normalize: bool = False, attn_method: Text = 'direct'): + features = self.visual(image, attn_method=attn_method) + return F.normalize(features, dim=-1) if normalize else features + + def encode_text(self, text, normalize: bool = False): + cast_dtype = self.transformer.get_cast_dtype() + + x = self.token_embedding(text).to(cast_dtype) # [batch_size, n_ctx, d_model] + + x = x + self.positional_embedding.to(cast_dtype) + # x = x.permute(1, 0, 2) # NLD -> LND + x = self.transformer(x, attn_mask=self.attn_mask) + # x = x.permute(1, 0, 2) # LND -> NLD + x = self.ln_final(x) # [batch_size, n_ctx, transformer.width] + # take features from the eot embedding (eot_token is the highest number in each sequence) + x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection + return F.normalize(x, dim=-1) if normalize else x + + def forward( + self, + image: Optional[torch.Tensor] = None, + text: Optional[torch.Tensor] = None, + ): + image_features = self.encode_image(image, normalize=True) if image is not None else None + text_features = self.encode_text(text, normalize=True) if text is not None else None + if self.output_dict: + return { + "image_features": image_features, + "text_features": text_features, + "logit_scale": self.logit_scale.exp() + } + return image_features, text_features, self.logit_scale.exp() + + +# used to maintain checkpoint compatibility +def convert_to_custom_text_state_dict(state_dict: dict): + if 'text_projection' in state_dict: + # old format state_dict, move text tower -> .text + new_state_dict = {} + for k, v in state_dict.items(): + if any(k.startswith(p) for p in ( + 'text_projection', + 'positional_embedding', + 'token_embedding', + 'transformer', + 'ln_final', + )): + k = 'text.' + k + new_state_dict[k] = v + return new_state_dict + return state_dict + + +def build_model_from_openai_state_dict( + state_dict: dict, + quick_gelu=True, + cast_dtype=torch.float16, +): + vit = "visual.proj" in state_dict + + if vit: + vision_width = state_dict["visual.conv1.weight"].shape[0] + vision_layers = len( + [k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")]) + vision_patch_size = state_dict["visual.conv1.weight"].shape[-1] + grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5) + image_size = vision_patch_size * grid_size + else: + counts: list = [ + len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]] + vision_layers = tuple(counts) + vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0] + output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5) + vision_patch_size = None + assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0] + image_size = output_width * 32 + + embed_dim = state_dict["text_projection"].shape[1] + context_length = state_dict["positional_embedding"].shape[0] + vocab_size = state_dict["token_embedding.weight"].shape[0] + transformer_width = state_dict["ln_final.weight"].shape[0] + transformer_heads = transformer_width // 64 + transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks"))) + + vision_cfg = CLIPVisionCfg( + layers=vision_layers, + width=vision_width, + patch_size=vision_patch_size, + image_size=image_size, + ) + text_cfg = CLIPTextCfg( + context_length=context_length, + vocab_size=vocab_size, + width=transformer_width, + heads=transformer_heads, + layers=transformer_layers, + ) + model = CLIP( + embed_dim, + vision_cfg=vision_cfg, + text_cfg=text_cfg, + quick_gelu=quick_gelu, # OpenAI models were trained with QuickGELU + cast_dtype=cast_dtype, + ) + + for key in ["input_resolution", "context_length", "vocab_size"]: + state_dict.pop(key, None) + + convert_weights_to_fp16(model) # OpenAI state dicts are partially converted to float16 + model.load_state_dict(state_dict) + return model.eval() + + +def resize_pos_embed(state_dict, model, interpolation: str = 'bicubic', antialias: bool = True): + # Rescale the grid of position embeddings when loading from state_dict + old_pos_embed = state_dict.get('visual.positional_embedding', None) + if old_pos_embed is None or not hasattr(model.visual, 'grid_size'): + return + grid_size = to_2tuple(model.visual.grid_size) + extra_tokens = 1 # FIXME detect different token configs (ie no class token, or more) + new_seq_len = grid_size[0] * grid_size[1] + extra_tokens + if new_seq_len == old_pos_embed.shape[0]: + return + + if extra_tokens: + pos_emb_tok, pos_emb_img = old_pos_embed[:extra_tokens], old_pos_embed[extra_tokens:] + else: + pos_emb_tok, pos_emb_img = None, old_pos_embed + old_grid_size = to_2tuple(int(math.sqrt(len(pos_emb_img)))) + + logging.info('Resizing position embedding grid-size from %s to %s', old_grid_size, grid_size) + pos_emb_img = pos_emb_img.reshape(1, old_grid_size[0], old_grid_size[1], -1).permute(0, 3, 1, 2) + pos_emb_img = F.interpolate( + pos_emb_img, + size=grid_size, + mode=interpolation, + antialias=antialias, + align_corners=False, + ) + pos_emb_img = pos_emb_img.permute(0, 2, 3, 1).reshape(1, grid_size[0] * grid_size[1], -1)[0] + if pos_emb_tok is not None: + new_pos_embed = torch.cat([pos_emb_tok, pos_emb_img], dim=0) + else: + new_pos_embed = pos_emb_img + state_dict['visual.positional_embedding'] = new_pos_embed \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/EVA01-g-14-plus.json b/API_CLIP/clip_prs/utils/model_configs/EVA01-g-14-plus.json new file mode 100644 index 0000000000000000000000000000000000000000..73f46a71e664fce987218b8eb48903e7bd895f41 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/EVA01-g-14-plus.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "timm_model_name": "eva_giant_patch14_224", + "timm_model_pretrained": false, + "timm_pool": "token", + "timm_proj": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24 + }, + "custom_text": true +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/EVA01-g-14.json b/API_CLIP/clip_prs/utils/model_configs/EVA01-g-14.json new file mode 100644 index 0000000000000000000000000000000000000000..9d0e80f290d9491b7c46fafd576201b1258165aa --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/EVA01-g-14.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "timm_model_name": "eva_giant_patch14_224", + "timm_model_pretrained": false, + "timm_pool": "token", + "timm_proj": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + }, + "custom_text": true +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/EVA02-B-16.json b/API_CLIP/clip_prs/utils/model_configs/EVA02-B-16.json new file mode 100644 index 0000000000000000000000000000000000000000..3f92357287e1f6600da1e7f391cb6370d7f66de4 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/EVA02-B-16.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "timm_model_name": "eva02_base_patch16_clip_224", + "timm_model_pretrained": false, + "timm_pool": "token", + "timm_proj": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + }, + "custom_text": true +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/EVA02-E-14-plus.json b/API_CLIP/clip_prs/utils/model_configs/EVA02-E-14-plus.json new file mode 100644 index 0000000000000000000000000000000000000000..e250c2a404c86ff168c54cfcf71bc2492be1b74c --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/EVA02-E-14-plus.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "timm_model_name": "eva02_enormous_patch14_clip_224", + "timm_model_pretrained": false, + "timm_pool": "token", + "timm_proj": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1280, + "heads": 20, + "layers": 32 + }, + "custom_text": true +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/EVA02-E-14.json b/API_CLIP/clip_prs/utils/model_configs/EVA02-E-14.json new file mode 100644 index 0000000000000000000000000000000000000000..4b6648e25092b151a9095e0a66956c7ebf835b16 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/EVA02-E-14.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "timm_model_name": "eva02_enormous_patch14_clip_224", + "timm_model_pretrained": false, + "timm_pool": "token", + "timm_proj": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24 + }, + "custom_text": true +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/EVA02-L-14-336.json b/API_CLIP/clip_prs/utils/model_configs/EVA02-L-14-336.json new file mode 100644 index 0000000000000000000000000000000000000000..2bb07f3c082fd88c4e86131b272163aaacfaef9e --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/EVA02-L-14-336.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 336, + "timm_model_name": "eva02_large_patch14_clip_336", + "timm_model_pretrained": false, + "timm_pool": "token", + "timm_proj": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + }, + "custom_text": true +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/EVA02-L-14.json b/API_CLIP/clip_prs/utils/model_configs/EVA02-L-14.json new file mode 100644 index 0000000000000000000000000000000000000000..b4c7f377bc543aa92a145358f2630a58ae9be989 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/EVA02-L-14.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 224, + "timm_model_name": "eva02_large_patch14_clip_224", + "timm_model_pretrained": false, + "timm_pool": "token", + "timm_proj": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + }, + "custom_text": true +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-B-16-plus-240.json b/API_CLIP/clip_prs/utils/model_configs/ViT-B-16-plus-240.json new file mode 100644 index 0000000000000000000000000000000000000000..5bbd12bcd01f64d6d0a0aa8316b129327a0d169a --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-B-16-plus-240.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 640, + "vision_cfg": { + "image_size": 240, + "layers": 12, + "width": 896, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 640, + "heads": 10, + "layers": 12 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-B-16-plus.json b/API_CLIP/clip_prs/utils/model_configs/ViT-B-16-plus.json new file mode 100644 index 0000000000000000000000000000000000000000..5dc1e09baccef2b15055c1bffeb9903e760101c6 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-B-16-plus.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 640, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 896, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 640, + "heads": 10, + "layers": 12 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-B-16.json b/API_CLIP/clip_prs/utils/model_configs/ViT-B-16.json new file mode 100644 index 0000000000000000000000000000000000000000..395eea77ec3907c0611531aba63459b193e67b9c --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-B-16.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-B-32-plus-256.json b/API_CLIP/clip_prs/utils/model_configs/ViT-B-32-plus-256.json new file mode 100644 index 0000000000000000000000000000000000000000..2f09c857de9a4c01ae51297a7e2451984879f9de --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-B-32-plus-256.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 640, + "vision_cfg": { + "image_size": 256, + "layers": 12, + "width": 896, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 640, + "heads": 10, + "layers": 12 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-B-32-quickgelu.json b/API_CLIP/clip_prs/utils/model_configs/ViT-B-32-quickgelu.json new file mode 100644 index 0000000000000000000000000000000000000000..ce6bd923593293ed50dfcfb28b73ca7403bcf3c5 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-B-32-quickgelu.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 512, + "quick_gelu": true, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-B-32.json b/API_CLIP/clip_prs/utils/model_configs/ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..07c8e28eb06fa1813ba932fe4eec668262d1c47f --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-B-32.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-H-14.json b/API_CLIP/clip_prs/utils/model_configs/ViT-H-14.json new file mode 100644 index 0000000000000000000000000000000000000000..3e3a7e934e7f02e41f4829996c4950e05f015a74 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-H-14.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 32, + "width": 1280, + "head_width": 80, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-H-16.json b/API_CLIP/clip_prs/utils/model_configs/ViT-H-16.json new file mode 100644 index 0000000000000000000000000000000000000000..588485455fdf8193ec16474450b94e31c91ea93c --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-H-16.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 32, + "width": 1280, + "head_width": 80, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-L-14-280.json b/API_CLIP/clip_prs/utils/model_configs/ViT-L-14-280.json new file mode 100644 index 0000000000000000000000000000000000000000..2262deaefa82792d35d73c0d7c8e620525092581 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-L-14-280.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 280, + "layers": 24, + "width": 1024, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-L-14-336.json b/API_CLIP/clip_prs/utils/model_configs/ViT-L-14-336.json new file mode 100644 index 0000000000000000000000000000000000000000..8d1f74c2639c3a3705df9865b9c08215675ddc97 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-L-14-336.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 336, + "layers": 24, + "width": 1024, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-L-14.json b/API_CLIP/clip_prs/utils/model_configs/ViT-L-14.json new file mode 100644 index 0000000000000000000000000000000000000000..d4a4bbb1dd4ed4edb317d3ace4f3ad13b211c241 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-L-14.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 224, + "layers": 24, + "width": 1024, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-L-16-320.json b/API_CLIP/clip_prs/utils/model_configs/ViT-L-16-320.json new file mode 100644 index 0000000000000000000000000000000000000000..fc2d13ca9ec7f0b56a886ddaf66c4a7ba7a442ba --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-L-16-320.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 320, + "layers": 24, + "width": 1024, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-L-16.json b/API_CLIP/clip_prs/utils/model_configs/ViT-L-16.json new file mode 100644 index 0000000000000000000000000000000000000000..82a1cedfa290adacbbdc02bc5d589734c22d41d3 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-L-16.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 224, + "layers": 24, + "width": 1024, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-M-16-alt.json b/API_CLIP/clip_prs/utils/model_configs/ViT-M-16-alt.json new file mode 100644 index 0000000000000000000000000000000000000000..1a317aad8e02d9c26d2decc7cc49a18dfdf9e0d8 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-M-16-alt.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 384, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 512, + "patch_size": 16, + "ls_init_value": 1e-4 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 384, + "heads": 6, + "layers": 12 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-M-16.json b/API_CLIP/clip_prs/utils/model_configs/ViT-M-16.json new file mode 100644 index 0000000000000000000000000000000000000000..f2f3225a46e09237730a151d161f70c86b985172 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-M-16.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 512, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-M-32-alt.json b/API_CLIP/clip_prs/utils/model_configs/ViT-M-32-alt.json new file mode 100644 index 0000000000000000000000000000000000000000..fd222aeac0f582ef6a1a33f1b3fec70a5b386ac0 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-M-32-alt.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 384, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 512, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 384, + "heads": 6, + "layers": 12 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-M-32.json b/API_CLIP/clip_prs/utils/model_configs/ViT-M-32.json new file mode 100644 index 0000000000000000000000000000000000000000..4f718642821035d9776d1e006817d65ede074366 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-M-32.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 512, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-S-16-alt.json b/API_CLIP/clip_prs/utils/model_configs/ViT-S-16-alt.json new file mode 100644 index 0000000000000000000000000000000000000000..a8c056555e4da3ba0d1475a61fc316362ecce76f --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-S-16-alt.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 256, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 384, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 256, + "heads": 4, + "layers": 10 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-S-16.json b/API_CLIP/clip_prs/utils/model_configs/ViT-S-16.json new file mode 100644 index 0000000000000000000000000000000000000000..1d8504e59658803f3093e5b05de45f30a09b8185 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-S-16.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 384, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 384, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 384, + "heads": 6, + "layers": 12 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-S-32-alt.json b/API_CLIP/clip_prs/utils/model_configs/ViT-S-32-alt.json new file mode 100644 index 0000000000000000000000000000000000000000..e1dfdec9824df09a2010e991ccfa1d9ee2f45807 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-S-32-alt.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 256, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 384, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 256, + "heads": 4, + "layers": 10 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-S-32.json b/API_CLIP/clip_prs/utils/model_configs/ViT-S-32.json new file mode 100644 index 0000000000000000000000000000000000000000..9b8b4191b268de267268cfcb90fc01c6b9df07d8 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-S-32.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 384, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 384, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 384, + "heads": 6, + "layers": 12 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-bigG-14.json b/API_CLIP/clip_prs/utils/model_configs/ViT-bigG-14.json new file mode 100644 index 0000000000000000000000000000000000000000..2cfba479a2e8f3737e71ce240732bf3bc743d8b7 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-bigG-14.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 1280, + "vision_cfg": { + "image_size": 224, + "layers": 48, + "width": 1664, + "head_width": 104, + "mlp_ratio": 4.9231, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1280, + "heads": 20, + "layers": 32 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-e-14.json b/API_CLIP/clip_prs/utils/model_configs/ViT-e-14.json new file mode 100644 index 0000000000000000000000000000000000000000..91a0fe14d25a107fb8ec48dd7faae313fd26ed7b --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-e-14.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 1280, + "vision_cfg": { + "image_size": 224, + "layers": 56, + "width": 1792, + "head_width": 112, + "mlp_ratio": 8.5715, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1280, + "heads": 20, + "layers": 36 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/ViT-g-14.json b/API_CLIP/clip_prs/utils/model_configs/ViT-g-14.json new file mode 100644 index 0000000000000000000000000000000000000000..8c4b7325cc75b6112be7107d36ae2cb5762d9091 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/ViT-g-14.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 40, + "width": 1408, + "head_width": 88, + "mlp_ratio": 4.3637, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/coca_ViT-B-32.json b/API_CLIP/clip_prs/utils/model_configs/coca_ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..7e7eb520a6a0096e5602d509ecd6186e278f4725 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/coca_ViT-B-32.json @@ -0,0 +1,30 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32, + "attentional_pool": true, + "attn_pooler_heads": 8, + "output_tokens": true + }, + "text_cfg": { + "context_length": 76, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12, + "embed_cls": true, + "output_tokens": true + }, + "multimodal_cfg": { + "context_length": 76, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12, + "attn_pooler_heads": 8 + }, + "custom_text": true +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/coca_ViT-L-14.json b/API_CLIP/clip_prs/utils/model_configs/coca_ViT-L-14.json new file mode 100644 index 0000000000000000000000000000000000000000..3d5ca4ca2338540f06852df5ff35ea6277e64555 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/coca_ViT-L-14.json @@ -0,0 +1,30 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 224, + "layers": 24, + "width": 1024, + "patch_size": 14, + "attentional_pool": true, + "attn_pooler_heads": 8, + "output_tokens": true + }, + "text_cfg": { + "context_length": 76, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12, + "embed_cls": true, + "output_tokens": true + }, + "multimodal_cfg": { + "context_length": 76, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12, + "attn_pooler_heads": 12 + }, + "custom_text": true +} diff --git a/API_CLIP/clip_prs/utils/model_configs/coca_base.json b/API_CLIP/clip_prs/utils/model_configs/coca_base.json new file mode 100644 index 0000000000000000000000000000000000000000..cf8c6cecb78a49d7e7140145a0307cbd561077c2 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/coca_base.json @@ -0,0 +1,31 @@ +{ + "embed_dim": 512, + "multimodal_cfg": { + "width": 768, + "context_length": 76, + "vocab_size": 64000, + "mlp_ratio": 4, + "layers": 12, + "dim_head": 64, + "heads": 12, + "n_queries": 256, + "attn_pooler_heads": 8 + }, + "vision_cfg": { + "image_size": 288, + "layers": 12, + "width": 768, + "patch_size": 18, + "output_tokens": true + }, + "text_cfg": { + "context_length": 76, + "vocab_size": 64000, + "layers": 12, + "heads": 12, + "width": 768, + "embed_cls": true, + "output_tokens": true + }, + "custom_text": true +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/coca_roberta-ViT-B-32.json b/API_CLIP/clip_prs/utils/model_configs/coca_roberta-ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..fb46354b95a17a46d7fcfd9d504e917ee6c1608c --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/coca_roberta-ViT-B-32.json @@ -0,0 +1,24 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32, + "output_tokens": true + }, + "text_cfg": { + "hf_model_name": "roberta-base", + "hf_tokenizer_name": "roberta-base", + "proj": "linear", + "width": 768, + "output_tokens": true + }, + "multimodal_cfg": { + "context_length": 76, + "width": 768, + "heads": 8, + "layers": 12 + }, + "custom_text": true +} diff --git a/API_CLIP/clip_prs/utils/model_configs/mt5-base-ViT-B-32.json b/API_CLIP/clip_prs/utils/model_configs/mt5-base-ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..58cad89cf0f446bbe15e4e25b1ac43424a828017 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/mt5-base-ViT-B-32.json @@ -0,0 +1,15 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "hf_model_name": "google/mt5-base", + "hf_tokenizer_name": "google/mt5-base", + "proj": "mlp", + "pooler_type": "mean_pooler" + } +} diff --git a/API_CLIP/clip_prs/utils/model_configs/mt5-xl-ViT-H-14.json b/API_CLIP/clip_prs/utils/model_configs/mt5-xl-ViT-H-14.json new file mode 100644 index 0000000000000000000000000000000000000000..b432810777ba7269dbb0e89edfe65cdd27e7d255 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/mt5-xl-ViT-H-14.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 32, + "width": 1280, + "head_width": 80, + "patch_size": 14 + }, + "text_cfg": { + "hf_model_name": "google/mt5-xl", + "hf_tokenizer_name": "google/mt5-xl", + "proj": "mlp", + "pooler_type": "mean_pooler" + } +} diff --git a/API_CLIP/clip_prs/utils/model_configs/roberta-ViT-B-32.json b/API_CLIP/clip_prs/utils/model_configs/roberta-ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..ed687d472a73bb2ac96025f355f80437ab14c260 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/roberta-ViT-B-32.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "quick_gelu": true, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "hf_model_name": "roberta-base", + "hf_tokenizer_name": "roberta-base", + "proj": "mlp", + "pooler_type": "mean_pooler" + } +} diff --git a/API_CLIP/clip_prs/utils/model_configs/swin_base_patch4_window7_224.json b/API_CLIP/clip_prs/utils/model_configs/swin_base_patch4_window7_224.json new file mode 100644 index 0000000000000000000000000000000000000000..bd6820f0cf2aa655e0a2723287f4b78895a58e6a --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/swin_base_patch4_window7_224.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 640, + "vision_cfg": { + "timm_model_name": "swin_base_patch4_window7_224", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "image_size": 224 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 640, + "heads": 10, + "layers": 12 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/vit_medium_patch16_gap_256.json b/API_CLIP/clip_prs/utils/model_configs/vit_medium_patch16_gap_256.json new file mode 100644 index 0000000000000000000000000000000000000000..8843eaf08cad16c3e7b5f496fd650715c9573f65 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/vit_medium_patch16_gap_256.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "timm_model_name": "vit_medium_patch16_gap_256", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "image_size": 256 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/vit_relpos_medium_patch16_cls_224.json b/API_CLIP/clip_prs/utils/model_configs/vit_relpos_medium_patch16_cls_224.json new file mode 100644 index 0000000000000000000000000000000000000000..ed217b202d5e6071c5307f4547c97ff4cfe2abd1 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/vit_relpos_medium_patch16_cls_224.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "timm_model_name": "vit_relpos_medium_patch16_cls_224", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "image_size": 224 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/model_configs/xlm-roberta-base-ViT-B-32.json b/API_CLIP/clip_prs/utils/model_configs/xlm-roberta-base-ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..751bccc2c6fc41bc4ff20182de88d86739d518d9 --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/xlm-roberta-base-ViT-B-32.json @@ -0,0 +1,15 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "hf_model_name": "xlm-roberta-base", + "hf_tokenizer_name": "xlm-roberta-base", + "proj": "mlp", + "pooler_type": "mean_pooler" + } +} diff --git a/API_CLIP/clip_prs/utils/model_configs/xlm-roberta-large-ViT-H-14.json b/API_CLIP/clip_prs/utils/model_configs/xlm-roberta-large-ViT-H-14.json new file mode 100644 index 0000000000000000000000000000000000000000..31f271faa9bbb7a9da53900b483a4c00a16f3c4a --- /dev/null +++ b/API_CLIP/clip_prs/utils/model_configs/xlm-roberta-large-ViT-H-14.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 32, + "width": 1280, + "head_width": 80, + "patch_size": 14 + }, + "text_cfg": { + "hf_model_name": "xlm-roberta-large", + "hf_tokenizer_name": "xlm-roberta-large", + "proj": "mlp", + "pooler_type": "mean_pooler" + } +} diff --git a/API_CLIP/clip_prs/utils/modified_resnet.py b/API_CLIP/clip_prs/utils/modified_resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..3e220c232a464754d55ac8a49bd868b8fbb40153 --- /dev/null +++ b/API_CLIP/clip_prs/utils/modified_resnet.py @@ -0,0 +1,181 @@ +from collections import OrderedDict + +import torch +from torch import nn +from torch.nn import functional as F + +from utils.misc import freeze_batch_norm_2d + + +class Bottleneck(nn.Module): + expansion = 4 + + def __init__(self, inplanes, planes, stride=1): + super().__init__() + + # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1 + self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False) + self.bn1 = nn.BatchNorm2d(planes) + self.act1 = nn.ReLU(inplace=True) + + self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(planes) + self.act2 = nn.ReLU(inplace=True) + + self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity() + + self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False) + self.bn3 = nn.BatchNorm2d(planes * self.expansion) + self.act3 = nn.ReLU(inplace=True) + + self.downsample = None + self.stride = stride + + if stride > 1 or inplanes != planes * Bottleneck.expansion: + # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1 + self.downsample = nn.Sequential(OrderedDict([ + ("-1", nn.AvgPool2d(stride)), + ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)), + ("1", nn.BatchNorm2d(planes * self.expansion)) + ])) + + def forward(self, x: torch.Tensor): + identity = x + + out = self.act1(self.bn1(self.conv1(x))) + out = self.act2(self.bn2(self.conv2(out))) + out = self.avgpool(out) + out = self.bn3(self.conv3(out)) + + if self.downsample is not None: + identity = self.downsample(x) + + out += identity + out = self.act3(out) + return out + + +class AttentionPool2d(nn.Module): + def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None): + super().__init__() + self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5) + self.k_proj = nn.Linear(embed_dim, embed_dim) + self.q_proj = nn.Linear(embed_dim, embed_dim) + self.v_proj = nn.Linear(embed_dim, embed_dim) + self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim) + self.num_heads = num_heads + + def forward(self, x): + x = x.reshape(x.shape[0], x.shape[1], x.shape[2] * x.shape[3]).permute(2, 0, 1) # NCHW -> (HW)NC + x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC + x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC + x, _ = F.multi_head_attention_forward( + query=x, key=x, value=x, + embed_dim_to_check=x.shape[-1], + num_heads=self.num_heads, + q_proj_weight=self.q_proj.weight, + k_proj_weight=self.k_proj.weight, + v_proj_weight=self.v_proj.weight, + in_proj_weight=None, + in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]), + bias_k=None, + bias_v=None, + add_zero_attn=False, + dropout_p=0., + out_proj_weight=self.c_proj.weight, + out_proj_bias=self.c_proj.bias, + use_separate_proj_weight=True, + training=self.training, + need_weights=False + ) + + return x[0] + + +class ModifiedResNet(nn.Module): + """ + A ResNet class that is similar to torchvision's but contains the following changes: + - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool. + - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1 + - The final pooling layer is a QKV attention instead of an average pool + """ + + def __init__(self, layers, output_dim, heads, image_size=224, width=64): + super().__init__() + self.output_dim = output_dim + self.image_size = image_size + + # the 3-layer stem + self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False) + self.bn1 = nn.BatchNorm2d(width // 2) + self.act1 = nn.ReLU(inplace=True) + self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(width // 2) + self.act2 = nn.ReLU(inplace=True) + self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False) + self.bn3 = nn.BatchNorm2d(width) + self.act3 = nn.ReLU(inplace=True) + self.avgpool = nn.AvgPool2d(2) + + # residual layers + self._inplanes = width # this is a *mutable* variable used during construction + self.layer1 = self._make_layer(width, layers[0]) + self.layer2 = self._make_layer(width * 2, layers[1], stride=2) + self.layer3 = self._make_layer(width * 4, layers[2], stride=2) + self.layer4 = self._make_layer(width * 8, layers[3], stride=2) + + embed_dim = width * 32 # the ResNet feature dimension + self.attnpool = AttentionPool2d(image_size // 32, embed_dim, heads, output_dim) + + self.init_parameters() + + def _make_layer(self, planes, blocks, stride=1): + layers = [Bottleneck(self._inplanes, planes, stride)] + + self._inplanes = planes * Bottleneck.expansion + for _ in range(1, blocks): + layers.append(Bottleneck(self._inplanes, planes)) + + return nn.Sequential(*layers) + + def init_parameters(self): + if self.attnpool is not None: + std = self.attnpool.c_proj.in_features ** -0.5 + nn.init.normal_(self.attnpool.q_proj.weight, std=std) + nn.init.normal_(self.attnpool.k_proj.weight, std=std) + nn.init.normal_(self.attnpool.v_proj.weight, std=std) + nn.init.normal_(self.attnpool.c_proj.weight, std=std) + + for resnet_block in [self.layer1, self.layer2, self.layer3, self.layer4]: + for name, param in resnet_block.named_parameters(): + if name.endswith("bn3.weight"): + nn.init.zeros_(param) + + def lock(self, unlocked_groups=0, freeze_bn_stats=False): + assert unlocked_groups == 0, 'partial locking not currently supported for this model' + for param in self.parameters(): + param.requires_grad = False + if freeze_bn_stats: + freeze_batch_norm_2d(self) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + # FIXME support for non-transformer + pass + + def stem(self, x): + x = self.act1(self.bn1(self.conv1(x))) + x = self.act2(self.bn2(self.conv2(x))) + x = self.act3(self.bn3(self.conv3(x))) + x = self.avgpool(x) + return x + + def forward(self, x): + x = self.stem(x) + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + x = self.attnpool(x) + + return x \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/openai_models.py b/API_CLIP/clip_prs/utils/openai_models.py new file mode 100644 index 0000000000000000000000000000000000000000..f87bd0b0272b66600f69905a2a53a1ab4bf38e72 --- /dev/null +++ b/API_CLIP/clip_prs/utils/openai_models.py @@ -0,0 +1,90 @@ +""" OpenAI pretrained model functions + +Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. +""" + +import os +import warnings +from typing import List, Optional, Union + +import torch + +from utils.constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD +from utils.model import build_model_from_openai_state_dict, get_cast_dtype +from utils.pretrained import * + +__all__ = ["list_openai_models", "load_openai_model"] + + +def list_openai_models() -> List[str]: + """Returns the names of available CLIP models""" + return list_pretrained_models_by_tag('openai') + + +def load_openai_model( + name: str, + precision: Optional[str] = None, + device: Optional[Union[str, torch.device]] = None, + cache_dir: Optional[str] = None, +): + """Load a CLIP model + + Parameters + ---------- + name : str + A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict + precision: str + Model precision, if None defaults to 'fp32' if device == 'cpu' else 'fp16'. + device : Union[str, torch.device] + The device to put the loaded model + cache_dir : Optional[str] + The directory to cache the downloaded model weights + + Returns + ------- + model : torch.nn.Module + The CLIP model + preprocess : Callable[[PIL.Image], torch.Tensor] + A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input + """ + if device is None: + device = "cuda" if torch.cuda.is_available() else "cpu" + if precision is None: + precision = 'fp32' if device == 'cpu' else 'fp16' + + if get_pretrained_url(name, 'openai'): + model_path = download_pretrained_from_url(get_pretrained_url(name, 'openai'), cache_dir=cache_dir) + elif os.path.isfile(name): + model_path = name + else: + raise RuntimeError(f"Model {name} not found; available models = {list_openai_models()}") + + try: + # loading JIT archive + model = torch.jit.load(model_path, map_location="cpu").eval() + state_dict = None + except RuntimeError: + # loading saved state dict + state_dict = torch.load(model_path, map_location="cpu") + + # Build a non-jit model from the OpenAI jitted model state dict + cast_dtype = get_cast_dtype(precision) + try: + model = build_model_from_openai_state_dict(state_dict or model.state_dict(), cast_dtype=cast_dtype) + except KeyError: + sd = {k[7:]: v for k, v in state_dict["state_dict"].items()} + model = build_model_from_openai_state_dict(sd, cast_dtype=cast_dtype) + + # model from OpenAI state dict is in manually cast fp16 mode, must be converted for AMP/fp32/bf16 use + model = model.to(device) + # FIXME support pure fp16/bf16 precision modes + if precision != 'fp16': + model.float() + if precision == 'bf16': + # for bf16, convert back to low-precision + convert_weights_to_lp(model, dtype=torch.bfloat16) + + # add mean / std attributes for consistency with OpenCLIP models + model.visual.image_mean = OPENAI_DATASET_MEAN + model.visual.image_std = OPENAI_DATASET_STD + return model \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/openai_templates.py b/API_CLIP/clip_prs/utils/openai_templates.py new file mode 100644 index 0000000000000000000000000000000000000000..66d9faa9bd814967266c7edf41ccc258a182b1c7 --- /dev/null +++ b/API_CLIP/clip_prs/utils/openai_templates.py @@ -0,0 +1,84 @@ + +OPENAI_IMAGENET_TEMPLATES = ( + lambda c: f'a bad photo of a {c}.', + lambda c: f'a photo of many {c}.', + lambda c: f'a sculpture of a {c}.', + lambda c: f'a photo of the hard to see {c}.', + lambda c: f'a low resolution photo of the {c}.', + lambda c: f'a rendering of a {c}.', + lambda c: f'graffiti of a {c}.', + lambda c: f'a bad photo of the {c}.', + lambda c: f'a cropped photo of the {c}.', + lambda c: f'a tattoo of a {c}.', + lambda c: f'the embroidered {c}.', + lambda c: f'a photo of a hard to see {c}.', + lambda c: f'a bright photo of a {c}.', + lambda c: f'a photo of a clean {c}.', + lambda c: f'a photo of a dirty {c}.', + lambda c: f'a dark photo of the {c}.', + lambda c: f'a drawing of a {c}.', + lambda c: f'a photo of my {c}.', + lambda c: f'the plastic {c}.', + lambda c: f'a photo of the cool {c}.', + lambda c: f'a close-up photo of a {c}.', + lambda c: f'a black and white photo of the {c}.', + lambda c: f'a painting of the {c}.', + lambda c: f'a painting of a {c}.', + lambda c: f'a pixelated photo of the {c}.', + lambda c: f'a sculpture of the {c}.', + lambda c: f'a bright photo of the {c}.', + lambda c: f'a cropped photo of a {c}.', + lambda c: f'a plastic {c}.', + lambda c: f'a photo of the dirty {c}.', + lambda c: f'a jpeg corrupted photo of a {c}.', + lambda c: f'a blurry photo of the {c}.', + lambda c: f'a photo of the {c}.', + lambda c: f'a good photo of the {c}.', + lambda c: f'a rendering of the {c}.', + lambda c: f'a {c} in a video game.', + lambda c: f'a photo of one {c}.', + lambda c: f'a doodle of a {c}.', + lambda c: f'a close-up photo of the {c}.', + lambda c: f'a photo of a {c}.', + lambda c: f'the origami {c}.', + lambda c: f'the {c} in a video game.', + lambda c: f'a sketch of a {c}.', + lambda c: f'a doodle of the {c}.', + lambda c: f'a origami {c}.', + lambda c: f'a low resolution photo of a {c}.', + lambda c: f'the toy {c}.', + lambda c: f'a rendition of the {c}.', + lambda c: f'a photo of the clean {c}.', + lambda c: f'a photo of a large {c}.', + lambda c: f'a rendition of a {c}.', + lambda c: f'a photo of a nice {c}.', + lambda c: f'a photo of a weird {c}.', + lambda c: f'a blurry photo of a {c}.', + lambda c: f'a cartoon {c}.', + lambda c: f'art of a {c}.', + lambda c: f'a sketch of the {c}.', + lambda c: f'a embroidered {c}.', + lambda c: f'a pixelated photo of a {c}.', + lambda c: f'itap of the {c}.', + lambda c: f'a jpeg corrupted photo of the {c}.', + lambda c: f'a good photo of a {c}.', + lambda c: f'a plushie {c}.', + lambda c: f'a photo of the nice {c}.', + lambda c: f'a photo of the small {c}.', + lambda c: f'a photo of the weird {c}.', + lambda c: f'the cartoon {c}.', + lambda c: f'art of the {c}.', + lambda c: f'a drawing of the {c}.', + lambda c: f'a photo of the large {c}.', + lambda c: f'a black and white photo of a {c}.', + lambda c: f'the plushie {c}.', + lambda c: f'a dark photo of a {c}.', + lambda c: f'itap of a {c}.', + lambda c: f'graffiti of the {c}.', + lambda c: f'a toy {c}.', + lambda c: f'itap of my {c}.', + lambda c: f'a photo of a cool {c}.', + lambda c: f'a photo of a small {c}.', + lambda c: f'a tattoo of the {c}.', +) + diff --git a/API_CLIP/clip_prs/utils/pretrained.py b/API_CLIP/clip_prs/utils/pretrained.py new file mode 100644 index 0000000000000000000000000000000000000000..48567fd1a46147c5c0c091a8731bd430042bd3cc --- /dev/null +++ b/API_CLIP/clip_prs/utils/pretrained.py @@ -0,0 +1,426 @@ +import hashlib +import os +import urllib +import warnings +from functools import partial +from typing import Dict, Union + +from tqdm import tqdm + + +try: + from huggingface_hub import hf_hub_download + hf_hub_download = partial(hf_hub_download, library_name="open_clip", library_version='2.20.0') + _has_hf_hub = True +except ImportError: + hf_hub_download = None + _has_hf_hub = False + + +def _pcfg(url='', hf_hub='', mean=None, std=None): + return dict( + url=url, + hf_hub=hf_hub, + mean=mean, + std=std, + ) + + +_RN50 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt"), + yfcc15m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-yfcc15m-455df137.pt"), + cc12m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-cc12m-f000538c.pt"), +) + +_RN50_quickgelu = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt"), + yfcc15m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-yfcc15m-455df137.pt"), + cc12m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-cc12m-f000538c.pt"), +) + +_RN101 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt"), + yfcc15m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn101-quickgelu-yfcc15m-3e04b30e.pt"), +) + +_RN101_quickgelu = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt"), + yfcc15m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn101-quickgelu-yfcc15m-3e04b30e.pt"), +) + +_RN50x4 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt"), +) + +_RN50x16 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt"), +) + +_RN50x64 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt"), +) + +_VITB32 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e31-d867053b.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e32-46683a32.pt"), + laion2b_e16=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-laion2b_e16-af8dbd0c.pth"), + laion2b_s34b_b79k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-laion2B-s34B-b79K/'), + # DataComp-M models + datacomp_m_s128m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-DataComp.M-s128M-b4K/'), + commonpool_m_clip_s128m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.M.clip-s128M-b4K/'), + commonpool_m_laion_s128m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.M.laion-s128M-b4K/'), + commonpool_m_image_s128m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.M.image-s128M-b4K/'), + commonpool_m_text_s128m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.M.text-s128M-b4K/'), + commonpool_m_basic_s128m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.M.basic-s128M-b4K/'), + commonpool_m_s128m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.M-s128M-b4K/'), + # DataComp-S models + datacomp_s_s13m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-DataComp.S-s13M-b4K/'), + commonpool_s_clip_s13m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.S.clip-s13M-b4K/'), + commonpool_s_laion_s13m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.S.laion-s13M-b4K/'), + commonpool_s_image_s13m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.S.image-s13M-b4K/'), + commonpool_s_text_s13m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.S.text-s13M-b4K/'), + commonpool_s_basic_s13m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.S.basic-s13M-b4K/'), + commonpool_s_s13m_b4k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-CommonPool.S-s13M-b4K/'), +) + +_VITB32_quickgelu = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e31-d867053b.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e32-46683a32.pt"), +) + +_VITB16 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16-laion400m_e31-00efa78f.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16-laion400m_e32-55e67d44.pt"), + laion2b_s34b_b88k=_pcfg(hf_hub='laion/CLIP-ViT-B-16-laion2B-s34B-b88K/'), + # DataComp-L models + datacomp_l_s1b_b8k=_pcfg(hf_hub='laion/CLIP-ViT-B-16-DataComp.L-s1B-b8K/'), + commonpool_l_clip_s1b_b8k=_pcfg(hf_hub='laion/CLIP-ViT-B-16-CommonPool.L.clip-s1B-b8K/'), + commonpool_l_laion_s1b_b8k=_pcfg(hf_hub='laion/CLIP-ViT-B-16-CommonPool.L.laion-s1B-b8K/'), + commonpool_l_image_s1b_b8k=_pcfg(hf_hub='laion/CLIP-ViT-B-16-CommonPool.L.image-s1B-b8K/'), + commonpool_l_text_s1b_b8k=_pcfg(hf_hub='laion/CLIP-ViT-B-16-CommonPool.L.text-s1B-b8K/'), + commonpool_l_basic_s1b_b8k=_pcfg(hf_hub='laion/CLIP-ViT-B-16-CommonPool.L.basic-s1B-b8K/'), + commonpool_l_s1b_b8k=_pcfg(hf_hub='laion/CLIP-ViT-B-16-CommonPool.L-s1B-b8K/'), +) + +_VITB16_PLUS_240 = dict( + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16_plus_240-laion400m_e31-8fb26589.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16_plus_240-laion400m_e32-699c4b84.pt"), +) + +_VITL14 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_l_14-laion400m_e31-69988bb6.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_l_14-laion400m_e32-3d133497.pt"), + laion2b_s32b_b82k=_pcfg( + hf_hub='laion/CLIP-ViT-L-14-laion2B-s32B-b82K/', + mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), + # DataComp-XL models + datacomp_xl_s13b_b90k=_pcfg(hf_hub='laion/CLIP-ViT-L-14-DataComp.XL-s13B-b90K/'), + commonpool_xl_clip_s13b_b90k=_pcfg(hf_hub='laion/CLIP-ViT-L-14-CommonPool.XL.clip-s13B-b90K/'), + commonpool_xl_laion_s13b_b90k=_pcfg(hf_hub='laion/CLIP-ViT-L-14-CommonPool.XL.laion-s13B-b90K/'), + commonpool_xl_s13b_b90k=_pcfg(hf_hub='laion/CLIP-ViT-L-14-CommonPool.XL-s13B-b90K/'), +) + +_VITL14_336 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt"), +) + +_VITH14 = dict( + laion2b_s32b_b79k=_pcfg(hf_hub='laion/CLIP-ViT-H-14-laion2B-s32B-b79K/'), +) + +_VITg14 = dict( + laion2b_s12b_b42k=_pcfg(hf_hub='laion/CLIP-ViT-g-14-laion2B-s12B-b42K/'), + laion2b_s34b_b88k=_pcfg(hf_hub='laion/CLIP-ViT-g-14-laion2B-s34B-b88K/'), +) + +_VITbigG14 = dict( + laion2b_s39b_b160k=_pcfg(hf_hub='laion/CLIP-ViT-bigG-14-laion2B-39B-b160k/'), +) + +_robertaViTB32 = dict( + laion2b_s12b_b32k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-roberta-base-laion2B-s12B-b32k/'), +) + +_xlmRobertaBaseViTB32 = dict( + laion5b_s13b_b90k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-xlm-roberta-base-laion5B-s13B-b90k/'), +) + +_xlmRobertaLargeFrozenViTH14 = dict( + frozen_laion5b_s13b_b90k=_pcfg(hf_hub='laion/CLIP-ViT-H-14-frozen-xlm-roberta-large-laion5B-s13B-b90k/'), +) + +_convnext_base = dict( + laion400m_s13b_b51k=_pcfg(hf_hub='laion/CLIP-convnext_base-laion400M-s13B-b51K/'), +) + +_convnext_base_w = dict( + laion2b_s13b_b82k=_pcfg(hf_hub='laion/CLIP-convnext_base_w-laion2B-s13B-b82K/'), + laion2b_s13b_b82k_augreg=_pcfg(hf_hub='laion/CLIP-convnext_base_w-laion2B-s13B-b82K-augreg/'), + laion_aesthetic_s13b_b82k=_pcfg(hf_hub='laion/CLIP-convnext_base_w-laion_aesthetic-s13B-b82K/'), +) + +_convnext_base_w_320 = dict( + laion_aesthetic_s13b_b82k=_pcfg(hf_hub='laion/CLIP-convnext_base_w_320-laion_aesthetic-s13B-b82K/'), + laion_aesthetic_s13b_b82k_augreg=_pcfg(hf_hub='laion/CLIP-convnext_base_w_320-laion_aesthetic-s13B-b82K-augreg/'), +) + +_convnext_large_d = dict( + laion2b_s26b_b102k_augreg=_pcfg(hf_hub='laion/CLIP-convnext_large_d.laion2B-s26B-b102K-augreg/'), +) + +_convnext_large_d_320 = dict( + laion2b_s29b_b131k_ft=_pcfg(hf_hub='laion/CLIP-convnext_large_d_320.laion2B-s29B-b131K-ft/'), + laion2b_s29b_b131k_ft_soup=_pcfg(hf_hub='laion/CLIP-convnext_large_d_320.laion2B-s29B-b131K-ft-soup/'), +) + +_convnext_xxlarge = dict( + laion2b_s34b_b82k_augreg=_pcfg(hf_hub='laion/CLIP-convnext_xxlarge-laion2B-s34B-b82K-augreg/'), + laion2b_s34b_b82k_augreg_rewind=_pcfg(hf_hub='laion/CLIP-convnext_xxlarge-laion2B-s34B-b82K-augreg-rewind/'), + laion2b_s34b_b82k_augreg_soup=_pcfg(hf_hub='laion/CLIP-convnext_xxlarge-laion2B-s34B-b82K-augreg-soup/'), +) + +_coca_VITB32 = dict( + laion2b_s13b_b90k=_pcfg(hf_hub='laion/CoCa-ViT-B-32-laion2B-s13B-b90k/'), + mscoco_finetuned_laion2b_s13b_b90k=_pcfg(hf_hub='laion/mscoco_finetuned_CoCa-ViT-B-32-laion2B-s13B-b90k/') +) + +_coca_VITL14 = dict( + laion2b_s13b_b90k=_pcfg(hf_hub='laion/CoCa-ViT-L-14-laion2B-s13B-b90k/'), + mscoco_finetuned_laion2b_s13b_b90k=_pcfg(hf_hub='laion/mscoco_finetuned_CoCa-ViT-L-14-laion2B-s13B-b90k/') +) + + +_PRETRAINED = { + "RN50": _RN50, + "RN50-quickgelu": _RN50_quickgelu, + "RN101": _RN101, + "RN101-quickgelu": _RN101_quickgelu, + "RN50x4": _RN50x4, + "RN50x16": _RN50x16, + "RN50x64": _RN50x64, + "ViT-B-32": _VITB32, + "ViT-B-32-quickgelu": _VITB32_quickgelu, + "ViT-B-16": _VITB16, + "ViT-B-16-plus-240": _VITB16_PLUS_240, + "ViT-L-14": _VITL14, + "ViT-L-14-336": _VITL14_336, + "ViT-H-14": _VITH14, + "ViT-g-14": _VITg14, + "ViT-bigG-14": _VITbigG14, + "roberta-ViT-B-32": _robertaViTB32, + "xlm-roberta-base-ViT-B-32": _xlmRobertaBaseViTB32, + "xlm-roberta-large-ViT-H-14": _xlmRobertaLargeFrozenViTH14, + "convnext_base": _convnext_base, + "convnext_base_w": _convnext_base_w, + "convnext_base_w_320": _convnext_base_w_320, + "convnext_large_d": _convnext_large_d, + "convnext_large_d_320": _convnext_large_d_320, + "convnext_xxlarge": _convnext_xxlarge, + "coca_ViT-B-32": _coca_VITB32, + "coca_ViT-L-14": _coca_VITL14, + "EVA01-g-14": dict( + # from QuanSun/EVA-CLIP/EVA01_CLIP_g_14_psz14_s11B.pt + laion400m_s11b_b41k=_pcfg(hf_hub='timm/eva_giant_patch14_clip_224.laion400m_s11b_b41k/'), + ), + "EVA01-g-14-plus": dict( + # from QuanSun/EVA-CLIP/EVA01_CLIP_g_14_plus_psz14_s11B.pt + merged2b_s11b_b114k=_pcfg(hf_hub='timm/eva_giant_patch14_plus_clip_224.merged2b_s11b_b114k/'), + ), + "EVA02-B-16": dict( + # from QuanSun/EVA-CLIP/EVA02_CLIP_B_psz16_s8B.pt + merged2b_s8b_b131k=_pcfg(hf_hub='timm/eva02_base_patch16_clip_224.merged2b_s8b_b131k/'), + ), + "EVA02-L-14": dict( + # from QuanSun/EVA-CLIP/EVA02_CLIP_L_psz14_s4B.pt + merged2b_s4b_b131k=_pcfg(hf_hub='timm/eva02_large_patch14_clip_224.merged2b_s4b_b131k/'), + ), + "EVA02-L-14-336": dict( + # from QuanSun/EVA-CLIP/EVA02_CLIP_L_336_psz14_s6B.pt + merged2b_s6b_b61k=_pcfg(hf_hub='timm/eva02_large_patch14_clip_336.merged2b_s6b_b61k/'), + ), + "EVA02-E-14": dict( + # from QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_s4B.pt + laion2b_s4b_b115k=_pcfg(hf_hub='timm/eva02_enormous_patch14_clip_224.laion2b_s4b_b115k/'), + ), + "EVA02-E-14-plus": dict( + # from QuanSun/EVA-CLIP/EVA02_CLIP_E_psz14_plus_s9B.pt + laion2b_s9b_b144k=_pcfg(hf_hub='timm/eva02_enormous_patch14_plus_clip_224.laion2b_s9b_b144k/'), + ) +} + + +def _clean_tag(tag: str): + # normalize pretrained tags + return tag.lower().replace('-', '_') + + +def list_pretrained(as_str: bool = False): + """ returns list of pretrained models + Returns a tuple (model_name, pretrain_tag) by default or 'name:tag' if as_str == True + """ + return [':'.join([k, t]) if as_str else (k, t) for k in _PRETRAINED.keys() for t in _PRETRAINED[k].keys()] + + +def list_pretrained_models_by_tag(tag: str): + """ return all models having the specified pretrain tag """ + models = [] + tag = _clean_tag(tag) + for k in _PRETRAINED.keys(): + if tag in _PRETRAINED[k]: + models.append(k) + return models + + +def list_pretrained_tags_by_model(model: str): + """ return all pretrain tags for the specified model architecture """ + tags = [] + if model in _PRETRAINED: + tags.extend(_PRETRAINED[model].keys()) + return tags + + +def is_pretrained_cfg(model: str, tag: str): + if model not in _PRETRAINED: + return False + return _clean_tag(tag) in _PRETRAINED[model] + + +def get_pretrained_cfg(model: str, tag: str): + if model not in _PRETRAINED: + return {} + model_pretrained = _PRETRAINED[model] + return model_pretrained.get(_clean_tag(tag), {}) + + +def get_pretrained_url(model: str, tag: str): + cfg = get_pretrained_cfg(model, _clean_tag(tag)) + return cfg.get('url', '') + + +def download_pretrained_from_url( + url: str, + cache_dir: Union[str, None] = None, +): + if not cache_dir: + cache_dir = os.path.expanduser("~/.cache/clip") + os.makedirs(cache_dir, exist_ok=True) + filename = os.path.basename(url) + + if 'openaipublic' in url: + expected_sha256 = url.split("/")[-2] + elif 'mlfoundations' in url: + expected_sha256 = os.path.splitext(filename)[0].split("-")[-1] + else: + expected_sha256 = '' + + download_target = os.path.join(cache_dir, filename) + + if os.path.exists(download_target) and not os.path.isfile(download_target): + raise RuntimeError(f"{download_target} exists and is not a regular file") + + if os.path.isfile(download_target): + if expected_sha256: + if hashlib.sha256(open(download_target, "rb").read()).hexdigest().startswith(expected_sha256): + return download_target + else: + warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file") + else: + return download_target + + with urllib.request.urlopen(url) as source, open(download_target, "wb") as output: + with tqdm(total=int(source.headers.get("Content-Length")), ncols=80, unit='iB', unit_scale=True) as loop: + while True: + buffer = source.read(8192) + if not buffer: + break + + output.write(buffer) + loop.update(len(buffer)) + + if expected_sha256 and not hashlib.sha256(open(download_target, "rb").read()).hexdigest().startswith(expected_sha256): + raise RuntimeError(f"Model has been downloaded but the SHA256 checksum does not not match") + + return download_target + + +def has_hf_hub(necessary=False): + if not _has_hf_hub and necessary: + # if no HF Hub module installed, and it is necessary to continue, raise error + raise RuntimeError( + 'Hugging Face hub model specified but package not installed. Run `pip install huggingface_hub`.') + return _has_hf_hub + + +def download_pretrained_from_hf( + model_id: str, + filename: str = 'open_clip_pytorch_model.bin', + revision=None, + cache_dir: Union[str, None] = None, +): + has_hf_hub(True) + cached_file = hf_hub_download(model_id, filename, revision=revision, cache_dir=cache_dir) + return cached_file + + +def download_pretrained( + cfg: Dict, + force_hf_hub: bool = False, + cache_dir: Union[str, None] = None, +): + target = '' + if not cfg: + return target + + download_url = cfg.get('url', '') + download_hf_hub = cfg.get('hf_hub', '') + if download_hf_hub and force_hf_hub: + # use HF hub even if url exists + download_url = '' + + if download_url: + target = download_pretrained_from_url(download_url, cache_dir=cache_dir) + elif download_hf_hub: + has_hf_hub(True) + # we assume the hf_hub entries in pretrained config combine model_id + filename in + # 'org/model_name/filename.pt' form. To specify just the model id w/o filename and + # use 'open_clip_pytorch_model.bin' default, there must be a trailing slash 'org/model_name/'. + model_id, filename = os.path.split(download_hf_hub) + if filename: + target = download_pretrained_from_hf(model_id, filename=filename, cache_dir=cache_dir) + else: + target = download_pretrained_from_hf(model_id, cache_dir=cache_dir) + + return target \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/segmentation_utils.py b/API_CLIP/clip_prs/utils/segmentation_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e286e0a4d3255952ef2d501b6ac8571cd72cb7f6 --- /dev/null +++ b/API_CLIP/clip_prs/utils/segmentation_utils.py @@ -0,0 +1,682 @@ +import torch +import matplotlib.cm +import skimage.io +import skimage.feature +import skimage.filters +import numpy as np +import os +from collections import OrderedDict +import glob +from sklearn.metrics import f1_score, average_precision_score +from sklearn.metrics import precision_recall_curve, roc_curve + +SMOOTH = 1e-6 + + +def get_iou(outputs: torch.Tensor, labels: torch.Tensor): + # You can comment out this line if you are passing tensors of equal shape + # But if you are passing output from UNet or something it will most probably + # be with the BATCH x 1 x H x W shape + outputs = outputs.squeeze(1) # BATCH x 1 x H x W => BATCH x H x W + labels = labels.squeeze(1) # BATCH x 1 x H x W => BATCH x H x W + + intersection = (outputs & labels).float().sum((1, 2)) # Will be zero if Truth=0 or Prediction=0 + union = (outputs | labels).float().sum((1, 2)) # Will be zzero if both are 0 + + iou = (intersection + SMOOTH) / (union + SMOOTH) # We smooth our devision to avoid 0/0 + + return iou.cpu().numpy() + + +def get_f1_scores(predict, target, ignore_index=-1): + # Tensor process + batch_size = predict.shape[0] + predict = predict.data.cpu().numpy().reshape(-1) + target = target.data.cpu().numpy().reshape(-1) + pb = predict[target != ignore_index].reshape(batch_size, -1) + tb = target[target != ignore_index].reshape(batch_size, -1) + + total = [] + for p, t in zip(pb, tb): + total.append(np.nan_to_num(f1_score(t, p))) + + return total + + +def get_roc(predict, target, ignore_index=-1): + target_expand = target.unsqueeze(1).expand_as(predict) + target_expand_numpy = target_expand.data.cpu().numpy().reshape(-1) + # Tensor process + x = torch.zeros_like(target_expand) + t = target.unsqueeze(1).clamp(min=0) + target_1hot = x.scatter_(1, t, 1) + batch_size = predict.shape[0] + predict = predict.data.cpu().numpy().reshape(-1) + target = target_1hot.data.cpu().numpy().reshape(-1) + pb = predict[target_expand_numpy != ignore_index].reshape(batch_size, -1) + tb = target[target_expand_numpy != ignore_index].reshape(batch_size, -1) + + total = [] + for p, t in zip(pb, tb): + total.append(roc_curve(t, p)) + + return total + + +def get_pr(predict, target, ignore_index=-1): + target_expand = target.unsqueeze(1).expand_as(predict) + target_expand_numpy = target_expand.data.cpu().numpy().reshape(-1) + # Tensor process + x = torch.zeros_like(target_expand) + t = target.unsqueeze(1).clamp(min=0) + target_1hot = x.scatter_(1, t, 1) + batch_size = predict.shape[0] + predict = predict.data.cpu().numpy().reshape(-1) + target = target_1hot.data.cpu().numpy().reshape(-1) + pb = predict[target_expand_numpy != ignore_index].reshape(batch_size, -1) + tb = target[target_expand_numpy != ignore_index].reshape(batch_size, -1) + + total = [] + for p, t in zip(pb, tb): + total.append(precision_recall_curve(t, p)) + + return total + + +def get_ap_scores(predict, target, ignore_index=-1): + total = [] + for pred, tgt in zip(predict, target): + target_expand = tgt.unsqueeze(0).expand_as(pred) + target_expand_numpy = target_expand.data.cpu().numpy().reshape(-1) + + # Tensor process + x = torch.zeros_like(target_expand) + t = tgt.unsqueeze(0).clamp(min=0).long() + target_1hot = x.scatter_(0, t, 1) + predict_flat = pred.data.cpu().numpy().reshape(-1) + target_flat = target_1hot.data.cpu().numpy().reshape(-1) + + p = predict_flat[target_expand_numpy != ignore_index] + t = target_flat[target_expand_numpy != ignore_index] + + total.append(np.nan_to_num(average_precision_score(t, p))) + + return total + + +def get_ap_multiclass(predict, target): + total = [] + for pred, tgt in zip(predict, target): + predict_flat = pred.data.cpu().numpy().reshape(-1) + target_flat = tgt.data.cpu().numpy().reshape(-1) + + total.append(np.nan_to_num(average_precision_score(target_flat, predict_flat))) + + return total + + +def batch_precision_recall(predict, target, thr=0.5): + """Batch Precision Recall + Args: + predict: input 4D tensor + target: label 4D tensor + """ + # _, predict = torch.max(predict, 1) + + predict = predict > thr + predict = predict.data.cpu().numpy() + 1 + target = target.data.cpu().numpy() + 1 + + tp = np.sum(((predict == 2) * (target == 2)) * (target > 0)) + fp = np.sum(((predict == 2) * (target == 1)) * (target > 0)) + fn = np.sum(((predict == 1) * (target == 2)) * (target > 0)) + + precision = float(np.nan_to_num(tp / (tp + fp))) + recall = float(np.nan_to_num(tp / (tp + fn))) + + return precision, recall + + +def batch_pix_accuracy(predict, target): + """Batch Pixel Accuracy + Args: + predict: input 3D tensor + target: label 3D tensor + """ + + # for thr in np.linspace(0, 1, slices): + + _, predict = torch.max(predict, 0) + predict = predict.cpu().numpy() + 1 + target = target.cpu().numpy() + 1 + pixel_labeled = np.sum(target > 0) + pixel_correct = np.sum((predict == target) * (target > 0)) + assert pixel_correct <= pixel_labeled, \ + "Correct area should be smaller than Labeled" + return pixel_correct, pixel_labeled + + +def batch_intersection_union(predict, target, nclass): + """Batch Intersection of Union + Args: + predict: input 3D tensor + target: label 3D tensor + nclass: number of categories (int) + """ + _, predict = torch.max(predict, 0) + mini = 1 + maxi = nclass + nbins = nclass + predict = predict.cpu().numpy() + 1 + target = target.cpu().numpy() + 1 + + predict = predict * (target > 0).astype(predict.dtype) + intersection = predict * (predict == target) + # areas of intersection and union + area_inter, _ = np.histogram(intersection, bins=nbins, range=(mini, maxi)) + area_pred, _ = np.histogram(predict, bins=nbins, range=(mini, maxi)) + area_lab, _ = np.histogram(target, bins=nbins, range=(mini, maxi)) + area_union = area_pred + area_lab - area_inter + assert (area_inter <= area_union).all(), \ + "Intersection area should be smaller than Union area" + return area_inter, area_union + + +def pixel_accuracy(im_pred, im_lab): + # ref https://github.com/CSAILVision/sceneparsing/blob/master/evaluationCode/utils_eval.py + im_pred = np.asarray(im_pred) + im_lab = np.asarray(im_lab) + + # Remove classes from unlabeled pixels in gt image. + # We should not penalize detections in unlabeled portions of the image. + pixel_labeled = np.sum(im_lab > 0) + pixel_correct = np.sum((im_pred == im_lab) * (im_lab > 0)) + # pixel_accuracy = 1.0 * pixel_correct / pixel_labeled + return pixel_correct, pixel_labeled + + +def intersection_and_union(im_pred, im_lab, num_class): + im_pred = np.asarray(im_pred) + im_lab = np.asarray(im_lab) + # Remove classes from unlabeled pixels in gt image. + im_pred = im_pred * (im_lab > 0) + # Compute area intersection: + intersection = im_pred * (im_pred == im_lab) + area_inter, _ = np.histogram(intersection, bins=num_class - 1, + range=(1, num_class - 1)) + # Compute area union: + area_pred, _ = np.histogram(im_pred, bins=num_class - 1, + range=(1, num_class - 1)) + area_lab, _ = np.histogram(im_lab, bins=num_class - 1, + range=(1, num_class - 1)) + area_union = area_pred + area_lab - area_inter + return area_inter, area_union + + +class Saver(object): + def __init__(self, args): + self.args = args + self.directory = os.path.join('run', args.train_dataset, args.model) + self.runs = sorted(glob.glob(os.path.join(self.directory, 'experiment_*'))) + run_id = int(self.runs[-1].split('_')[-1]) + 1 if self.runs else 0 + + self.experiment_dir = os.path.join(self.directory, 'experiment_{}'.format(str(run_id))) + if not os.path.exists(self.experiment_dir): + os.makedirs(self.experiment_dir) + + def save_checkpoint(self, state, filename='checkpoint.pth.tar'): + """Saves checkpoint to disk""" + filename = os.path.join(self.experiment_dir, filename) + torch.save(state, filename) + + def save_experiment_config(self): + logfile = os.path.join(self.experiment_dir, 'parameters.txt') + log_file = open(logfile, 'w') + p = OrderedDict() + p['train_dataset'] = self.args.train_dataset + p['lr'] = self.args.lr + p['epoch'] = self.args.epochs + + for key, val in p.items(): + log_file.write(key + ':' + str(val) + '\n') + log_file.close() + + +class Metric(object): + """Base class for all metrics. + From: https://github.com/pytorch/tnt/blob/master/torchnet/meter/meter.py + """ + def reset(self): + pass + + def add(self): + pass + + def value(self): + pass + + +class ConfusionMatrix(Metric): + """Constructs a confusion matrix for a multi-class classification problems. + Does not support multi-label, multi-class problems. + Keyword arguments: + - num_classes (int): number of classes in the classification problem. + - normalized (boolean, optional): Determines whether or not the confusion + matrix is normalized or not. Default: False. + Modified from: https://github.com/pytorch/tnt/blob/master/torchnet/meter/confusionmeter.py + """ + + def __init__(self, num_classes, normalized=False): + super().__init__() + + self.conf = np.ndarray((num_classes, num_classes), dtype=np.int32) + self.normalized = normalized + self.num_classes = num_classes + self.reset() + + def reset(self): + self.conf.fill(0) + + def add(self, predicted, target): + """Computes the confusion matrix + The shape of the confusion matrix is K x K, where K is the number + of classes. + Keyword arguments: + - predicted (Tensor or numpy.ndarray): Can be an N x K tensor/array of + predicted scores obtained from the model for N examples and K classes, + or an N-tensor/array of integer values between 0 and K-1. + - target (Tensor or numpy.ndarray): Can be an N x K tensor/array of + ground-truth classes for N examples and K classes, or an N-tensor/array + of integer values between 0 and K-1. + """ + # If target and/or predicted are tensors, convert them to numpy arrays + if torch.is_tensor(predicted): + predicted = predicted.cpu().numpy() + if torch.is_tensor(target): + target = target.cpu().numpy() + + assert predicted.shape[0] == target.shape[0], \ + 'number of targets and predicted outputs do not match' + + if np.ndim(predicted) != 1: + assert predicted.shape[1] == self.num_classes, \ + 'number of predictions does not match size of confusion matrix' + predicted = np.argmax(predicted, 1) + else: + assert (predicted.max() < self.num_classes) and (predicted.min() >= 0), \ + 'predicted values are not between 0 and k-1' + + if np.ndim(target) != 1: + assert target.shape[1] == self.num_classes, \ + 'Onehot target does not match size of confusion matrix' + assert (target >= 0).all() and (target <= 1).all(), \ + 'in one-hot encoding, target values should be 0 or 1' + assert (target.sum(1) == 1).all(), \ + 'multi-label setting is not supported' + target = np.argmax(target, 1) + else: + assert (target.max() < self.num_classes) and (target.min() >= 0), \ + 'target values are not between 0 and k-1' + + # hack for bincounting 2 arrays together + x = predicted + self.num_classes * target + bincount_2d = np.bincount( + x.astype(np.int32), minlength=self.num_classes**2) + assert bincount_2d.size == self.num_classes**2 + conf = bincount_2d.reshape((self.num_classes, self.num_classes)) + + self.conf += conf + + def value(self): + """ + Returns: + Confustion matrix of K rows and K columns, where rows corresponds + to ground-truth targets and columns corresponds to predicted + targets. + """ + if self.normalized: + conf = self.conf.astype(np.float32) + return conf / conf.sum(1).clip(min=1e-12)[:, None] + else: + return self.conf + + +def vec2im(V, shape=()): + ''' + Transform an array V into a specified shape - or if no shape is given assume a square output format. + + Parameters + ---------- + + V : numpy.ndarray + an array either representing a matrix or vector to be reshaped into an two-dimensional image + + shape : tuple or list + optional. containing the shape information for the output array if not given, the output is assumed to be square + + Returns + ------- + + W : numpy.ndarray + with W.shape = shape or W.shape = [np.sqrt(V.size)]*2 + + ''' + + if len(shape) < 2: + shape = [np.sqrt(V.size)] * 2 + shape = map(int, shape) + return np.reshape(V, shape) + + +def enlarge_image(img, scaling=3): + ''' + Enlarges a given input matrix by replicating each pixel value scaling times in horizontal and vertical direction. + + Parameters + ---------- + + img : numpy.ndarray + array of shape [H x W] OR [H x W x D] + + scaling : int + positive integer value > 0 + + Returns + ------- + + out : numpy.ndarray + two-dimensional array of shape [scaling*H x scaling*W] + OR + three-dimensional array of shape [scaling*H x scaling*W x D] + depending on the dimensionality of the input + ''' + + if scaling < 1 or not isinstance(scaling, int): + print('scaling factor needs to be an int >= 1') + + if len(img.shape) == 2: + H, W = img.shape + + out = np.zeros((scaling * H, scaling * W)) + for h in range(H): + fh = scaling * h + for w in range(W): + fw = scaling * w + out[fh:fh + scaling, fw:fw + scaling] = img[h, w] + + elif len(img.shape) == 3: + H, W, D = img.shape + + out = np.zeros((scaling * H, scaling * W, D)) + for h in range(H): + fh = scaling * h + for w in range(W): + fw = scaling * w + out[fh:fh + scaling, fw:fw + scaling, :] = img[h, w, :] + + return out + + +def repaint_corner_pixels(rgbimg, scaling=3): + ''' + DEPRECATED/OBSOLETE. + + Recolors the top left and bottom right pixel (groups) with the average rgb value of its three neighboring pixel (groups). + The recoloring visually masks the opposing pixel values which are a product of stabilizing the scaling. + Assumes those image ares will pretty much never show evidence. + + Parameters + ---------- + + rgbimg : numpy.ndarray + array of shape [H x W x 3] + + scaling : int + positive integer value > 0 + + Returns + ------- + + rgbimg : numpy.ndarray + three-dimensional array of shape [scaling*H x scaling*W x 3] + ''' + + # top left corner. + rgbimg[0:scaling, 0:scaling, :] = (rgbimg[0, scaling, :] + rgbimg[scaling, 0, :] + rgbimg[scaling, scaling, + :]) / 3.0 + # bottom right corner + rgbimg[-scaling:, -scaling:, :] = (rgbimg[-1, -1 - scaling, :] + rgbimg[-1 - scaling, -1, :] + rgbimg[-1 - scaling, + -1 - scaling, + :]) / 3.0 + return rgbimg + + +def digit_to_rgb(X, scaling=3, shape=(), cmap='binary'): + ''' + Takes as input an intensity array and produces a rgb image due to some color map + + Parameters + ---------- + + X : numpy.ndarray + intensity matrix as array of shape [M x N] + + scaling : int + optional. positive integer value > 0 + + shape: tuple or list of its , length = 2 + optional. if not given, X is reshaped to be square. + + cmap : str + name of color map of choice. default is 'binary' + + Returns + ------- + + image : numpy.ndarray + three-dimensional array of shape [scaling*H x scaling*W x 3] , where H*W == M*N + ''' + + # create color map object from name string + cmap = eval('matplotlib.cm.{}'.format(cmap)) + + image = enlarge_image(vec2im(X, shape), scaling) # enlarge + image = cmap(image.flatten())[..., 0:3].reshape([image.shape[0], image.shape[1], 3]) # colorize, reshape + + return image + + +def hm_to_rgb(R, X=None, scaling=3, shape=(), sigma=2, cmap='bwr', normalize=True): + ''' + Takes as input an intensity array and produces a rgb image for the represented heatmap. + optionally draws the outline of another input on top of it. + + Parameters + ---------- + + R : numpy.ndarray + the heatmap to be visualized, shaped [M x N] + + X : numpy.ndarray + optional. some input, usually the data point for which the heatmap R is for, which shall serve + as a template for a black outline to be drawn on top of the image + shaped [M x N] + + scaling: int + factor, on how to enlarge the heatmap (to control resolution and as a inverse way to control outline thickness) + after reshaping it using shape. + + shape: tuple or list, length = 2 + optional. if not given, X is reshaped to be square. + + sigma : double + optional. sigma-parameter for the canny algorithm used for edge detection. the found edges are drawn as outlines. + + cmap : str + optional. color map of choice + + normalize : bool + optional. whether to normalize the heatmap to [-1 1] prior to colorization or not. + + Returns + ------- + + rgbimg : numpy.ndarray + three-dimensional array of shape [scaling*H x scaling*W x 3] , where H*W == M*N + ''' + + # create color map object from name string + cmap = eval('matplotlib.cm.{}'.format(cmap)) + + if normalize: + R = R / np.max(np.abs(R)) # normalize to [-1,1] wrt to max relevance magnitude + R = (R + 1.) / 2. # shift/normalize to [0,1] for color mapping + + R = enlarge_image(R, scaling) + rgb = cmap(R.flatten())[..., 0:3].reshape([R.shape[0], R.shape[1], 3]) + # rgb = repaint_corner_pixels(rgb, scaling) #obsolete due to directly calling the color map with [0,1]-normalized inputs + + if not X is None: # compute the outline of the input + # X = enlarge_image(vec2im(X,shape), scaling) + xdims = X.shape + Rdims = R.shape + + return rgb + + +def save_image(rgb_images, path, gap=2): + ''' + Takes as input a list of rgb images, places them next to each other with a gap and writes out the result. + + Parameters + ---------- + + rgb_images : list , tuple, collection. such stuff + each item in the collection is expected to be an rgb image of dimensions [H x _ x 3] + where the width is variable + + path : str + the output path of the assembled image + + gap : int + optional. sets the width of a black area of pixels realized as an image shaped [H x gap x 3] in between the input images + + Returns + ------- + + image : numpy.ndarray + the assembled image as written out to path + ''' + + sz = [] + image = [] + for i in range(len(rgb_images)): + if not sz: + sz = rgb_images[i].shape + image = rgb_images[i] + gap = np.zeros((sz[0], gap, sz[2])) + continue + if not sz[0] == rgb_images[i].shape[0] and sz[1] == rgb_images[i].shape[2]: + print('image', i, 'differs in size. unable to perform horizontal alignment') + print('expected: Hx_xD = {0}x_x{1}'.format(sz[0], sz[1])) + print('got : Hx_xD = {0}x_x{1}'.format(rgb_images[i].shape[0], rgb_images[i].shape[1])) + print('skipping image\n') + else: + image = np.hstack((image, gap, rgb_images[i])) + + image *= 255 + image = image.astype(np.uint8) + + print('saving image to ', path) + skimage.io.imsave(path, image) + return image + + +class IoU(Metric): + """Computes the intersection over union (IoU) per class and corresponding + mean (mIoU). + + Intersection over union (IoU) is a common evaluation metric for semantic + segmentation. The predictions are first accumulated in a confusion matrix + and the IoU is computed from it as follows: + + IoU = true_positive / (true_positive + false_positive + false_negative). + + Keyword arguments: + - num_classes (int): number of classes in the classification problem + - normalized (boolean, optional): Determines whether or not the confusion + matrix is normalized or not. Default: False. + - ignore_index (int or iterable, optional): Index of the classes to ignore + when computing the IoU. Can be an int, or any iterable of ints. + """ + + def __init__(self, num_classes, normalized=False, ignore_index=None): + super().__init__() + self.conf_metric = ConfusionMatrix(num_classes, normalized) + + if ignore_index is None: + self.ignore_index = None + elif isinstance(ignore_index, int): + self.ignore_index = (ignore_index,) + else: + try: + self.ignore_index = tuple(ignore_index) + except TypeError: + raise ValueError("'ignore_index' must be an int or iterable") + + def reset(self): + self.conf_metric.reset() + + def add(self, predicted, target): + """Adds the predicted and target pair to the IoU metric. + + Keyword arguments: + - predicted (Tensor): Can be a (N, K, H, W) tensor of + predicted scores obtained from the model for N examples and K classes, + or (N, H, W) tensor of integer values between 0 and K-1. + - target (Tensor): Can be a (N, K, H, W) tensor of + target scores for N examples and K classes, or (N, H, W) tensor of + integer values between 0 and K-1. + + """ + # Dimensions check + assert predicted.size(0) == target.size(0), \ + 'number of targets and predicted outputs do not match' + assert predicted.dim() == 3 or predicted.dim() == 4, \ + "predictions must be of dimension (N, H, W) or (N, K, H, W)" + assert target.dim() == 3 or target.dim() == 4, \ + "targets must be of dimension (N, H, W) or (N, K, H, W)" + + # If the tensor is in categorical format convert it to integer format + if predicted.dim() == 4: + _, predicted = predicted.max(1) + if target.dim() == 4: + _, target = target.max(1) + + self.conf_metric.add(predicted.view(-1), target.view(-1)) + + def value(self): + """Computes the IoU and mean IoU. + + The mean computation ignores NaN elements of the IoU array. + + Returns: + Tuple: (IoU, mIoU). The first output is the per class IoU, + for K classes it's numpy.ndarray with K elements. The second output, + is the mean IoU. + """ + conf_matrix = self.conf_metric.value() + if self.ignore_index is not None: + for index in self.ignore_index: + conf_matrix[:, self.ignore_index] = 0 + conf_matrix[self.ignore_index, :] = 0 + true_positive = np.diag(conf_matrix) + false_positive = np.sum(conf_matrix, 0) - true_positive + false_negative = np.sum(conf_matrix, 1) - true_positive + + # Just in case we get a division by 0, ignore/hide the error + with np.errstate(divide='ignore', invalid='ignore'): + iou = true_positive / (true_positive + false_positive + false_negative) + + return iou, np.nanmean(iou) + \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/timm_model.py b/API_CLIP/clip_prs/utils/timm_model.py new file mode 100644 index 0000000000000000000000000000000000000000..3fae156ba4b31b4652d8b444a09e3f2d396fd78e --- /dev/null +++ b/API_CLIP/clip_prs/utils/timm_model.py @@ -0,0 +1,149 @@ +""" timm model adapter + +Wraps timm (https://github.com/rwightman/pytorch-image-models) models for use as a vision tower in CLIP model. +""" +import logging +from collections import OrderedDict + +import torch +import torch.nn as nn + +try: + import timm + from timm.models.layers import Mlp, to_2tuple + try: + # old timm imports < 0.8.1 + from timm.models.layers.attention_pool2d import RotAttentionPool2d + from timm.models.layers.attention_pool2d import AttentionPool2d as AbsAttentionPool2d + except ImportError: + # new timm imports >= 0.8.1 + from timm.layers import RotAttentionPool2d + from timm.layers import AttentionPool2d as AbsAttentionPool2d +except ImportError: + timm = None + +from utils.misc import freeze_batch_norm_2d + + +class TimmModel(nn.Module): + """ timm model adapter + """ + + def __init__( + self, + model_name, + embed_dim, + image_size=224, + pool='avg', + proj='linear', + proj_bias=False, + drop=0., + drop_path=None, + patch_drop=None, + pretrained=False, + ): + super().__init__() + if timm is None: + raise RuntimeError("Please `pip install timm` to use timm models.") + self.image_size = to_2tuple(image_size) + + # setup kwargs that may not be common across all models + timm_kwargs = {} + if drop_path is not None: + timm_kwargs['drop_path_rate'] = drop_path + if patch_drop is not None: + timm_kwargs['patch_drop_rate'] = patch_drop + + custom_pool = pool in ('abs_attn', 'rot_attn') + if not proj and not custom_pool: + # use network classifier head as projection if no proj specified and no custom pooling used + self.trunk = timm.create_model( + model_name, + num_classes=embed_dim, + global_pool=pool, + pretrained=pretrained, + **timm_kwargs, + ) + prev_chs = embed_dim + else: + self.trunk = timm.create_model( + model_name, + pretrained=pretrained, + **timm_kwargs, + ) + feat_size = self.trunk.default_cfg.get('pool_size', None) + feature_ndim = 1 if not feat_size else 2 + if custom_pool: + assert feature_ndim == 2 + # if attn pooling used, remove both classifier and default pool + self.trunk.reset_classifier(0, global_pool='') + else: + # reset global pool if pool config set, otherwise leave as network default + reset_kwargs = dict(global_pool=pool) if pool else {} + self.trunk.reset_classifier(0, **reset_kwargs) + prev_chs = self.trunk.num_features + + head_layers = OrderedDict() + + # Add custom pooling to head + if pool == 'abs_attn': + head_layers['pool'] = AbsAttentionPool2d(prev_chs, feat_size=feat_size, out_features=embed_dim) + prev_chs = embed_dim + elif pool == 'rot_attn': + head_layers['pool'] = RotAttentionPool2d(prev_chs, out_features=embed_dim) + prev_chs = embed_dim + + # NOTE attention pool ends with a projection layer, so proj should usually be set to '' if such pooling is used + if proj == 'linear': + head_layers['drop'] = nn.Dropout(drop) + head_layers['proj'] = nn.Linear(prev_chs, embed_dim, bias=proj_bias) + elif proj == 'mlp': + head_layers['mlp'] = Mlp(prev_chs, 2 * embed_dim, embed_dim, drop=(drop, 0), bias=(True, proj_bias)) + else: + assert not proj, f'Unknown projection type {proj}.' + + self.head = nn.Sequential(head_layers) + + def lock(self, unlocked_groups=0, freeze_bn_stats=False): + """ lock modules + Args: + unlocked_groups (int): leave last n layer groups unlocked (default: 0) + """ + if not unlocked_groups: + # lock full model + for param in self.trunk.parameters(): + param.requires_grad = False + if freeze_bn_stats: + freeze_batch_norm_2d(self.trunk) + else: + # NOTE: partial freeze requires latest timm (master) branch and is subject to change + try: + # FIXME import here until API stable and in an official release + from timm.models.helpers import group_parameters, group_modules + except ImportError: + raise RuntimeError( + 'Please install latest timm `pip install git+https://github.com/rwightman/pytorch-image-models`') + matcher = self.trunk.group_matcher() + gparams = group_parameters(self.trunk, matcher) + max_layer_id = max(gparams.keys()) + max_layer_id = max_layer_id - unlocked_groups + for group_idx in range(max_layer_id + 1): + group = gparams[group_idx] + for param in group: + self.trunk.get_parameter(param).requires_grad = False + if freeze_bn_stats: + gmodules = group_modules(self.trunk, matcher, reverse=True) + gmodules = {k for k, v in gmodules.items() if v <= max_layer_id} + freeze_batch_norm_2d(self.trunk, gmodules) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + try: + self.trunk.set_grad_checkpointing(enable) + except Exception as e: + logging.warning('grad checkpointing not supported for this timm image tower, continuing without...') + + def forward(self, x): + x = self.trunk(x) + x = self.head(x) + return x \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/tokenizer.py b/API_CLIP/clip_prs/utils/tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..33ecf184db66784ad6c2639bfb9e382cb2071187 --- /dev/null +++ b/API_CLIP/clip_prs/utils/tokenizer.py @@ -0,0 +1,214 @@ +""" CLIP tokenizer + +Copied from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. +""" +import gzip +import html +import os +from functools import lru_cache +from typing import Union, List + +import ftfy +import regex as re +import torch + +# https://stackoverflow.com/q/62691279 +import os +os.environ["TOKENIZERS_PARALLELISM"] = "false" + + +@lru_cache() +def default_bpe(): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), "vocab/bpe_simple_vocab_16e6.txt.gz") + + +@lru_cache() +def bytes_to_unicode(): + """ + Returns list of utf-8 byte and a corresponding list of unicode strings. + The reversible bpe codes work on unicode strings. + This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. + When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. + This is a significant percentage of your normal, say, 32K bpe vocab. + To avoid that, we want lookup tables between utf-8 bytes and unicode strings. + And avoids mapping to whitespace/control characters the bpe code barfs on. + """ + bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1)) + cs = bs[:] + n = 0 + for b in range(2**8): + if b not in bs: + bs.append(b) + cs.append(2**8+n) + n += 1 + cs = [chr(n) for n in cs] + return dict(zip(bs, cs)) + + +def get_pairs(word): + """Return set of symbol pairs in a word. + Word is represented as tuple of symbols (symbols being variable-length strings). + """ + pairs = set() + prev_char = word[0] + for char in word[1:]: + pairs.add((prev_char, char)) + prev_char = char + return pairs + + +def basic_clean(text): + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + +def whitespace_clean(text): + text = re.sub(r'\s+', ' ', text) + text = text.strip() + return text + + +class SimpleTokenizer(object): + def __init__(self, bpe_path: str = default_bpe(), special_tokens=None): + self.byte_encoder = bytes_to_unicode() + self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} + merges = gzip.open(bpe_path).read().decode("utf-8").split('\n') + merges = merges[1:49152-256-2+1] + merges = [tuple(merge.split()) for merge in merges] + vocab = list(bytes_to_unicode().values()) + vocab = vocab + [v+'' for v in vocab] + for merge in merges: + vocab.append(''.join(merge)) + if not special_tokens: + special_tokens = ['', ''] + else: + special_tokens = ['', ''] + special_tokens + vocab.extend(special_tokens) + self.encoder = dict(zip(vocab, range(len(vocab)))) + self.decoder = {v: k for k, v in self.encoder.items()} + self.bpe_ranks = dict(zip(merges, range(len(merges)))) + self.cache = {t:t for t in special_tokens} + special = "|".join(special_tokens) + self.pat = re.compile(special + r"""|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE) + + self.vocab_size = len(self.encoder) + self.all_special_ids = [self.encoder[t] for t in special_tokens] + + def bpe(self, token): + if token in self.cache: + return self.cache[token] + word = tuple(token[:-1]) + ( token[-1] + '',) + pairs = get_pairs(word) + + if not pairs: + return token+'' + + while True: + bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf'))) + if bigram not in self.bpe_ranks: + break + first, second = bigram + new_word = [] + i = 0 + while i < len(word): + try: + j = word.index(first, i) + new_word.extend(word[i:j]) + i = j + except: + new_word.extend(word[i:]) + break + + if word[i] == first and i < len(word)-1 and word[i+1] == second: + new_word.append(first+second) + i += 2 + else: + new_word.append(word[i]) + i += 1 + new_word = tuple(new_word) + word = new_word + if len(word) == 1: + break + else: + pairs = get_pairs(word) + word = ' '.join(word) + self.cache[token] = word + return word + + def encode(self, text): + bpe_tokens = [] + text = whitespace_clean(basic_clean(text)).lower() + for token in re.findall(self.pat, text): + token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8')) + bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' ')) + return bpe_tokens + + def decode(self, tokens): + text = ''.join([self.decoder[token] for token in tokens]) + text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('', ' ') + return text + + +_tokenizer = SimpleTokenizer() + +def decode(output_ids: torch.Tensor): + output_ids = output_ids.cpu().numpy() + return _tokenizer.decode(output_ids) + +def tokenize(texts: Union[str, List[str]], context_length: int = 77) -> torch.LongTensor: + """ + Returns the tokenized representation of given input string(s) + + Parameters + ---------- + texts : Union[str, List[str]] + An input string or a list of input strings to tokenize + context_length : int + The context length to use; all CLIP models use 77 as the context length + + Returns + ------- + A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length] + """ + if isinstance(texts, str): + texts = [texts] + + sot_token = _tokenizer.encoder[""] + eot_token = _tokenizer.encoder[""] + all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts] + result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) + + for i, tokens in enumerate(all_tokens): + if len(tokens) > context_length: + tokens = tokens[:context_length] # Truncate + tokens[-1] = eot_token + result[i, :len(tokens)] = torch.tensor(tokens) + + return result + + +class HFTokenizer: + """HuggingFace tokenizer wrapper""" + + def __init__(self, tokenizer_name: str): + from transformers import AutoTokenizer + self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name) + + def save_pretrained(self, dest): + self.tokenizer.save_pretrained(dest) + + def __call__(self, texts: Union[str, List[str]], context_length: int = 77) -> torch.Tensor: + # same cleaning as for default tokenizer, except lowercasing + # adding lower (for case-sensitive tokenizers) will make it more robust but less sensitive to nuance + if isinstance(texts, str): + texts = [texts] + texts = [whitespace_clean(basic_clean(text)) for text in texts] + input_ids = self.tokenizer( + texts, + return_tensors='pt', + max_length=context_length, + padding='max_length', + truncation=True, + ).input_ids + return input_ids \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/transform.py b/API_CLIP/clip_prs/utils/transform.py new file mode 100644 index 0000000000000000000000000000000000000000..2f1b3e71658767131e6e5319c227242219e7b9d5 --- /dev/null +++ b/API_CLIP/clip_prs/utils/transform.py @@ -0,0 +1,133 @@ +import warnings +from dataclasses import dataclass, asdict +from typing import Any, Dict, Optional, Sequence, Tuple, Union + +import torch +import torch.nn as nn +import torchvision.transforms.functional as F + +from torchvision.transforms import Normalize, Compose, RandomResizedCrop, InterpolationMode, ToTensor, Resize, \ + CenterCrop + +from utils.constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD + + +@dataclass +class AugmentationCfg: + scale: Tuple[float, float] = (0.9, 1.0) + ratio: Optional[Tuple[float, float]] = None + color_jitter: Optional[Union[float, Tuple[float, float, float]]] = None + interpolation: Optional[str] = None + re_prob: Optional[float] = None + re_count: Optional[int] = None + use_timm: bool = False + + +class ResizeMaxSize(nn.Module): + + def __init__(self, max_size, interpolation=InterpolationMode.BICUBIC, fn='max', fill=0): + super().__init__() + if not isinstance(max_size, int): + raise TypeError(f"Size should be int. Got {type(max_size)}") + self.max_size = max_size + self.interpolation = interpolation + self.fn = min if fn == 'min' else min + self.fill = fill + + def forward(self, img): + if isinstance(img, torch.Tensor): + height, width = img.shape[:2] + else: + width, height = img.size + scale = self.max_size / float(max(height, width)) + if scale != 1.0: + new_size = tuple(round(dim * scale) for dim in (height, width)) + img = F.resize(img, new_size, self.interpolation) + pad_h = self.max_size - new_size[0] + pad_w = self.max_size - new_size[1] + img = F.pad(img, padding=[pad_w//2, pad_h//2, pad_w - pad_w//2, pad_h - pad_h//2], fill=self.fill) + return img + + +def _convert_to_rgb(image): + return image.convert('RGB') + + +def image_transform( + image_size: int, + is_train: bool, + mean: Optional[Tuple[float, ...]] = None, + std: Optional[Tuple[float, ...]] = None, + resize_longest_max: bool = False, + fill_color: int = 0, + aug_cfg: Optional[Union[Dict[str, Any], AugmentationCfg]] = None, +): + mean = mean or OPENAI_DATASET_MEAN + if not isinstance(mean, (list, tuple)): + mean = (mean,) * 3 + + std = std or OPENAI_DATASET_STD + if not isinstance(std, (list, tuple)): + std = (std,) * 3 + + if isinstance(image_size, (list, tuple)) and image_size[0] == image_size[1]: + # for square size, pass size as int so that Resize() uses aspect preserving shortest edge + image_size = image_size[0] + + if isinstance(aug_cfg, dict): + aug_cfg = AugmentationCfg(**aug_cfg) + else: + aug_cfg = aug_cfg or AugmentationCfg() + normalize = Normalize(mean=mean, std=std) + if is_train: + aug_cfg_dict = {k: v for k, v in asdict(aug_cfg).items() if v is not None} + use_timm = aug_cfg_dict.pop('use_timm', False) + if use_timm: + from timm.data import create_transform # timm can still be optional + if isinstance(image_size, (tuple, list)): + assert len(image_size) >= 2 + input_size = (3,) + image_size[-2:] + else: + input_size = (3, image_size, image_size) + # by default, timm aug randomly alternates bicubic & bilinear for better robustness at inference time + aug_cfg_dict.setdefault('interpolation', 'random') + aug_cfg_dict.setdefault('color_jitter', None) # disable by default + train_transform = create_transform( + input_size=input_size, + is_training=True, + hflip=0., + mean=mean, + std=std, + re_mode='pixel', + **aug_cfg_dict, + ) + else: + train_transform = Compose([ + RandomResizedCrop( + image_size, + scale=aug_cfg_dict.pop('scale'), + interpolation=InterpolationMode.BICUBIC, + ), + _convert_to_rgb, + ToTensor(), + normalize, + ]) + if aug_cfg_dict: + warnings.warn(f'Unused augmentation cfg items, specify `use_timm` to use ({list(aug_cfg_dict.keys())}).') + return train_transform + else: + if resize_longest_max: + transforms = [ + ResizeMaxSize(image_size, fill=fill_color) + ] + else: + transforms = [ + Resize(image_size, interpolation=InterpolationMode.BICUBIC), + CenterCrop(image_size), + ] + transforms.extend([ + _convert_to_rgb, + ToTensor(), + normalize, + ]) + return Compose(transforms) \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/transformer.py b/API_CLIP/clip_prs/utils/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..945a23bd37acb2fe8dc758756e93468b434e829d --- /dev/null +++ b/API_CLIP/clip_prs/utils/transformer.py @@ -0,0 +1,821 @@ +from collections import OrderedDict +import math +from typing import Callable, Optional, Sequence, Tuple, Text + +import torch +from torch import nn +from torch.nn import functional as F +from torch.utils.checkpoint import checkpoint +import numbers +import einops +import numpy as np +from utils.misc import to_2tuple +from utils.hook import HookManager + + +class LayerNorm(nn.Module): + """Subclass torch's LayerNorm (with cast back to input dtype).""" + def __init__(self, normalized_shape, eps: float = 1e-5, elementwise_affine: bool = True, device=None, dtype=None, + hook: Optional[HookManager] = None): + super().__init__() + self.hook = hook or HookManager() + if isinstance(normalized_shape, numbers.Integral): + # mypy error: incompatible types in assignment + normalized_shape = (normalized_shape,) # type: ignore[assignment] + self.normalized_shape = tuple(normalized_shape) # type: ignore[arg-type] + self.eps = eps + self.elementwise_affine = elementwise_affine + if self.elementwise_affine: + self.weight = torch.nn.Parameter(torch.empty(self.normalized_shape,)) + self.bias = torch.nn.Parameter(torch.empty(self.normalized_shape,)) + else: + self.register_parameter('weight', None) + self.register_parameter('bias', None) + + def forward(self, x: torch.Tensor): + orig_type = x.dtype + assert self.normalized_shape == x.shape[-len(self.normalized_shape):] + dims = [-(i + 1) for i in range(len(self.normalized_shape))] + mean = self.hook('mean', ret=x.mean(dim=dims, keepdim=True)) + mean_x2 = (x ** 2).mean(dim=dims, keepdim=True) + var = mean_x2 - mean ** 2 + x_norm = self.hook('mean_reduced', ret=(x - mean)) / self.hook('sqrt_var', ret=torch.sqrt(var + self.eps)) + if self.elementwise_affine: + x_norm = self.hook('renorm.post', ret=self.weight * x_norm + self.bias) + self.hook.finalize() + return x_norm.to(orig_type) + + +class QuickGELU(nn.Module): + # NOTE This is slower than nn.GELU or nn.SiLU and uses more GPU memory + def forward(self, x: torch.Tensor): + return x * torch.sigmoid(1.702 * x) + + +class LayerScale(nn.Module): + def __init__(self, dim, init_values=1e-5, inplace=False): + super().__init__() + self.inplace = inplace + self.gamma = nn.Parameter(init_values * torch.ones(dim)) + + def forward(self, x): + raise ValueError('Not implemented') + return x.mul_(self.gamma) if self.inplace else x * self.gamma + + +class PatchDropout(nn.Module): + """ + https://arxiv.org/abs/2212.00794 + """ + + def __init__(self, prob, exclude_first_token=True): + super().__init__() + assert 0 <= prob < 1. + self.prob = prob + self.exclude_first_token = exclude_first_token # exclude CLS token + + def forward(self, x): + if not self.training or self.prob == 0.: + return x + + if self.exclude_first_token: + cls_tokens, x = x[:, :1], x[:, 1:] + else: + cls_tokens = torch.jit.annotate(torch.Tensor, x[:, :1]) + + batch = x.size()[0] + num_tokens = x.size()[1] + + batch_indices = torch.arange(batch) + batch_indices = batch_indices[..., None] + + keep_prob = 1 - self.prob + num_patches_keep = max(1, int(num_tokens * keep_prob)) + + rand = torch.randn(batch, num_tokens) + patch_indices_keep = rand.topk(num_patches_keep, dim=-1).indices + + x = x[batch_indices, patch_indices_keep] + + if self.exclude_first_token: + x = torch.cat((cls_tokens, x), dim=1) + + return x + + +class Attention(nn.Module): + def __init__( + self, + dim, + num_heads=8, + qkv_bias=True, + scaled_cosine=False, + scale_heads=False, + logit_scale_max=math.log(1. / 0.01), + attn_drop=0., + proj_drop=0. + ): + super().__init__() + self.scaled_cosine = scaled_cosine + self.scale_heads = scale_heads + assert dim % num_heads == 0, 'dim should be divisible by num_heads' + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.scale = self.head_dim ** -0.5 + self.logit_scale_max = logit_scale_max + + # keeping in_proj in this form (instead of nn.Linear) to match weight scheme of original + self.in_proj_weight = nn.Parameter(torch.randn((dim * 3, dim)) * self.scale) + if qkv_bias: + self.in_proj_bias = nn.Parameter(torch.zeros(dim * 3)) + else: + self.in_proj_bias = None + + if self.scaled_cosine: + self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1)))) + else: + self.logit_scale = None + self.attn_drop = nn.Dropout(attn_drop) + if self.scale_heads: + self.head_scale = nn.Parameter(torch.ones((num_heads, 1, 1))) + else: + self.head_scale = None + self.out_proj = nn.Linear(dim, dim) + self.out_drop = nn.Dropout(proj_drop) + + def forward(self, x, attn_mask: Optional[torch.Tensor] = None): + L, N, C = x.shape + q, k, v = F.linear(x, self.in_proj_weight, self.in_proj_bias).chunk(3, dim=-1) + q = q.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1) + k = k.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1) + v = v.contiguous().view(L, N * self.num_heads, -1).transpose(0, 1) + + if self.logit_scale is not None: + attn = torch.bmm(F.normalize(q, dim=-1), F.normalize(k, dim=-1).transpose(-1, -2)) + logit_scale = torch.clamp(self.logit_scale, max=self.logit_scale_max).exp() + attn = attn.view(N, self.num_heads, L, L) * logit_scale + attn = attn.view(-1, L, L) + else: + q = q * self.scale + attn = torch.bmm(q, k.transpose(-1, -2)) + + if attn_mask is not None: + if attn_mask.dtype == torch.bool: + new_attn_mask = torch.zeros_like(attn_mask, dtype=q.dtype) + new_attn_mask.masked_fill_(attn_mask, float("-inf")) + attn_mask = new_attn_mask + attn += attn_mask + + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + + x = torch.bmm(attn, v) + if self.head_scale is not None: + x = x.view(N, self.num_heads, L, C) * self.head_scale + x = x.view(-1, L, C) + x = x.transpose(0, 1).reshape(L, N, C) + x = self.out_proj(x) + x = self.out_drop(x) + return x + + +class AttentionalPooler(nn.Module): + def __init__( + self, + d_model: int, + context_dim: int, + n_head: int = 8, + n_queries: int = 256, + norm_layer: Callable = LayerNorm + ): + super().__init__() + self.query = nn.Parameter(torch.randn(n_queries, d_model)) + self.attn = nn.MultiheadAttention(d_model, n_head, kdim=context_dim, vdim=context_dim) + self.ln_q = norm_layer(d_model) + self.ln_k = norm_layer(context_dim) + + def forward(self, x: torch.Tensor): + x = self.ln_k(x).permute(1, 0, 2) # NLD -> LND + N = x.shape[1] + q = self.ln_q(self.query) + out = self.attn(self._repeat(q, N), x, x, need_weights=False)[0] + return out.permute(1, 0, 2) # LND -> NLD + + def _repeat(self, query, N: int): + return query.unsqueeze(1).repeat(1, N, 1) + + +class MLP(nn.Module): + def __init__(self, d_model: int, mlp_width: int, act_layer: Callable = nn.GELU, hook: Optional[HookManager] = None,): + super().__init__() + self.hook = hook or HookManager() + self.c_fc = nn.Linear(d_model, mlp_width) + self.gelu = act_layer() + self.c_proj = nn.Linear(mlp_width, d_model) + + def forward(self, x): + x = self.hook('c_fc.post', ret=self.c_fc(x)) + x = self.hook('gelu.post', ret=self.gelu(x)) + x = self.hook('c_proj.post', ret=self.c_proj(x)) + self.hook.finalize() + return x + + +class MultiheadAttention(nn.Module): + """ + There are variety of ways to look at multihead attention. Because of that I implemented a few so it will be easy to compare. + """ + def __init__(self, embed_dim, num_heads, dropout=0., bias=True, add_bias_kv=False, add_zero_attn=False, + kdim=None, vdim=None, batch_first=False, device=None, dtype=None, hook: Optional[HookManager] = None,): + super().__init__() + self.hook = hook or HookManager() + self.embed_dim = embed_dim + self.kdim = kdim if kdim is not None else embed_dim + self.vdim = vdim if vdim is not None else embed_dim + self._qkv_same_embed_dim = self.kdim == embed_dim and self.vdim == embed_dim + + self.num_heads = num_heads + self.dropout = dropout + self.batch_first = batch_first + self.head_dim = embed_dim // num_heads + assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads" + self.in_proj_weight = nn.Parameter(torch.empty((3 * embed_dim, embed_dim))) + + if bias: + self.in_proj_bias = nn.Parameter(torch.empty(3 * embed_dim)) + else: + self.register_parameter('in_proj_bias', None) + self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + + if add_bias_kv: + self.bias_k = nn.Parameter(torch.empty((1, 1, embed_dim))) + self.bias_v = nn.Parameter(torch.empty((1, 1, embed_dim))) + else: + self.bias_k = self.bias_v = None + + self.add_zero_attn = add_zero_attn + + def forward_direct(self, x, attn_mask=None): + B, N, C = x.shape + qkv = self.hook('in_proj_bias.post', + ret=self.hook('in_proj.post', + ret=x @ self.in_proj_weight.T) + self.in_proj_bias) + qkv = qkv.reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) + q, k, v = qkv.unbind(0) + k = self.hook('k', ret=k) + q = self.hook('q', ret=q) + v = self.hook('v', ret=v) + dk = q.size()[-1] + q = q / math.sqrt(dk) + q = self.hook('q_norm', ret=q) + attn = q @ k.transpose(-2, -1) # [B, H, N, N] + attn = self.hook('pre_mask', ret=attn) + if attn_mask is not None: + attn += attn_mask + attn = self.hook('post_mask', ret=attn) + attn = attn.softmax(dim=-1) + attn = self.hook('post_softmax', ret=attn) + x = attn @ v + + x = x.transpose(1, 2).reshape(B, N, C) + x = self.hook('attn_v', ret=x) + x = self.hook('out_proj_bias.post', + ret=self.hook('out_proj.post', ret=x @ self.out_proj.weight.T) + self.out_proj.bias) + return x + + def _split_qkv_weight(self): + q_weight, k_weight, v_weight = (self.in_proj_weight[:self.embed_dim].reshape(self.num_heads, self.head_dim, -1), + self.in_proj_weight[self.embed_dim:self.embed_dim*2].reshape(self.num_heads, self.head_dim, -1), + self.in_proj_weight[self.embed_dim*2:].reshape(self.num_heads, self.head_dim, -1) + ) + return q_weight, k_weight, v_weight + + def _split_qkv_bias(self): + q_bias, k_bias, v_bias = (self.in_proj_bias[:self.embed_dim].reshape(1, self.num_heads, 1, self.head_dim), + self.in_proj_bias[self.embed_dim:self.embed_dim*2].reshape(1, self.num_heads, 1, self.head_dim), + self.in_proj_bias[self.embed_dim*2:].reshape(1, self.num_heads, 1, self.head_dim) + ) + return q_bias, k_bias, v_bias + + def forward_qkv(self, x, attn_mask=None): + B, N, C = x.shape + q_weight, k_weight, v_weight = (self.in_proj_weight[:self.embed_dim], + self.in_proj_weight[self.embed_dim:self.embed_dim*2], + self.in_proj_weight[self.embed_dim*2:]) + q_bias, k_bias, v_bias = (self.in_proj_bias[:self.embed_dim], + self.in_proj_bias[self.embed_dim:self.embed_dim*2], + self.in_proj_bias[self.embed_dim*2:]) + q = self.hook('in_q_bias.post', + ret=self.hook('in_q.post', + ret=x @ q_weight.T) + + q_bias).reshape(B, N, self.num_heads, self.head_dim).permute(0, 2, 1, 3) + k = self.hook('in_k_bias.post', + ret=self.hook('in_k.post', + ret=x @ k_weight.T) + + k_bias).reshape(B, N, self.num_heads, self.head_dim).permute(0, 2, 1, 3) + v = self.hook('in_v_bias.post', + ret=self.hook('in_v.post', + ret=x @ v_weight.T) + + v_bias).reshape(B, N, self.num_heads, self.head_dim).permute(0, 2, 1, 3) + dk = q.size()[-1] + q = q / math.sqrt(dk) + q = self.hook('q_norm', ret=q) + attn = q @ k.transpose(-2, -1) + attn = self.hook('attention.pre_mask', ret=attn) + if attn_mask is not None: + attn += attn_mask + attn = self.hook('attention.post_mask', ret=attn) + attn = attn.softmax(dim=-1) + attn = self.hook('attention.post_softmax', ret=attn) # [B, H, N, N] + x = torch.einsum('bhnm,bhmc->bhnmc', attn, v) + x = self.hook('extended_attn_v', ret=x) + x = x.sum(axis=3).transpose(1, 2).reshape(B, N, C) + x = self.hook('attn_v', ret=x) + x = self.hook('out.post_bias', + ret=self.hook('out.post', + ret=x @ self.out_proj.weight.T) + + self.out_proj.bias) + return x + + def forward_per_head(self, x, attn_mask=None): + """ Old Version + B, N, C = x.shape # batch size, number of tokens, embedding dim + q_weight, k_weight, v_weight = self._split_qkv_weight()# number of head, head im + q_bias, k_bias, v_bias = self._split_qkv_bias() + q = self.hook('in_q_bias.post', + ret=self.hook('in_q.post', + ret=torch.einsum('bnc,hdc->bhnd', x, q_weight)) + + q_bias) + k = self.hook('in_k_bias.post', + ret=self.hook('in_k.post', + ret=torch.einsum('bnc,hdc->bhnd', x, k_weight)) + + k_bias) + v = self.hook('in_v_bias.post', + ret=self.hook('in_v.post', + ret=torch.einsum('bnc,hdc->bhnd', x, v_weight)) + + v_bias) # (B, self.num_heads, N, self.head_dim) + dk = q.size()[-1] + q = q / math.sqrt(dk) + q = self.hook('q_norm', ret=q) + attn = q @ k.transpose(-2, -1) + attn = self.hook('attention.pre_mask', ret=attn) + if attn_mask is not None: + attn += attn_mask + attn = self.hook('attention.post_mask', ret=attn) + attn = attn.softmax(dim=-1) + attn = self.hook('attention.post_softmax', ret=attn) # [B, H, N, N] + x = torch.einsum('bhnm,bhmc->bnmhc', attn, v) # We also switch here back from head-first to n-first + x = self.hook('extended_attn_v', ret=x) + x = self.hook('out.post', ret=torch.einsum('bnmhc,dhc->bnmhd', x, self.out_proj.weight.reshape(self.embed_dim, self.num_heads, self.head_dim))) + x = self.hook('out.post_collapse', ret=x.sum(axis=[2,3])) + x = self.hook('out.post_bias', ret=x + self.out_proj.bias) + return x""" + + B, N, C = x.shape # batch size, number of tokens, embedding dim + q_weight, k_weight, v_weight = self._split_qkv_weight()# number of head, head im + q_bias, k_bias, v_bias = self._split_qkv_bias() + q = self.hook('in_q_bias.post', + ret=self.hook('in_q.post', + ret=torch.einsum('bnc,hdc->bhnd', x, q_weight)) + + q_bias) + k = self.hook('in_k_bias.post', + ret=self.hook('in_k.post', + ret=torch.einsum('bnc,hdc->bhnd', x, k_weight)) + + k_bias) + v = self.hook('in_v_bias.post', + ret=self.hook('in_v.post', + ret=torch.einsum('bnc,hdc->bhnd', x, v_weight)) + + v_bias) # (B, self.num_heads, N, self.head_dim) + dk = q.size()[-1] + q = q / math.sqrt(dk) + q = self.hook('q_norm', ret=q) + attn = q @ k.transpose(-2, -1) + attn = self.hook('attention.pre_mask', ret=attn) + if attn_mask is not None: + attn += attn_mask + attn = self.hook('attention.post_mask', ret=attn) + attn = attn.softmax(dim=-1) + attn = self.hook('attention.post_softmax', ret=attn) # [B, H, N, N] + x = torch.einsum('bhnm,bhmc->bnmhc', attn, v) # We also switch here back from head-first to n-first + x = self.hook('extended_attn_v', ret=x) + x = self.hook('out.post', ret=torch.einsum('bnmhc,dhc->bnmd', x, self.out_proj.weight.reshape(self.embed_dim, self.num_heads, self.head_dim))) + x = self.hook('out.post_collapse', ret=x.sum(axis=[2])) + x = self.hook('out.post_bias', ret=x + self.out_proj.bias) + return x + + def _get_ov_circuit(self,): + reshaped_o = self.out_proj.weight.reshape(self.embed_dim, self.num_heads, self.head_dim) + _, _, v_weight = self._split_qkv_weight() # num_heads, head_dim, embed_dim + _, _, v_bias = self._split_qkv_bias() # 1, num_heads, 1, head_dim + ov_circuit = torch.einsum('onh,nhi->oni', reshaped_o, v_weight) + ov_bias_circuit = torch.einsum('onh,bnxh->bnxo', reshaped_o, v_bias) # [1, num_heads, 1, embed_dim] + return ov_circuit, ov_bias_circuit + + def forward_ov_circuit(self, x, attn_mask=None): + B, N, C = x.shape + q_weight, k_weight, _ = self._split_qkv_weight() + q_bias, k_bias, _ = self._split_qkv_bias() + q = self.hook('in_q_bias.post', + ret=self.hook('in_q.post', + ret=torch.einsum('bnc,hdc->bhnd', x, q_weight)) + + q_bias) + k = self.hook('in_k_bias.post', + ret=self.hook('in_k.post', + ret=torch.einsum('bnc,hdc->bhnd', x, k_weight)) + + k_bias) + ov, ov_bias = self._get_ov_circuit() + ov = self.hook('ov', ret=ov) + ov_bias = self.hook('ov_bias', ret=ov_bias) + v = self.hook('ov_bias.post', + ret=self.hook('ov.post', + ret=torch.einsum('bnc,dhc->bhnd', x, ov)) + + ov_bias) + + dk = q.size()[-1] + q = q / math.sqrt(dk) + q = self.hook('q_norm', ret=q) + attn = q @ k.transpose(-2, -1) + attn = self.hook('attention.pre_mask', ret=attn) + if attn_mask is not None: + attn += attn_mask + attn = self.hook('attention.post_mask', ret=attn) + attn = attn.softmax(dim=-1) + attn = self.hook('attention.post_softmax', ret=attn) # [B, H, N, N] + x = torch.einsum('bhnm,bhmc->bnmhc', attn, v) # We also switch here back from head-first to n-first + x = self.hook('extended_attn_ov', ret=x) + x = self.hook('out.post_collapse', ret=x.sum(axis=[2,3])) + x = self.hook('out.post_bias', ret=x + self.out_proj.bias) + return x + + def forward(self, x, attn_mask=None, method: Text = 'ov_circuit'): + if method == 'direct': + x = self.forward_direct(x, attn_mask=attn_mask) + elif method == 'qkv': + x = self.forward_qkv(x, attn_mask=attn_mask) + elif method == 'head': + x = self.forward_per_head(x, attn_mask=attn_mask) + elif method == 'ov_circuit': + x = self.forward_ov_circuit(x, attn_mask=attn_mask) + self.hook.finalize() + + return x + + +class ResidualAttentionBlock(nn.Module): + def __init__( + self, + d_model: int, + n_head: int, + mlp_ratio: float = 4.0, + ls_init_value: float = None, + act_layer: Callable = nn.GELU, + norm_layer: Callable = LayerNorm, + hook: Optional[HookManager] = None, + ): + super().__init__() + self.hook = hook or HookManager() + self.ln_1 = norm_layer(d_model, hook=hook.fork('ln_1')) + self.attn = MultiheadAttention(d_model, n_head, hook=hook.fork('attn')) + + self.ls_1 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity() + + self.ln_2 = norm_layer(d_model, hook=hook.fork('ln_2')) + mlp_width = int(d_model * mlp_ratio) + self.mlp = MLP(d_model, mlp_width, act_layer=act_layer, hook=hook.fork('mlp')) + self.ls_2 = LayerScale(d_model, ls_init_value) if ls_init_value is not None else nn.Identity() + + def attention( + self, + q_x: torch.Tensor, + attn_mask: Optional[torch.Tensor] = None, + method: Text = 'direct' + ): + attn_mask = attn_mask.to(q_x.dtype) if attn_mask is not None else None + return self.attn( + q_x, attn_mask=attn_mask, + method=method + ) + + def forward( + self, + q_x: torch.Tensor, + attn_mask: Optional[torch.Tensor] = None, + attn_method: Text = 'direct', + ): + q_x = self.hook('pre', ret=q_x) + after_ln1 = self.ln_1(q_x) + after_attn = self.attention(q_x=after_ln1, attn_mask=attn_mask, method=attn_method) + after_attn = self.hook('after_attn', ret=after_attn) + x = q_x + self.ls_1(after_attn) + after_ln2 = self.ln_2(x) + after_mlp = self.mlp(after_ln2) + after_mlp = self.hook('after_mlp', ret=after_mlp) + x = x + self.ls_2(after_mlp) + x = self.hook('post', ret=x) + self.hook.finalize() + return x + + +class Transformer(nn.Module): + def __init__( + self, + width: int, + layers: int, + heads: int, + mlp_ratio: float = 4.0, + ls_init_value: float = None, + act_layer: Callable = nn.GELU, + norm_layer: Callable = LayerNorm, + hook: Optional[HookManager] = None, + ): + super().__init__() + self.hook = hook or HookManager() + self.width = width + self.layers = layers + self.grad_checkpointing = False + + self.resblocks = nn.ModuleList([ + ResidualAttentionBlock( + width, heads, mlp_ratio, ls_init_value=ls_init_value, + act_layer=act_layer, norm_layer=norm_layer, hook=hook.fork(f'resblocks.{i}')) + for i in range(layers) + ]) + + def get_cast_dtype(self) -> torch.dtype: + if hasattr(self.resblocks[0].mlp.c_fc, 'int8_original_dtype'): + return self.resblocks[0].mlp.c_fc.int8_original_dtype + return self.resblocks[0].mlp.c_fc.weight.dtype + + def forward(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None, attn_method: Text = 'direct'): + for r in self.resblocks: + if self.grad_checkpointing and not torch.jit.is_scripting(): + raise ValueError('grad_checkpointing not implement') + # TODO: handle kwargs https://github.com/pytorch/pytorch/issues/79887#issuecomment-1161758372 + x = checkpoint(r, x, None, None, attn_mask) + else: + x = r(x, attn_mask=attn_mask, attn_method=attn_method) + self.hook.finalize() + return x + + +class VisionTransformer(nn.Module): + output_tokens: torch.jit.Final[bool] + + def __init__( + self, + image_size: int, + patch_size: int, + width: int, + layers: int, + heads: int, + mlp_ratio: float, + ls_init_value: float = None, + global_average_pool: bool = False, + attentional_pool: bool = False, + n_queries: int = 256, + attn_pooler_heads: int = 8, + output_dim: int = 512, + patch_dropout: float = 0., + input_patchnorm: bool = False, + act_layer: Callable = nn.GELU, + norm_layer: Callable = LayerNorm, + output_tokens: bool = False, + hook: Optional[HookManager] = None + ): + super().__init__() + self.hook = hook or HookManager() + self.output_tokens = output_tokens + image_height, image_width = self.image_size = to_2tuple(image_size) + patch_height, patch_width = self.patch_size = to_2tuple(patch_size) + self.grid_size = (image_height // patch_height, image_width // patch_width) + self.output_dim = output_dim + + # whether to layernorm each patch, as done in dual patchnorm paper - https://arxiv.org/abs/2302.01327v1 + self.input_patchnorm = input_patchnorm + + if input_patchnorm: + patch_input_dim = patch_height * patch_width * 3 + self.patchnorm_pre_ln = LayerNorm(patch_input_dim, hook=hook.fork('patchnorm_pre_ln')) + self.conv1 = nn.Linear(patch_input_dim, width) + else: + self.patchnorm_pre_ln = nn.Identity() + self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False) + + # class embeddings and positional embeddings + scale = width ** -0.5 + self.class_embedding = nn.Parameter(scale * torch.randn(width)) + self.positional_embedding = nn.Parameter(scale * torch.randn(self.grid_size[0] * self.grid_size[1] + 1, width)) + + # setting a patch_dropout of 0. would mean it is disabled and this function would be the identity fn + self.patch_dropout = PatchDropout(patch_dropout) if patch_dropout > 0. else nn.Identity() + + self.ln_pre = norm_layer(width, hook=hook.fork('ln_pre')) + self.transformer = Transformer( + width, + layers, + heads, + mlp_ratio, + ls_init_value=ls_init_value, + act_layer=act_layer, + norm_layer=norm_layer, + hook=hook.fork('transformer'), + ) + + self.global_average_pool = global_average_pool + if attentional_pool: + self.attn_pool = AttentionalPooler(output_dim, width, n_head=attn_pooler_heads, n_queries=n_queries) + self.ln_post = norm_layer(output_dim, hook=hook.fork('ln_post')) + self.proj = nn.Parameter(scale * torch.randn(output_dim, output_dim)) + else: + self.attn_pool = None + self.ln_post = norm_layer(width, hook=hook.fork('ln_post')) + self.proj = nn.Parameter(scale * torch.randn(width, output_dim)) + + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.transformer.grad_checkpointing = enable + + def _global_pool(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: + if self.global_average_pool: + return x.mean(dim=1), x + else: + return x[:, 0], x[:, 1:] + + def forward(self, x: torch.Tensor, attn_method: Text = 'direct'): + + # to patches - whether to use dual patchnorm - https://arxiv.org/abs/2302.01327v1 + if self.input_patchnorm: + # einops - rearrange(x, 'b c (h p1) (w p2) -> b (h w) (c p1 p2)') + x = x.reshape(x.shape[0], x.shape[1], self.grid_size[0], self.patch_size[0], self.grid_size[1], self.patch_size[1]) + x = x.permute(0, 2, 4, 1, 3, 5) + x = x.reshape(x.shape[0], self.grid_size[0] * self.grid_size[1], -1) + x = self.hook('patchnorm_pre_ln.post', ret=self.patchnorm_pre_ln(x)) + x = self.hook('conv1.post', ret=self.conv1(x)) + else: + x = self.hook('conv1.post', ret=self.conv1(x)) # shape = [*, width, grid, grid] + x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2] + x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width] + + # class embeddings and positional embeddings + x = torch.cat( + [self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), + x], dim=1) # shape = [*, grid ** 2 + 1, width] + x = self.hook('positional_embedding.post', ret=x + self.positional_embedding.to(x.dtype)) + + # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in + x = self.hook('patch_dropout.post', ret=self.patch_dropout(x)) + x = self.hook('ln_pre_post', ret=self.ln_pre(x)) + # x = x.permute(1, 0, 2) # NLD -> LND + x = self.transformer(x, attn_method=attn_method) + # x = x.permute(1, 0, 2) # LND -> NLD + if self.attn_pool is not None: + x = self.hook('attn_pool.post', ret=self.attn_pool(x)) + x = self.hook('ln_post_post', ret=self.ln_post(x)) + pooled, tokens = self.hook('global_pool.post', ret=self._global_pool(x)) + else: + pooled, tokens = self.hook('global_pool.post', ret=self._global_pool(x)) + pooled = self.hook('ln_post_post', ret=self.ln_post(pooled)) # pooled is cls token, tokens are others + + if self.proj is not None: + pooled = self.hook('proj.post', ret=self.hook('proj.pre', ret=pooled) @ self.proj) + + self.hook.finalize() + + if self.output_tokens: + return pooled, tokens + + return pooled + + +class TextTransformer(nn.Module): + output_tokens: torch.jit.Final[bool] + + def __init__( + self, + context_length: int = 77, + vocab_size: int = 49408, + width: int = 512, + heads: int = 8, + layers: int = 12, + ls_init_value: float = None, + output_dim: int = 512, + act_layer: Callable = nn.GELU, + norm_layer: Callable = LayerNorm, + embed_cls: bool = False, + pad_id: int = 0, + output_tokens: bool = False, + hook: Optional[HookManager] = None + ): + super().__init__() + self.hook = hook or HookManager() + self.output_tokens = output_tokens + self.num_pos = self.context_length = context_length + self.vocab_size = vocab_size + self.width = width + self.output_dim = output_dim + self.heads = heads + self.pad_id = pad_id + + self.text_projection = nn.Parameter(torch.empty(width, output_dim)) + + if embed_cls: + self.cls_emb = nn.Parameter(torch.empty(width)) + self.num_pos += 1 + else: + self.cls_emb = None + + self.token_embedding = nn.Embedding(vocab_size, width) + self.positional_embedding = nn.Parameter(torch.empty(self.num_pos, width)) + self.transformer = Transformer( + width=width, + layers=layers, + heads=heads, + ls_init_value=ls_init_value, + act_layer=act_layer, + norm_layer=norm_layer, + hook=self.hook.fork('transformer'), + ) + self.ln_final = norm_layer(width) + + self.register_buffer('attn_mask', self.build_attention_mask(), persistent=False) + + self.init_parameters() + + def init_parameters(self): + nn.init.normal_(self.token_embedding.weight, std=0.02) + nn.init.normal_(self.positional_embedding, std=0.01) + if self.cls_emb is not None: + nn.init.normal_(self.cls_emb, std=0.01) + + proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5) + attn_std = self.transformer.width ** -0.5 + fc_std = (2 * self.transformer.width) ** -0.5 + for block in self.transformer.resblocks: + nn.init.normal_(block.attn.in_proj_weight, std=attn_std) + nn.init.normal_(block.attn.out_proj.weight, std=proj_std) + nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) + nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) + + if self.text_projection is not None: + nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.transformer.grad_checkpointing = enable + + def build_attention_mask(self): + # lazily create causal attention mask, with full attention between the tokens + # pytorch uses additive attention mask; fill with -inf + mask = torch.empty(self.num_pos, self.num_pos) + mask.fill_(float("-inf")) + mask.triu_(1) # zero out the lower diagonal + return mask + + def build_cls_mask(self, text, cast_dtype: torch.dtype): + cls_mask = (text != self.pad_id).unsqueeze(1) + cls_mask = F.pad(cls_mask, (1, 0, cls_mask.shape[2], 0), value=1.0) + additive_mask = torch.empty(cls_mask.shape, dtype=cast_dtype, device=cls_mask.device) + additive_mask.fill_(0) + additive_mask.masked_fill_(~cls_mask, float("-inf")) + additive_mask = torch.repeat_interleave(additive_mask, self.heads, 0) + return additive_mask + + def _repeat(self, t, N: int): + return t.reshape(1, 1, -1).repeat(N, 1, 1) + + def forward(self, text, attn_method: Text = 'direct'): + cast_dtype = self.transformer.get_cast_dtype() + seq_len = text.shape[1] + + x = self.token_embedding(text).to(cast_dtype) # [batch_size, n_ctx, d_model] + attn_mask = self.attn_mask + if self.cls_emb is not None: + seq_len += 1 + x = torch.cat([x, self._repeat(self.cls_emb, x.shape[0])], dim=1) + cls_mask = self.build_cls_mask(text, cast_dtype) + attn_mask = attn_mask[None, :seq_len, :seq_len] + cls_mask[:, :seq_len, :seq_len] + + x = x + self.positional_embedding[:seq_len].to(cast_dtype) + #x = x.permute(1, 0, 2) # NLD -> LND + x = self.transformer(x, attn_mask=attn_mask, attn_method=attn_method) + #x = x.permute(1, 0, 2) # LND -> NLD + + # x.shape = [batch_size, n_ctx, transformer.width] + # take features from the eot embedding (eot_token is the highest number in each sequence) + if self.cls_emb is not None: + pooled, tokens = x[:, -1], x[:, :-1] + pooled = self.ln_final(pooled) + else: + x = self.ln_final(x) + pooled, tokens = x[torch.arange(x.shape[0]), text.argmax(dim=-1)], x + + if self.text_projection is not None: + pooled = pooled @ self.text_projection + + self.hook.finalize() + + if self.output_tokens: + return pooled, tokens + + return pooled \ No newline at end of file diff --git a/API_CLIP/clip_prs/utils/vocab/bpe_simple_vocab_16e6.txt.gz b/API_CLIP/clip_prs/utils/vocab/bpe_simple_vocab_16e6.txt.gz new file mode 100644 index 0000000000000000000000000000000000000000..36a15856e00a06a9fbed8cdd34d2393fea4a3113 --- /dev/null +++ b/API_CLIP/clip_prs/utils/vocab/bpe_simple_vocab_16e6.txt.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a +size 1356917 diff --git a/API_CLIP/hook.py b/API_CLIP/hook.py new file mode 100644 index 0000000000000000000000000000000000000000..ccd20bfcf460e693329d8ae2af2983db28dd3b69 --- /dev/null +++ b/API_CLIP/hook.py @@ -0,0 +1,110 @@ +import time +import numpy as np +import torch +from PIL import Image +import glob +import sys +import argparse +import datetime +import json +from pathlib import Path + +class MaskHookLogger(object): + def __init__(self, model, device): + self.current_layer = 0 + self.device = device + self.attentions = [] + self.mlps = [] + self.post_ln_std = None + self.post_ln_mean = None + self.model = model + + @torch.no_grad() + def compute_attentions(self, ret): + if self.current_layer == self.layer_index: + bias_term = self.model.visual.transformer.resblocks[self.current_layer].attn.out_proj.bias + return_value = ret[:, 0] + return_value = return_value + bias_term[np.newaxis, np.newaxis] / (return_value.shape[1])# [b, n, d] + self.attentions.append(return_value.detach()) + self.current_layer += 1 + return ret + + @torch.no_grad() + def compute_mlps(self, ret): + if self.current_layer == self.layer_index + 1: + self.mlps.append(ret[:, 1:].detach()) # [b, n, d] + return ret + + @torch.no_grad() + def log_post_ln_mean(self, ret): + self.post_ln_mean = ret.detach() # [b, 1] + return ret + + @torch.no_grad() + def log_post_ln_std(self, ret): + self.post_ln_std = ret.detach() # [b, 1] + return ret + + def _normalize_mlps(self): + len_intermediates = self.current_layer * 2 - 1 + # This is just the normalization layer: + mean_centered = (self.mlps - + self.post_ln_mean[:, :, np.newaxis, np.newaxis] / len_intermediates) + + weighted_mean_centered = self.model.visual.ln_post.weight.detach() * mean_centered + weighted_mean_by_std = weighted_mean_centered / self.post_ln_std[:, :, np.newaxis, np.newaxis] + + bias_term = self.model.visual.ln_post.bias.detach() / len_intermediates + post_ln = weighted_mean_by_std + bias_term + return post_ln @ self.model.visual.proj.detach() + + def _normalize_attentions(self): + len_intermediates = self.current_layer * 2 - 1 # 2*l + 1 + normalization_term = self.attentions.shape[2] * 1 # n * h, h=1 + # This is just the normalization layer: + mean_centered = (self.attentions - + self.post_ln_mean[:, :, np.newaxis, np.newaxis] / + (len_intermediates * normalization_term)) + weighted_mean_centered = self.model.visual.ln_post.weight.detach() * mean_centered + weighted_mean_by_std = weighted_mean_centered / self.post_ln_std[:, :, np.newaxis, np.newaxis] + bias_term = self.model.visual.ln_post.bias.detach() / (len_intermediates * normalization_term) + post_ln = weighted_mean_by_std + bias_term + return post_ln @ self.model.visual.proj.detach() + + @torch.no_grad() + def finalize(self, representation): + """We calculate the post-ln scaling, project it and normalize by the last norm.""" + self.attentions = torch.stack(self.attentions, axis=1) # [b, 1, n, d] + self.mlps = torch.stack(self.mlps, axis=1) # [b, 1, n, d] + projected_attentions = self._normalize_attentions() + projected_mlps = self._normalize_mlps() + norm = representation.norm(dim=-1).detach() + return (projected_attentions / norm[:, np.newaxis, np.newaxis, np.newaxis], + projected_mlps / norm[:, np.newaxis, np.newaxis, np.newaxis]) + + def reinit(self): + self.current_layer = 0 + self.attentions = [] + self.mlps = [] + self.post_ln_mean = None + self.post_ln_std = None + torch.cuda.empty_cache() + + +def hook_prs_logger(model, device, layer_index = 23): + """Hooks a projected residual stream logger to the model.""" + prs = MaskHookLogger(model, device) + model.hook_manager.register('visual.transformer.resblocks.*.attn.out.post', + prs.compute_attentions) + + model.hook_manager.register('visual.transformer.resblocks.*.post', + prs.compute_mlps) + model.hook_manager.register('visual.ln_pre_post', + prs.compute_mlps) + model.hook_manager.register('visual.ln_post.mean', + prs.log_post_ln_mean) + model.hook_manager.register('visual.ln_post.sqrt_var', + prs.log_post_ln_std) + prs.layer_index = layer_index + + return prs diff --git a/API_CLIP/main.py b/API_CLIP/main.py new file mode 100644 index 0000000000000000000000000000000000000000..d0e223665688ee68601a1064705f56ea4447fbd6 --- /dev/null +++ b/API_CLIP/main.py @@ -0,0 +1,139 @@ +import os, time, base64, requests, json, sys, datetime, argparse +from itertools import product + +from PIL import Image +import cv2 + +import numpy as np +import torch +from torch.nn import functional as F +from torch.utils.data import DataLoader +import torchvision.transforms as T + +from .clip_prs.utils.factory import create_model_and_transforms, get_tokenizer +from .hook import hook_prs_logger + +def toImg(t): + return T.ToPILImage()(t) + +def invtrans(mask, image, method = Image.BICUBIC): + return mask.resize(image.size, method) + +def merge(mask, image, grap_scale = 200): + gray = np.ones((image.size[1], image.size[0], 3))*grap_scale + image_np = np.array(image).astype(np.float32)[..., :3] + mask_np = np.array(mask).astype(np.float32) + mask_np = mask_np / 255.0 + blended_np = image_np * mask_np[:, :, None] + (1 - mask_np[:, :, None]) * gray + blended_image = Image.fromarray((blended_np).astype(np.uint8)) + return blended_image + +def normalize(mat, method = "max"): + if method == "max": + return (mat.max() - mat) / (mat.max() - mat.min()) + elif method == "min": + return (mat - mat.min()) / (mat.max() - mat.min()) + else: + raise NotImplementedError + +def enhance(mat, coe=10): + mat = mat - mat.mean() + mat = mat / mat.std() + mat = mat * coe + mat = torch.sigmoid(mat) + mat = mat.clamp(0,1) + return mat + +def get_model(model_name = "ViT-L-14-336", layer_index = 23, device = "cuda:0"): # "ViT-L-14", "ViT-B-32" + ## Hyperparameters + pretrained = 'openai' # 'laion2b_s32b_b79k' + + ## Loading Model + model, _, preprocess = create_model_and_transforms(model_name, pretrained=pretrained) + model.to(device) + model.eval() + context_length = model.context_length + vocab_size = model.vocab_size + tokenizer = get_tokenizer(model_name) + + print("Model parameters:", f"{np.sum([int(np.prod(p.shape)) for p in model.parameters()]):,}") + print("Context length:", context_length) + print("Vocab size:", vocab_size) + print("Len of res:", len(model.visual.transformer.resblocks)) + + prs = hook_prs_logger(model, device, layer_index) + + return model, prs, preprocess, device, tokenizer + +def gen_mask(model, prs, preprocess, device, tokenizer, image_path_or_pil_images, questions): + ## Load image + images = [] + image_pils = [] + for image_path_or_pil_image in image_path_or_pil_images: + if isinstance(image_path_or_pil_image, str): + image_pil = Image.open(image_path_or_pil_image) + elif isinstance(image_path_or_pil_image, Image.Image): + image_pil = image_path_or_pil_image + else: + raise NotImplementedError + image = preprocess(image_pil)[np.newaxis, :, :, :] + images.append(image) + image_pils.append(image_pil) + image = torch.cat(images, dim = 0).to(device) + + ## Run the image: + prs.reinit() + with torch.no_grad(): + representation = model.encode_image(image, + attn_method='head', + normalize=False) + + attentions, mlps = prs.finalize(representation) + + ## Get the texts + lines = questions if isinstance(questions, list) else [questions] + print(lines[0]) + texts = tokenizer(lines).to(device) # tokenize + class_embeddings = model.encode_text(texts) + class_embedding = F.normalize(class_embeddings, dim=-1) + + attention_map = attentions[:, 0, 1:, :] + attention_map = torch.einsum('bnd,bd->bn', attention_map, class_embedding) + HW = int(np.sqrt(attention_map.shape[1])) + batch_size = attention_map.shape[0] + attention_map = attention_map.view(batch_size,HW,HW) + # print(HW) + + token_map = torch.einsum('bnd,bd->bn', mlps[:,0,:,:], class_embedding) + token_map = token_map.view(batch_size,HW,HW) + + return attention_map[0], token_map[0] + +def merge_mask(cls_mask, patch_mask, kernel_size = 3, enhance_coe = 10): + cls_mask = normalize(cls_mask, "min") + cls_mask = enhance(cls_mask, coe = enhance_coe) + + patch_mask = normalize(patch_mask, "max") + + assert kernel_size % 2 == 1 + padding_size = int((kernel_size - 1) / 2) + conv = torch.nn.Conv2d(1,1,kernel_size = kernel_size, padding = padding_size, padding_mode = "replicate", stride = 1, bias = False) + conv.weight.data = torch.ones_like(conv.weight.data) / kernel_size**2 + conv.to(cls_mask.device) + + cls_mask = conv(cls_mask.unsqueeze(0))[0] + + patch_mask = conv(patch_mask.unsqueeze(0))[0] + + mask = normalize(cls_mask + patch_mask - cls_mask * patch_mask, "min") + + return mask + +def blend_mask(image, cls_mask, patch_mask, enhance_coe, kernel_size, interpolate_method_name, grayscale): + mask = merge_mask(cls_mask, patch_mask, kernel_size = kernel_size, enhance_coe = enhance_coe) + mask = toImg(mask.detach().cpu().unsqueeze(0)) + interpolate_method = getattr(Image, interpolate_method_name) + mask = invtrans(mask, image, method = interpolate_method) + merged_image = merge(mask.convert("L"), image.convert("RGB"), grayscale).convert("RGB") + + return merged_image \ No newline at end of file diff --git a/API_LLaVA/functions.py b/API_LLaVA/functions.py new file mode 100644 index 0000000000000000000000000000000000000000..c7b4244e0b8878ce85940cb1a39f6cc74c3e8a50 --- /dev/null +++ b/API_LLaVA/functions.py @@ -0,0 +1,229 @@ +import argparse +import torch + +from llava.constants import ( + IMAGE_TOKEN_INDEX, + DEFAULT_IMAGE_TOKEN, + DEFAULT_IM_START_TOKEN, + DEFAULT_IM_END_TOKEN, + IMAGE_PLACEHOLDER, +) +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 ( + process_images, + tokenizer_image_token, + get_model_name_from_path, + KeywordsStoppingCriteria, +) +from llava.transformers.generation.stopping_criteria import MaxNewTokensCriteria + +from PIL import Image + +import requests +from PIL import Image +from io import BytesIO +import re + +def image_parser(args): + out = args.image_file.split(args.sep) + return out + +def load_image(image_file): + if image_file.startswith("http") or image_file.startswith("https"): + response = requests.get(image_file) + image = Image.open(BytesIO(response.content)).convert("RGB") + else: + image = Image.open(image_file).convert("RGB") + return image + + +def load_images(image_files): + out = [] + for image_file in image_files: + image = load_image(image_file) + out.append(image) + return out + +def get_preanswer(model, model_name, hl, tokenizer, image_processor, context_len, query, image): + sep = "," + temperature = 0 + top_p = None + num_beams = 1 + max_new_tokens = 1024 + conv_mode = None + + disable_torch_init() + + tokenizer, model, image_processor, context_len = tokenizer, model, image_processor, context_len + + hl = hl + + hl.reinit() + + qs = query + image_token_se = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + if IMAGE_PLACEHOLDER in qs: + if model.config.mm_use_im_start_end: + qs = re.sub(IMAGE_PLACEHOLDER, image_token_se, qs) + else: + qs = re.sub(IMAGE_PLACEHOLDER, DEFAULT_IMAGE_TOKEN, qs) + else: + if model.config.mm_use_im_start_end: + qs = image_token_se + "\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 conv_mode is not None and conv_mode != conv_mode: + print( + "[WARNING] the auto inferred conversation mode is {}, while `--conv-mode` is {}, using {}".format( + conv_mode, conv_mode, conv_mode + ) + ) + else: + conv_mode = conv_mode + + conv = conv_templates[conv_mode].copy() + conv.append_message(conv.roles[0], qs) + conv.append_message(conv.roles[1], None) + prompt = conv.get_prompt() + + images = [image] + images = [image.convert('RGB') if image.mode != 'RGB' else image for image in images] + + images_tensor = process_images( + images, + image_processor, + model.config + ).to(model.device, dtype=torch.float16) + + input_ids = ( + tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt") + .unsqueeze(0) + .to(model.device) + ) + + stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2 + keywords = [stop_str] + stopping_criteria = [ + KeywordsStoppingCriteria(keywords, tokenizer, input_ids), + MaxNewTokensCriteria(input_ids.shape[1], max_new_tokens) + ] + + with torch.inference_mode(): + output_ids = model.generate( + input_ids, + images=images_tensor, + do_sample=True if temperature > 0 else False, + temperature=temperature, + top_p=top_p, + num_beams=num_beams, + # max_new_tokens=max_new_tokens, + use_cache=True, + stopping_criteria=stopping_criteria, + ) + + attention_output = hl.finalize() + attention_output = attention_output.view(attention_output.shape[0],24,24) + attention_output = attention_output.detach() + + 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:].cpu(), skip_special_tokens=True + # )[0] + # outputs = outputs.strip() + # if outputs.endswith(stop_str): + # outputs = outputs[: -len(stop_str)] + # outputs = outputs.strip() + output = tokenizer.decode(output_ids[:, input_token_len:].cpu()[0]) + + token_mapping = get_token_mapping(tokenizer, output, output_ids[:, input_token_len:].cpu()[0]) + + return output, {"llava_attentions":attention_output.detach(), "llava_token_mapping":token_mapping} + +def clean_text(text): + cleaned_text = re.sub(r'^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$', '', text) + return cleaned_text + +def get_token_mapping(tokenizer, outputs, output_ids): + tokens = tokenizer.tokenize(outputs)[1:] + assert len(tokens) == len(output_ids) + current_position = 0 + offsets = [] + + for token in tokens: + cleaned_token = clean_text(token) + try: + token_start = outputs.find(cleaned_token, current_position) + except: + print(outputs, cleaned_token) + continue + token_end = token_start + len(cleaned_token) + offsets.append((token_start, token_end)) + current_position = token_end + + return offsets + +def from_preanswer_to_mask(highlight_text, query, cache_dict): + if highlight_text.strip() == query.strip() or highlight_text.strip() == "": + token_start_index = 0 + token_end_index = len(cache_dict["llava_token_mapping"]) - 1 + else: + text_start_index = query.find(highlight_text) + text_end_index = text_start_index + len(highlight_text) + + for token_index, (token_text_mapping_st, token_text_mapping_end) in enumerate(cache_dict["llava_token_mapping"]): + if token_text_mapping_st <= text_start_index: + token_start_index = token_index + if token_text_mapping_end >= text_end_index: + token_end_index = token_index + break + + attentions = cache_dict["llava_attentions"] + selected_attentions = attentions[token_start_index:token_end_index+1] + mask = selected_attentions.mean(dim=0) + return mask + +def get_model(model_path = "llava-v1.5-7b", device = "cuda:0"): + model_path = f"liuhaotian/{model_path}" + model_path = model_path + model_base = None + model_name = get_model_name_from_path(model_path) + + tokenizer, model, image_processor, context_len = load_pretrained_model( + model_path=model_path, + model_base=model_base, + model_name=model_name, + device= device, + # load_4bit = True, + ) + return tokenizer, model, image_processor, context_len, model_name + +if __name__ == "__main__": + prompt = "What are the things I should be cautious about when I visit here?" + image_file = "https://llava-vl.github.io/static/images/view.jpg" + image = Image.open(BytesIO(requests.get(image_file).content)).convert("RGB") + + tokenizer, model, image_processor, context_len, model_name = get_model() + + from .hook import hook_logger + hl = hook_logger(model, model.device, layer_index = 20) + output, cache_dict = get_preanswer(model, model_name, hl, tokenizer, image_processor, context_len, prompt, image) + + mask = from_preanswer_to_mask(output[10:20], output, cache_dict) \ No newline at end of file diff --git a/API_LLaVA/hook.py b/API_LLaVA/hook.py new file mode 100644 index 0000000000000000000000000000000000000000..1a34b99a32963a29f496da3e3115ff216ce9e75f --- /dev/null +++ b/API_LLaVA/hook.py @@ -0,0 +1,108 @@ +import time +import numpy as np +import torch +from PIL import Image +import glob +import sys +import argparse +import datetime +import json +from pathlib import Path + +from llava.hook import HookManager + +def init_hookmanager(module): + module.hook_manager = HookManager() + +class MaskHookLogger(object): + def __init__(self, model, device): + self.current_layer = 0 + self.device = device + self.attns = [] + self.projected_attns = [] + self.image_embed_range = [] + self.index = [] + self.model = model + + @torch.no_grad() + def compute_attentions(self, ret): + assert len(self.image_embed_range) > 0 + st, ed = self.image_embed_range[-1] + image_attention = ret[:,:,-1,st:ed].detach() + image_attention = image_attention.mean(dim = 1) + self.attns.append(image_attention) # [b, k] + return ret + + @torch.no_grad() + def compute_projected_attentions(self, ret): + assert len(self.image_embed_range) > 0 + st, ed = self.image_embed_range[-1] + image_attention = ret[:,-1,st:ed].detach() # [b, k, d] + self.projected_attns.append(image_attention) # [b, k, d] + return ret + + @torch.no_grad() + def compute_attentions_withsoftmax(self, ret): + assert len(self.image_embed_range) > 0 + st, ed = self.image_embed_range[-1] + image_attention = ret[:,:,-1,st:ed].detach() + image_attention = image_attention.softmax(dim = -1) + image_attention = image_attention.mean(dim = 1) + self.attns.append(image_attention) # [b, k] + return ret + + @torch.no_grad() + def compute_logits_index(self, ret): + next_token_logits = ret[:, -1, :] + index = next_token_logits.argmax(dim=-1) + self.index.append(index.item()) + return ret + + @torch.no_grad() + def finalize(self): + attns = torch.cat(self.attns, dim = 0).to(self.device) + return attns + + @torch.no_grad() + def finalize_projected_attn(self, norm_weight, proj): + assert len(self.index) == len(self.projected_attns) + mask = [] + for i in range(-4,-2): + index = self.index[i] + attns = self.projected_attns[i].to(self.device) # 1,k,d + input_dtype = attns.dtype + attns_var = attns.to(torch.float32).sum(dim = 1).pow(2).mean(-1, keepdim=True)# 1,d + attns_var = attns_var.unsqueeze(1)# 1,1,d + normalized_attns = attns * torch.rsqrt(attns_var + 1e-6) # 1,k,d + normalized_attns = norm_weight.to(normalized_attns.device) * normalized_attns.to(input_dtype) # 1,k,d + logits = proj(normalized_attns) + max_logits = logits[0,:,index] # k + mask.append(max_logits) + + mask = torch.stack(mask, dim = 0) + + return mask.mean(dim = 0) + + def reinit(self): + self.attns = [] + self.projected_attns = [] + self.image_embed_range = [] + self.index = [] + torch.cuda.empty_cache() + + def log_image_embeds_range(self, ret): + self.image_embed_range.append(ret[0][0]) + return ret + +def hook_logger(model, device, layer_index = 20): + """Hooks a projected residual stream logger to the model.""" + + init_hookmanager(model.model.layers[layer_index].self_attn) + + prs = MaskHookLogger(model, device) + model.model.layers[layer_index].self_attn.hook_manager.register('after_attn_mask', + prs.compute_attentions_withsoftmax) + + model.hooklogger = prs + + return prs diff --git a/API_LLaVA/main.py b/API_LLaVA/main.py new file mode 100644 index 0000000000000000000000000000000000000000..0b55f742f862f50b845ba5858959f8743a36031c --- /dev/null +++ b/API_LLaVA/main.py @@ -0,0 +1,82 @@ +## Imports +import os, time, argparse, base64, requests, os, json, sys, datetime +from itertools import product +import warnings +warnings.filterwarnings("ignore") + +# import cv2 +from PIL import Image + +import numpy as np +import torch +from torch.nn import functional as F +from torch.utils.data import DataLoader +from torchvision.datasets import ImageNet +import torchvision.transforms as T + +def readImg(p): + return Image.open(p) + +def toImg(t): + return T.ToPILImage()(t) + +def invtrans(mask, image, method = Image.BICUBIC): + return mask.resize(image.size, method) + +def merge(mask, image, grap_scale = 200): + gray = np.ones((image.size[1], image.size[0], 3))*grap_scale + image_np = np.array(image).astype(np.float32)[..., :3] + mask_np = np.array(mask).astype(np.float32) + mask_np = mask_np / 255.0 + blended_np = image_np * mask_np[:, :, None] + (1 - mask_np[:, :, None]) * gray + blended_image = Image.fromarray((blended_np).astype(np.uint8)) + return blended_image + +def normalize(mat, method = "max"): + if method == "max": + return (mat.max() - mat) / (mat.max() - mat.min()) + elif method == "min": + return (mat - mat.min()) / (mat.max() - mat.min()) + else: + raise NotImplementedError + +def enhance(mat, coe=10): + mat = mat - mat.mean() + mat = mat / mat.std() + mat = mat * coe + mat = torch.sigmoid(mat) + mat = mat.clamp(0,1) + return mat + +def revise_mask(patch_mask, kernel_size = 3, enhance_coe = 10): + + patch_mask = normalize(patch_mask, "min") + patch_mask = enhance(patch_mask, coe = enhance_coe) + + assert kernel_size % 2 == 1 + padding_size = int((kernel_size - 1) / 2) + conv = torch.nn.Conv2d(1,1,kernel_size = kernel_size, padding = padding_size, padding_mode = "replicate", stride = 1, bias = False) + conv.weight.data = torch.ones_like(conv.weight.data) / kernel_size**2 + conv.to(patch_mask.device) + + patch_mask = conv(patch_mask.unsqueeze(0))[0] + + mask = patch_mask + + return mask + +def blend_mask(image_path_or_pil_image, mask, enhance_coe, kernel_size, interpolate_method_name, grayscale): + mask = revise_mask(mask.float(), kernel_size = kernel_size, enhance_coe = enhance_coe) + mask = mask.detach().cpu() + mask = toImg(mask.reshape(1,24,24)) + + if isinstance(image_path_or_pil_image, Image.Image): + image = image_path_or_pil_image + else: + raise NotImplementedError + + interpolate_method = getattr(Image, interpolate_method_name) + mask = invtrans(mask, image, method = interpolate_method) + merged_image = merge(mask.convert("L"), image.convert("RGB"), grayscale).convert("RGB") + + return merged_image \ No newline at end of file diff --git a/app.py b/app.py new file mode 100644 index 0000000000000000000000000000000000000000..848fe9c24931f645e931787658b734965224c4a2 --- /dev/null +++ b/app.py @@ -0,0 +1,268 @@ +import os +import gradio as gr +import torch + +from API_LLaVA.functions import get_model as llava_get_model, get_preanswer as llava_get_preanswer, from_preanswer_to_mask as llava_from_preanswer_to_mask +from API_LLaVA.hook import hook_logger as llava_hook_logger +from API_LLaVA.main import blend_mask as llava_blend_mask + +from API_CLIP.main import get_model as clip_get_model, gen_mask as clip_gen_mask, blend_mask as clip_blend_mask + +DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') + +MARKDOWN = """ +
+

+ API: Attention Prompting on Image for Large Vision-Language Models +

+
+ [ arXiv paper ] + [ project page ] + [ python package ] + [ code ] +
+""" + +def init_clip(): + clip_model, clip_prs, clip_preprocess, _, clip_tokenizer = clip_get_model(model_name = "ViT-L-14-336", layer_index = 22, device= DEVICE) + return {"clip_model": clip_model, "clip_prs": clip_prs, "clip_preprocess": clip_preprocess, "clip_tokenizer": clip_tokenizer} + +def init_llava(): + llava_tokenizer, llava_model, llava_image_processor, llava_context_len, llava_model_name = llava_get_model("llava-v1.5-13b", device= DEVICE) + llava_hl = llava_hook_logger(llava_model, DEVICE, layer_index = 20) + return {"llava_tokenizer": llava_tokenizer, "llava_model": llava_model, "llava_image_processor": llava_image_processor, "llava_context_len": llava_context_len, "llava_model_name": llava_model_name, "llava_hl": llava_hl} + +def change_api_method(api_method): + new_text_pre_answer = gr.Textbox( + label="LLaVA Response", + info = 'Only used for LLaVA-Based API. Press "Pre-Answer" to generate the response.', + placeholder="", + value = "", + lines=4, + interactive=False, + type="text") + new_image_output = gr.Image( + label="API Masked Image", + type="pil", + interactive=False, + height=512 + ) + if api_method == "CLIP_Based API": + model_dict = init_clip() + new_generate_llava_response_button = gr.Button("Pre-Answer", interactive=False) + elif api_method == "LLaVA_Based API": + model_dict = init_llava() + new_generate_llava_response_button = gr.Button("Pre-Answer", interactive=True) + else: + raise NotImplementedError + return model_dict, {}, new_generate_llava_response_button, new_text_pre_answer, new_image_output + +def clear_cache(cache_dict): + return {} + +def clear_mask_cache(cache_dict): + if "llava_mask" in cache_dict.keys(): + del cache_dict["llava_mask"] + if "clip_mask" in cache_dict.keys(): + del cache_dict["clip_mask"] + return cache_dict + +def llava_pre_answer(image, query, cache_dict, model_dict): + pre_answer, cache_dict_update = llava_get_preanswer( + model_dict["llava_model"], + model_dict["llava_model_name"], + model_dict["llava_hl"], + model_dict["llava_tokenizer"], + model_dict["llava_image_processor"], + model_dict["llava_context_len"], + query, image) + cache_dict.update(cache_dict_update) + return pre_answer, cache_dict + +def generate_mask( + image, + query, + pre_answer, + highlight_text, + api_method, + enhance_coe, + kernel_size, + interpolate_method_name, + mask_grayscale, + cache_dict, + model_dict): + if api_method == "LLaVA_Based API": + assert highlight_text.strip() in pre_answer + if "llava_mask" in cache_dict.keys() and cache_dict["llava_mask"] is not None: + pass + else: + cache_dict["llava_mask"] = llava_from_preanswer_to_mask(highlight_text, pre_answer, cache_dict) + masked_image = llava_blend_mask(image, cache_dict["llava_mask"], enhance_coe, kernel_size, interpolate_method_name, mask_grayscale) + elif api_method == "CLIP_Based API": + # assert highlight_text in query + if "clip_mask" in cache_dict.keys() and cache_dict["clip_mask"] is not None: + pass + else: + cache_dict["clip_mask"] = clip_gen_mask( + model_dict["clip_model"], + model_dict["clip_prs"], + model_dict["clip_preprocess"], + DEVICE, + model_dict["clip_tokenizer"], + [image], + [highlight_text if highlight_text.strip() != "" else query]) + masked_image = clip_blend_mask(image, *cache_dict["clip_mask"], enhance_coe, kernel_size, interpolate_method_name, mask_grayscale) + else: + raise NotImplementedError + return masked_image, cache_dict + + +image_input = gr.Image( + label="Input Image", + type="pil", + interactive=True, + height=512 +) +image_output = gr.Image( + label="API Masked Image", + type="pil", + interactive=False, + height=512 +) + +text_query = gr.Textbox( + label="Query", + placeholder="Enter a query about the image", + lines=4, + type="text") +text_pre_answer = gr.Textbox( + label="LLaVA Response", + info = 'Only used for LLaVA-Based API. Press "Pre-Answer" to generate the response.', + placeholder="", + lines=4, + interactive=False, + type="text") +text_highlight_text = gr.Textbox( + label = "Hint Text.", + info = "The text based on which the mask will be generated. For CLIP-Based API, it should be a substring of the query. For LLaVA-Based API, it should be a substring of the pre-answer.", + placeholder="Enter the hint text", + lines=1, + type="text") + +radio_api_method = gr.Radio( + ["CLIP_Based API", "LLaVA_Based API"] if 'cuda' in DEVICE else ["CLIP_Based API"], + interactive=True, + value = "CLIP_Based API", + label="Type of API") +slider_mask_grayscale = gr.Slider( + minimum=0, + maximum=255, + step = 0.5, + value=100, + interactive=True, + info = "0: black mask, 255: white mask.", + label="Grayscale") +slider_enhance_coe = gr.Slider( + minimum=1, + maximum=50, + step = 1, + value=1, + interactive=True, + info = "The larger contrast, the greater the contrast between the bright and dark areas of the mask.", + label="Contrast") +slider_kernel_size = gr.Slider( + minimum=1, + maximum=9, + step = 2, + value=1, + interactive=True, + info = "The larger smoothness, the smoother the mask appears, reducing the rectangular shapes.", + label="Smoothness") +radio_interpolate_method_name = gr.Radio( + ["BICUBIC", "BILINEAR","BOX","LANCZOS", "NEAREST"], + value = "BICUBIC", + interactive=True, + label="Interpolation Method", + info="The interpolation method used during mask resizing.") + +generate_llava_response_button = gr.Button("Pre-Answer", interactive=False) +generate_mask_button = gr.Button("API Go!") + +with gr.Blocks() as demo: + gr.Markdown(MARKDOWN) + state_cache = gr.State({}) + state_model = gr.State(init_clip()) + with gr.Row(): + with gr.Column(): + image_input.render() + with gr.Column(): + image_output.render() + with gr.Row(): + radio_api_method.render() + with gr.Row(): + with gr.Column(): + with gr.Row(): + text_query.render() + with gr.Row(): + generate_llava_response_button.render() + with gr.Row(): + text_pre_answer.render() + with gr.Row(): + text_highlight_text.render() + with gr.Column(): + with gr.Row(): + slider_enhance_coe.render() + with gr.Row(): + slider_kernel_size.render() + with gr.Row(): + radio_interpolate_method_name.render() + with gr.Row(): + slider_mask_grayscale.render() + generate_mask_button.render() + + radio_api_method.change( + fn=change_api_method, + inputs = [radio_api_method], + outputs=[state_model, state_cache, generate_llava_response_button, text_pre_answer, image_output] + ) + + image_input.change( + fn=clear_cache, + inputs = state_cache, + outputs=state_cache + ) + text_query.change( + fn=clear_cache, + inputs = state_cache, + outputs=state_cache + ) + text_highlight_text.change( + fn=clear_mask_cache, + inputs = state_cache, + outputs=state_cache + ) + + generate_llava_response_button.click( + fn=llava_pre_answer, + inputs=[image_input, text_query, state_cache, state_model], + outputs=[text_pre_answer, state_cache] + ) + generate_mask_button.click( + fn=generate_mask, + inputs=[ + image_input, + text_query, + text_pre_answer, + text_highlight_text, + radio_api_method, + slider_enhance_coe, + slider_kernel_size, + radio_interpolate_method_name, + slider_mask_grayscale, + state_cache, + state_model + ], + outputs=[image_output, state_cache] + ) + +demo.queue(max_size = 1).launch(show_error=True) \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..2d1ff3b8044c7e70ac3a1e3b41c60eb02adbd1c4 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,30 @@ +torch==2.0.1 +torchvision==0.15.2 +transformers==4.31.0 +tokenizers>=0.12.1,<0.14 +sentencepiece==0.1.99 +shortuuid +accelerate==0.21.0 +peft==0.4.0 +bitsandbytes==0.41.0 +pydantic<2,>=1 +markdown2[all] +numpy==1.24.0 +scikit-learn==1.2.2 +gradio==3.35.2 +gradio_client==0.2.9 +requests +httpx==0.24.0 +uvicorn +fastapi +einops==0.6.1 +einops-exts==0.0.4 +timm==0.6.13 +ftfy +scipy +imageio +h5py +scikit-image +opencv-python +regex +git+https://github.com/yu-rp/apiprompting_llava_hf.git@master \ No newline at end of file