ZihengZ commited on
Commit
41e43cd
·
0 Parent(s):

Initial commit

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +37 -0
  2. .gradio/flagged/FinerCAM Output/4fed4b69cde6d672f2f4/image.webp +3 -0
  3. .gradio/flagged/FinerCAM Output/9519167382f9f6d861da/image.webp +3 -0
  4. .gradio/flagged/Upload Image/1fe9d088d209be5fd963/Screenshot 2025-04-03 at 5.14.41PM.png +3 -0
  5. .gradio/flagged/Upload Image/ba62db3d6e146a397c6a/Screenshot 2025-04-03 at 5.40.19PM.png +3 -0
  6. .gradio/flagged/dataset1.csv +2 -0
  7. .gradio/flagged/dataset2.csv +2 -0
  8. .gradio/flagged/dataset3.csv +2 -0
  9. README.md +13 -0
  10. app.py +132 -0
  11. clip/__init__.py +1 -0
  12. clip/__pycache__/__init__.cpython-310.pyc +0 -0
  13. clip/__pycache__/clip.cpython-310.pyc +0 -0
  14. clip/__pycache__/model.cpython-310.pyc +0 -0
  15. clip/__pycache__/simple_tokenizer.cpython-310.pyc +0 -0
  16. clip/bpe_simple_vocab_16e6.txt.gz +3 -0
  17. clip/clip.py +245 -0
  18. clip/model.py +517 -0
  19. clip/simple_tokenizer.py +132 -0
  20. data/aircraft.png +3 -0
  21. data/bird.png +3 -0
  22. data/car.png +3 -0
  23. data/car2.png +3 -0
  24. data/redwing.png +3 -0
  25. pytorch_grad_cam/__init__.py +16 -0
  26. pytorch_grad_cam/__pycache__/__init__.cpython-310.pyc +0 -0
  27. pytorch_grad_cam/__pycache__/__init__.cpython-39.pyc +0 -0
  28. pytorch_grad_cam/__pycache__/ablation_cam.cpython-310.pyc +0 -0
  29. pytorch_grad_cam/__pycache__/ablation_cam.cpython-39.pyc +0 -0
  30. pytorch_grad_cam/__pycache__/ablation_layer.cpython-310.pyc +0 -0
  31. pytorch_grad_cam/__pycache__/ablation_layer.cpython-39.pyc +0 -0
  32. pytorch_grad_cam/__pycache__/activations_and_gradients.cpython-310.pyc +0 -0
  33. pytorch_grad_cam/__pycache__/activations_and_gradients.cpython-39.pyc +0 -0
  34. pytorch_grad_cam/__pycache__/base_cam.cpython-310.pyc +0 -0
  35. pytorch_grad_cam/__pycache__/base_cam.cpython-39.pyc +0 -0
  36. pytorch_grad_cam/__pycache__/diff_cam.cpython-39.pyc +0 -0
  37. pytorch_grad_cam/__pycache__/eigen_cam.cpython-310.pyc +0 -0
  38. pytorch_grad_cam/__pycache__/eigen_cam.cpython-39.pyc +0 -0
  39. pytorch_grad_cam/__pycache__/eigen_grad_cam.cpython-310.pyc +0 -0
  40. pytorch_grad_cam/__pycache__/eigen_grad_cam.cpython-39.pyc +0 -0
  41. pytorch_grad_cam/__pycache__/finer_cam.cpython-310.pyc +0 -0
  42. pytorch_grad_cam/__pycache__/fullgrad_cam.cpython-310.pyc +0 -0
  43. pytorch_grad_cam/__pycache__/fullgrad_cam.cpython-39.pyc +0 -0
  44. pytorch_grad_cam/__pycache__/grad_cam.cpython-310.pyc +0 -0
  45. pytorch_grad_cam/__pycache__/grad_cam.cpython-39.pyc +0 -0
  46. pytorch_grad_cam/__pycache__/grad_cam_plusplus.cpython-310.pyc +0 -0
  47. pytorch_grad_cam/__pycache__/grad_cam_plusplus.cpython-39.pyc +0 -0
  48. pytorch_grad_cam/__pycache__/guided_backprop.cpython-310.pyc +0 -0
  49. pytorch_grad_cam/__pycache__/guided_backprop.cpython-39.pyc +0 -0
  50. pytorch_grad_cam/__pycache__/layer_cam.cpython-310.pyc +0 -0
.gitattributes ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.png filter=lfs diff=lfs merge=lfs -text
37
+ *.webp filter=lfs diff=lfs merge=lfs -text
.gradio/flagged/FinerCAM Output/4fed4b69cde6d672f2f4/image.webp ADDED

Git LFS Details

  • SHA256: a8bfcd5a6e580c18bce572466f265ac1f467279fba487ccf6d50fa1b66e64dfe
  • Pointer size: 130 Bytes
  • Size of remote file: 18.1 kB
.gradio/flagged/FinerCAM Output/9519167382f9f6d861da/image.webp ADDED

Git LFS Details

  • SHA256: 31a10e74527ebea2d8c5a68d143cf90eac3f47078059e501137f0b96be12a922
  • Pointer size: 130 Bytes
  • Size of remote file: 83.2 kB
.gradio/flagged/Upload Image/1fe9d088d209be5fd963/Screenshot 2025-04-03 at 5.14.41PM.png ADDED

Git LFS Details

  • SHA256: c5fb0568f74f70e5eb713911828fc346a273cbedc6e0ee00cca05eb8b22398cc
  • Pointer size: 132 Bytes
  • Size of remote file: 1.86 MB
.gradio/flagged/Upload Image/ba62db3d6e146a397c6a/Screenshot 2025-04-03 at 5.40.19PM.png ADDED

Git LFS Details

  • SHA256: 8736bed06f89fb6bad50840565b14fd46028f08b76491710f386196ad8318778
  • Pointer size: 131 Bytes
  • Size of remote file: 690 kB
.gradio/flagged/dataset1.csv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ Target,Compared Target,Upload Image,Processed Image,timestamp
2
+ ,,,,2025-04-03 17:04:53.125226
.gradio/flagged/dataset2.csv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ Target,Compared Target,Upload Image,FinerCAM Output,timestamp
2
+ Bird,Red epaulets,.gradio/flagged/Upload Image/1fe9d088d209be5fd963/Screenshot 2025-04-03 at 5.14.41PM.png,.gradio/flagged/FinerCAM Output/9519167382f9f6d861da/image.webp,2025-04-03 17:25:35.547658
.gradio/flagged/dataset3.csv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ Target,Compared Target,Upload Image,Weight (for FinerWeightedTarget),FinerCAM Output,timestamp
2
+ Red epaulets,Bird,.gradio/flagged/Upload Image/ba62db3d6e146a397c6a/Screenshot 2025-04-03 at 5.40.19PM.png,0,.gradio/flagged/FinerCAM Output/4fed4b69cde6d672f2f4/image.webp,2025-04-03 17:41:30.454960
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Playground
3
+ emoji: 🏢
4
+ colorFrom: yellow
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: 5.23.3
8
+ app_file: app.py
9
+ pinned: false
10
+ license: mit
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import clip
4
+ from PIL import Image
5
+ import numpy as np
6
+ import cv2
7
+ from pytorch_grad_cam import FinerCAM
8
+ from pytorch_grad_cam.utils.image import show_cam_on_image
9
+ from pytorch_grad_cam.utils.model_targets import FinerWeightedTarget
10
+ from torchvision.transforms import Compose, Resize, ToTensor, Normalize
11
+ from torchvision.transforms import InterpolationMode
12
+ import os
13
+
14
+ # Load CLIP model
15
+ device = "cuda" if torch.cuda.is_available() else "cpu"
16
+ model, _ = clip.load("ViT-B/16", device=device)
17
+
18
+ BICUBIC = InterpolationMode.BICUBIC
19
+ PATCH_SIZE = 16
20
+
21
+ def _convert_image_to_rgb(image):
22
+ return image.convert("RGB")
23
+
24
+ def _transform_resize(h, w):
25
+ return Compose([
26
+ Resize((h, w), interpolation=BICUBIC),
27
+ _convert_image_to_rgb,
28
+ ToTensor(),
29
+ Normalize((0.48145466, 0.4578275, 0.40821073),
30
+ (0.26862954, 0.26130258, 0.27577711)),
31
+ ])
32
+
33
+ def preprocess_uploaded_image(uploaded_image, ori_height, ori_width):
34
+ preprocess = _transform_resize(
35
+ int(np.ceil(ori_height / PATCH_SIZE) * PATCH_SIZE),
36
+ int(np.ceil(ori_width / PATCH_SIZE) * PATCH_SIZE)
37
+ )
38
+ image = preprocess(uploaded_image)
39
+ return [image]
40
+
41
+ def reshape_transform(tensor, height=28, width=28):
42
+ tensor = tensor.permute(1, 0, 2)
43
+ result = tensor[:, 1:, :].reshape(tensor.size(0), height, width, tensor.size(2))
44
+ result = result.transpose(2, 3).transpose(1, 2)
45
+ return result
46
+
47
+ def zeroshot_classifier(classnames, templates, model):
48
+ with torch.no_grad():
49
+ zeroshot_weights = []
50
+ for classname in classnames:
51
+ texts = [template.format(classname) for template in templates]
52
+ texts = clip.tokenize(texts).to(device)
53
+ class_embeddings = model.encode_text(texts)
54
+ class_embeddings /= class_embeddings.norm(dim=-1, keepdim=True)
55
+ class_embedding = class_embeddings.mean(dim=0)
56
+ class_embedding /= class_embedding.norm()
57
+ zeroshot_weights.append(class_embedding)
58
+ zeroshot_weights = torch.stack(zeroshot_weights, dim=1).to(device)
59
+ return zeroshot_weights.t()
60
+
61
+ def process_inputs(target_text, compared_text, image, weight_value):
62
+ if image is None or not target_text or not compared_text:
63
+ return None
64
+
65
+ image = image.convert("RGB")
66
+ ori_width, ori_height = image.size
67
+ ms_imgs = preprocess_uploaded_image(image, ori_height, ori_width)
68
+ ms_imgs = [ms_imgs[0]]
69
+
70
+ class_names = [target_text, compared_text]
71
+ text_features = zeroshot_classifier(class_names, ['a clean origami {}.'], model)
72
+
73
+ target_layers = [model.visual.transformer.resblocks[-1].ln_1]
74
+ cam = FinerCAM(model=model, target_layers=target_layers, reshape_transform=reshape_transform)
75
+
76
+ for ms_image in ms_imgs:
77
+ ms_image = ms_image.unsqueeze(0).to(device)
78
+ h, w = ms_image.shape[-2], ms_image.shape[-1]
79
+ image_features, _ = model.encode_image(ms_image, h, w)
80
+
81
+ input_tensor = [image_features, text_features, h, w]
82
+ targets = [FinerWeightedTarget(0, [1], weight_value)]
83
+ grayscale_cam, _, _ = cam(input_tensor=input_tensor, targets=targets, target_size=None, alpha=1, k=3)
84
+ grayscale_cam = grayscale_cam[0, :]
85
+ grayscale_cam_highres = cv2.resize(grayscale_cam, (ori_width, ori_height))
86
+
87
+ np_image = np.array(image) / 255.0
88
+ visualization = show_cam_on_image(np_image, grayscale_cam_highres, use_rgb=True)
89
+ result_image = Image.fromarray(visualization)
90
+
91
+ return result_image
92
+
93
+ return image
94
+
95
+ # Paths to example images
96
+ example_images = [
97
+ ["Bird", "Red epaulets", "data/redwing.png"],
98
+ ["Car", "Car Headlight", "data/car.png"],
99
+ ["Beak", "Bird", "data/bird.png"],
100
+ ["Aircraft wheel", "Aircraft", "data/aircraft.png"],
101
+ ["Car wheel", "Car", "data/car2.png"],
102
+
103
+
104
+
105
+ ]
106
+
107
+ # Gradio Interface
108
+ demo = gr.Interface(
109
+ fn=process_inputs,
110
+ inputs=[
111
+ gr.Textbox(label="Target"),
112
+ gr.Textbox(label="Compared Target"),
113
+ gr.Image(label="Upload Image", type="pil"),
114
+ gr.Slider(label="Comparison strength", minimum=0.0, maximum=1.0, value=1.0, step=0.01),
115
+ ],
116
+ outputs=gr.Image(label="FinerCAM Output"),
117
+ title="FinerCAM Visualizer with CLIP",
118
+ description="Upload an image and enter two target texts. Adjust the weight parameter.",
119
+ examples=[
120
+ ["Bird", "Red epaulets", "data/redwing.png", 1.0],
121
+ ["Car Headlight", "Car", "data/car.png", 1.0],
122
+ ["Beak", "Bird", "data/bird.png", 1.0],
123
+ ["Aircraft wheel", "Aircraft", "data/aircraft.png",1.0],
124
+ ["Car wheel", "Car", "data/car2.png",1.0],
125
+
126
+
127
+
128
+ ]
129
+ )
130
+
131
+ if __name__ == "__main__":
132
+ demo.launch()
clip/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .clip import *
clip/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (167 Bytes). View file
 
clip/__pycache__/clip.cpython-310.pyc ADDED
Binary file (8.99 kB). View file
 
clip/__pycache__/model.cpython-310.pyc ADDED
Binary file (16.6 kB). View file
 
clip/__pycache__/simple_tokenizer.cpython-310.pyc ADDED
Binary file (5.7 kB). View file
 
clip/bpe_simple_vocab_16e6.txt.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a
3
+ size 1356917
clip/clip.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import os
3
+ import urllib
4
+ import warnings
5
+ from typing import Any, Union, List
6
+ from pkg_resources import packaging
7
+
8
+ import torch
9
+ from PIL import Image
10
+ from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
11
+ from tqdm import tqdm
12
+
13
+ from .model import build_model
14
+ from .simple_tokenizer import SimpleTokenizer as _Tokenizer
15
+ from collections import OrderedDict
16
+
17
+ try:
18
+ from torchvision.transforms import InterpolationMode
19
+ BICUBIC = InterpolationMode.BICUBIC
20
+ except ImportError:
21
+ BICUBIC = Image.BICUBIC
22
+
23
+
24
+ if packaging.version.parse(torch.__version__) < packaging.version.parse("1.7.1"):
25
+ warnings.warn("PyTorch version 1.7.1 or higher is recommended")
26
+
27
+
28
+ __all__ = ["available_models", "load", "tokenize"]
29
+ _tokenizer = _Tokenizer()
30
+
31
+ _MODELS = {
32
+ "RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt",
33
+ "RN101": "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt",
34
+ "RN50x4": "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt",
35
+ "RN50x16": "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt",
36
+ "RN50x64": "https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt",
37
+ "ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt",
38
+ "ViT-B/16": "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt",
39
+ "ViT-L/14": "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt",
40
+ "ViT-L/14@336px": "https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt",
41
+ }
42
+
43
+
44
+ def _download(url: str, root: str):
45
+ os.makedirs(root, exist_ok=True)
46
+ filename = os.path.basename(url)
47
+
48
+ expected_sha256 = url.split("/")[-2]
49
+ download_target = os.path.join(root, filename)
50
+
51
+ if os.path.exists(download_target) and not os.path.isfile(download_target):
52
+ raise RuntimeError(f"{download_target} exists and is not a regular file")
53
+
54
+ if os.path.isfile(download_target):
55
+ if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256:
56
+ return download_target
57
+ else:
58
+ warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
59
+
60
+ with urllib.request.urlopen(url) as source, open(download_target, "wb") as output:
61
+ with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True, unit_divisor=1024) as loop:
62
+ while True:
63
+ buffer = source.read(8192)
64
+ if not buffer:
65
+ break
66
+
67
+ output.write(buffer)
68
+ loop.update(len(buffer))
69
+
70
+ if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256:
71
+ raise RuntimeError(f"Model has been downloaded but the SHA256 checksum does not not match")
72
+
73
+ return download_target
74
+
75
+
76
+ def _convert_image_to_rgb(image):
77
+ return image.convert("RGB")
78
+
79
+
80
+ def _transform(n_px):
81
+ return Compose([
82
+ Resize(n_px, interpolation=BICUBIC),
83
+ CenterCrop(n_px),
84
+ _convert_image_to_rgb,
85
+ ToTensor(),
86
+ Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
87
+ ])
88
+
89
+
90
+ def available_models() -> List[str]:
91
+ """Returns the names of available CLIP models"""
92
+ return list(_MODELS.keys())
93
+
94
+
95
+ def load(name: str, device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", jit: bool = False, download_root: str = None):
96
+ """Load a CLIP model
97
+
98
+ Parameters
99
+ ----------
100
+ name : str
101
+ A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict
102
+
103
+ device : Union[str, torch.device]
104
+ The device to put the loaded model
105
+
106
+ jit : bool
107
+ Whether to load the optimized JIT model or more hackable non-JIT model (default).
108
+
109
+ download_root: str
110
+ path to download the model files; by default, it uses "~/.cache/clip"
111
+
112
+ Returns
113
+ -------
114
+ model : torch.nn.Module
115
+ The CLIP model
116
+
117
+ preprocess : Callable[[PIL.Image], torch.Tensor]
118
+ A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
119
+ """
120
+ if name in _MODELS:
121
+ model_path = _download(_MODELS[name], download_root or os.path.expanduser("~/.cache/clip"))
122
+ elif os.path.isfile(name):
123
+ model_path = name
124
+ else:
125
+ raise RuntimeError(f"Model {name} not found; available models = {available_models()}")
126
+
127
+ with open(model_path, 'rb') as opened_file:
128
+ try:
129
+ # loading JIT archive
130
+ model = torch.jit.load(opened_file, map_location=device if jit else "cpu").eval()
131
+ state_dict = None
132
+ except RuntimeError:
133
+ # loading saved state dict
134
+ if jit:
135
+ warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead")
136
+ jit = False
137
+ if 'RN50' in model_path:
138
+ state_dict = torch.load(opened_file, map_location="cpu")
139
+ else:
140
+ state_dict0 = torch.load(model_path, map_location="cpu")
141
+ state_dict = OrderedDict()
142
+ for k in state_dict0.keys():
143
+ state_dict[k.replace('module.', '')] = state_dict0[k]
144
+
145
+
146
+ if not jit:
147
+ model = build_model(state_dict or model.state_dict()).to(device)
148
+ if str(device) == "cpu":
149
+ model.float()
150
+ return model, _transform(model.visual.input_resolution)
151
+
152
+ # patch the device names
153
+ device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[])
154
+ device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1]
155
+
156
+ def patch_device(module):
157
+ try:
158
+ graphs = [module.graph] if hasattr(module, "graph") else []
159
+ except RuntimeError:
160
+ graphs = []
161
+
162
+ if hasattr(module, "forward1"):
163
+ graphs.append(module.forward1.graph)
164
+
165
+ for graph in graphs:
166
+ for node in graph.findAllNodes("prim::Constant"):
167
+ if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"):
168
+ node.copyAttributes(device_node)
169
+
170
+ model.apply(patch_device)
171
+ patch_device(model.encode_image)
172
+ patch_device(model.encode_text)
173
+
174
+ # patch dtype to float32 on CPU
175
+ if str(device) == "cpu":
176
+ float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[])
177
+ float_input = list(float_holder.graph.findNode("aten::to").inputs())[1]
178
+ float_node = float_input.node()
179
+
180
+ def patch_float(module):
181
+ try:
182
+ graphs = [module.graph] if hasattr(module, "graph") else []
183
+ except RuntimeError:
184
+ graphs = []
185
+
186
+ if hasattr(module, "forward1"):
187
+ graphs.append(module.forward1.graph)
188
+
189
+ for graph in graphs:
190
+ for node in graph.findAllNodes("aten::to"):
191
+ inputs = list(node.inputs())
192
+ for i in [1, 2]: # dtype can be the second or third argument to aten::to()
193
+ if inputs[i].node()["value"] == 5:
194
+ inputs[i].node().copyAttributes(float_node)
195
+
196
+ model.apply(patch_float)
197
+ patch_float(model.encode_image)
198
+ patch_float(model.encode_text)
199
+
200
+ model.float()
201
+
202
+ return model, _transform(model.input_resolution.item())
203
+
204
+
205
+ def tokenize(texts: Union[str, List[str]], context_length: int = 77, truncate: bool = False) -> Union[torch.IntTensor, torch.LongTensor]:
206
+ """
207
+ Returns the tokenized representation of given input string(s)
208
+
209
+ Parameters
210
+ ----------
211
+ texts : Union[str, List[str]]
212
+ An input string or a list of input strings to tokenize
213
+
214
+ context_length : int
215
+ The context length to use; all CLIP models use 77 as the context length
216
+
217
+ truncate: bool
218
+ Whether to truncate the text in case its encoding is longer than the context length
219
+
220
+ Returns
221
+ -------
222
+ A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length].
223
+ We return LongTensor when torch version is <1.8.0, since older index_select requires indices to be long.
224
+ """
225
+ if isinstance(texts, str):
226
+ texts = [texts]
227
+
228
+ sot_token = _tokenizer.encoder["<|startoftext|>"]
229
+ eot_token = _tokenizer.encoder["<|endoftext|>"]
230
+ all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts]
231
+ if packaging.version.parse(torch.__version__) < packaging.version.parse("1.8.0"):
232
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
233
+ else:
234
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.int)
235
+
236
+ for i, tokens in enumerate(all_tokens):
237
+ if len(tokens) > context_length:
238
+ if truncate:
239
+ tokens = tokens[:context_length]
240
+ tokens[-1] = eot_token
241
+ else:
242
+ raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}")
243
+ result[i, :len(tokens)] = torch.tensor(tokens)
244
+
245
+ return result
clip/model.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from typing import Tuple, Union
3
+
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from torch import nn
8
+
9
+ def upsample_pos_emb(emb, new_size):
10
+ # upsample the pretrained embedding for higher resolution
11
+ # emb size NxD
12
+ first = emb[:1, :]
13
+ emb = emb[1:, :]
14
+ N, D = emb.size(0), emb.size(1)
15
+ size = int(np.sqrt(N))
16
+ assert size * size == N
17
+ #new_size = size * self.upsample
18
+ emb = emb.permute(1, 0)
19
+ emb = emb.view(1, D, size, size).contiguous()
20
+ emb = F.upsample(emb, size=new_size, mode='bilinear',)
21
+ emb = emb.view(D, -1).contiguous()
22
+ emb = emb.permute(1, 0)
23
+ emb = torch.cat([first, emb], 0)
24
+ emb = nn.parameter.Parameter(emb.half())
25
+ return emb
26
+
27
+ class Bottleneck(nn.Module):
28
+ expansion = 4
29
+
30
+ def __init__(self, inplanes, planes, stride=1):
31
+ super().__init__()
32
+
33
+ # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
34
+ self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
35
+ self.bn1 = nn.BatchNorm2d(planes)
36
+ self.relu1 = nn.ReLU(inplace=True)
37
+
38
+ self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
39
+ self.bn2 = nn.BatchNorm2d(planes)
40
+ self.relu2 = nn.ReLU(inplace=True)
41
+
42
+ self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
43
+
44
+ self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
45
+ self.bn3 = nn.BatchNorm2d(planes * self.expansion)
46
+ self.relu3 = nn.ReLU(inplace=True)
47
+
48
+ self.downsample = None
49
+ self.stride = stride
50
+
51
+ if stride > 1 or inplanes != planes * Bottleneck.expansion:
52
+ # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
53
+ self.downsample = nn.Sequential(OrderedDict([
54
+ ("-1", nn.AvgPool2d(stride)),
55
+ ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),
56
+ ("1", nn.BatchNorm2d(planes * self.expansion))
57
+ ]))
58
+
59
+ def forward(self, x: torch.Tensor):
60
+ identity = x
61
+
62
+ out = self.relu1(self.bn1(self.conv1(x)))
63
+ out = self.relu2(self.bn2(self.conv2(out)))
64
+ out = self.avgpool(out)
65
+ out = self.bn3(self.conv3(out))
66
+
67
+ if self.downsample is not None:
68
+ identity = self.downsample(x)
69
+
70
+ out += identity
71
+ out = self.relu3(out)
72
+ return out
73
+
74
+
75
+ class AttentionPool2d(nn.Module):
76
+ def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
77
+ super().__init__()
78
+ self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)
79
+ self.k_proj = nn.Linear(embed_dim, embed_dim)
80
+ self.q_proj = nn.Linear(embed_dim, embed_dim)
81
+ self.v_proj = nn.Linear(embed_dim, embed_dim)
82
+ self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
83
+ self.num_heads = num_heads
84
+
85
+ def forward(self, x, H, W):
86
+ x = x.reshape(x.shape[0], x.shape[1], x.shape[2] * x.shape[3]).permute(2, 0, 1) # NCHW -> (HW)NC
87
+ x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
88
+ self.positional_embedding_new = upsample_pos_emb(self.positional_embedding, (H//32,W//32))
89
+ x = x + self.positional_embedding_new[:, None, :].to(x.dtype) # (HW+1)NC
90
+ x, attn_weight = F.multi_head_attention_forward(
91
+ query=x, key=x, value=x,
92
+ embed_dim_to_check=x.shape[-1],
93
+ num_heads=self.num_heads,
94
+ q_proj_weight=self.q_proj.weight,
95
+ k_proj_weight=self.k_proj.weight,
96
+ v_proj_weight=self.v_proj.weight,
97
+ in_proj_weight=None,
98
+ in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
99
+ bias_k=None,
100
+ bias_v=None,
101
+ add_zero_attn=False,
102
+ dropout_p=0,
103
+ out_proj_weight=self.c_proj.weight,
104
+ out_proj_bias=self.c_proj.bias,
105
+ use_separate_proj_weight=True,
106
+ training=self.training,
107
+ need_weights=False
108
+ )
109
+ return x[0]
110
+
111
+
112
+ class ModifiedResNet(nn.Module):
113
+ """
114
+ A ResNet class that is similar to torchvision's but contains the following changes:
115
+ - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
116
+ - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
117
+ - The final pooling layer is a QKV attention instead of an average pool
118
+ """
119
+
120
+ def __init__(self, layers, output_dim, heads, input_resolution=224, width=64):
121
+ super().__init__()
122
+ self.output_dim = output_dim
123
+ self.input_resolution = input_resolution
124
+
125
+ # the 3-layer stem
126
+ self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
127
+ self.bn1 = nn.BatchNorm2d(width // 2)
128
+ self.relu1 = nn.ReLU(inplace=True)
129
+ self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
130
+ self.bn2 = nn.BatchNorm2d(width // 2)
131
+ self.relu2 = nn.ReLU(inplace=True)
132
+ self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
133
+ self.bn3 = nn.BatchNorm2d(width)
134
+ self.relu3 = nn.ReLU(inplace=True)
135
+ self.avgpool = nn.AvgPool2d(2)
136
+
137
+ # residual layers
138
+ self._inplanes = width # this is a *mutable* variable used during construction
139
+ self.layer1 = self._make_layer(width, layers[0])
140
+ self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
141
+ self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
142
+ self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
143
+
144
+ embed_dim = width * 32 # the ResNet feature dimension
145
+ self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
146
+
147
+ def _make_layer(self, planes, blocks, stride=1):
148
+ layers = [Bottleneck(self._inplanes, planes, stride)]
149
+
150
+ self._inplanes = planes * Bottleneck.expansion
151
+ for _ in range(1, blocks):
152
+ layers.append(Bottleneck(self._inplanes, planes))
153
+
154
+ return nn.Sequential(*layers)
155
+
156
+ def forward(self, x, H, W):
157
+ def stem(x):
158
+ x = self.relu1(self.bn1(self.conv1(x)))
159
+ x = self.relu2(self.bn2(self.conv2(x)))
160
+ x = self.relu3(self.bn3(self.conv3(x)))
161
+ x = self.avgpool(x)
162
+ return x
163
+
164
+ x = x.type(self.conv1.weight.dtype)
165
+ x = stem(x)
166
+ x = self.layer1(x)
167
+ x = self.layer2(x)
168
+ x = self.layer3(x)
169
+ x = self.layer4(x)#(1,,2048, 7, 7)
170
+ x_pooled = self.attnpool(x, H, W)
171
+
172
+ return x_pooled
173
+
174
+
175
+ class LayerNorm(nn.LayerNorm):
176
+ """Subclass torch's LayerNorm to handle fp16."""
177
+
178
+ def forward(self, x: torch.Tensor):
179
+ orig_type = x.dtype
180
+ ret = super().forward(x.type(torch.float32))
181
+ return ret.type(orig_type)
182
+
183
+
184
+ class QuickGELU(nn.Module):
185
+ def forward(self, x: torch.Tensor):
186
+ return x * torch.sigmoid(1.702 * x)
187
+
188
+
189
+ class ResidualAttentionBlock(nn.Module):
190
+ def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
191
+ super().__init__()
192
+
193
+ self.attn = nn.MultiheadAttention(d_model, n_head)
194
+ self.ln_1 = LayerNorm(d_model)
195
+ self.mlp = nn.Sequential(OrderedDict([
196
+ ("c_fc", nn.Linear(d_model, d_model * 4)),
197
+ ("gelu", QuickGELU()),
198
+ ("c_proj", nn.Linear(d_model * 4, d_model))
199
+ ]))
200
+ self.ln_2 = LayerNorm(d_model)
201
+ self.attn_mask = attn_mask
202
+
203
+ def attention(self, x: torch.Tensor):
204
+ self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
205
+ return self.attn(x, x, x, need_weights=True, attn_mask=self.attn_mask)#[0]
206
+
207
+ def forward(self, x: torch.Tensor):
208
+ attn_output, attn_weight = self.attention(self.ln_1(x))#(L,N,E) (N,L,L)
209
+ x = x + attn_output
210
+ x = x + self.mlp(self.ln_2(x))
211
+ return x, attn_weight
212
+
213
+
214
+
215
+ class Transformer(nn.Module):
216
+ def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):
217
+ super().__init__()
218
+ self.width = width
219
+ self.layers = layers
220
+ self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])
221
+
222
+ def forward(self, x: torch.Tensor):
223
+ attn_weights = []
224
+ with torch.no_grad():
225
+ layers = self.layers if x.shape[0] == 77 else self.layers-1
226
+ for i in range(layers):
227
+ x, attn_weight = self.resblocks[i](x)
228
+ attn_weights.append(attn_weight)
229
+ '''
230
+ for i in range(self.layers-1, self.layers):
231
+ x, attn_weight = self.resblocks[i](x)
232
+ attn_weights.append(attn_weight)
233
+ #feature_map_list.append(x)
234
+ '''
235
+ return x, attn_weights
236
+
237
+
238
+ class VisionTransformer(nn.Module):
239
+ def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int):
240
+ super().__init__()
241
+ self.input_resolution = input_resolution
242
+ self.output_dim = output_dim
243
+ self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
244
+
245
+ scale = width ** -0.5
246
+ self.class_embedding = nn.Parameter(scale * torch.randn(width))
247
+ self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
248
+ self.ln_pre = LayerNorm(width)
249
+
250
+ self.transformer = Transformer(width, layers, heads)
251
+
252
+ self.ln_post = LayerNorm(width)
253
+ self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
254
+ self.patch_size = patch_size
255
+
256
+ def forward(self, x: torch.Tensor, H, W):
257
+
258
+
259
+ self.positional_embedding_new = upsample_pos_emb(self.positional_embedding, (H//16,W//16))
260
+ x = self.conv1(x) # shape = [*, width, grid, grid]
261
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
262
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
263
+ 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]
264
+ x = x + self.positional_embedding_new.to(x.dtype)
265
+ x = self.ln_pre(x)
266
+
267
+ x = x.permute(1, 0, 2) # NLD -> LND
268
+ x, attn_weight = self.transformer(x)
269
+ '''
270
+ x = x.permute(1, 0, 2) # LND -> NLD
271
+
272
+ x = self.ln_post(x)
273
+ #x = x[:, 0, :]
274
+ #x = x[:,1:,:]
275
+ x = torch.mean(x[:,1:,:],dim=1)
276
+ #feature_map_list.append(x)
277
+
278
+ if self.proj is not None:
279
+ x = x @ self.proj
280
+ '''
281
+
282
+ return x, attn_weight#cls_attn
283
+
284
+
285
+ class CLIP(nn.Module):
286
+ def __init__(self,
287
+ embed_dim: int,
288
+ # vision
289
+ image_resolution: int,
290
+ vision_layers: Union[Tuple[int, int, int, int], int],
291
+ vision_width: int,
292
+ vision_patch_size: int,
293
+ # text
294
+ context_length: int,
295
+ vocab_size: int,
296
+ transformer_width: int,
297
+ transformer_heads: int,
298
+ transformer_layers: int
299
+ ):
300
+ super().__init__()
301
+
302
+ self.context_length = context_length
303
+
304
+ if isinstance(vision_layers, (tuple, list)):
305
+ vision_heads = vision_width * 32 // 64
306
+ self.visual = ModifiedResNet(
307
+ layers=vision_layers,
308
+ output_dim=embed_dim,
309
+ heads=vision_heads,
310
+ input_resolution=image_resolution,
311
+ width=vision_width
312
+ )
313
+ else:
314
+ vision_heads = vision_width // 64
315
+ self.visual = VisionTransformer(
316
+ input_resolution=image_resolution,
317
+ patch_size=vision_patch_size,
318
+ width=vision_width,
319
+ layers=vision_layers,
320
+ heads=vision_heads,
321
+ output_dim=embed_dim
322
+ )
323
+
324
+ self.transformer = Transformer(
325
+ width=transformer_width,
326
+ layers=transformer_layers,
327
+ heads=transformer_heads,
328
+ attn_mask=self.build_attention_mask()
329
+ )
330
+
331
+ self.vocab_size = vocab_size
332
+ self.token_embedding = nn.Embedding(vocab_size, transformer_width)
333
+ self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))
334
+ self.ln_final = LayerNorm(transformer_width)
335
+
336
+ self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
337
+ self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
338
+
339
+ self.initialize_parameters()
340
+
341
+ def initialize_parameters(self):
342
+ nn.init.normal_(self.token_embedding.weight, std=0.02)
343
+ nn.init.normal_(self.positional_embedding, std=0.01)
344
+
345
+ if isinstance(self.visual, ModifiedResNet):
346
+ if self.visual.attnpool is not None:
347
+ std = self.visual.attnpool.c_proj.in_features ** -0.5
348
+ nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std)
349
+ nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std)
350
+ nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std)
351
+ nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std)
352
+
353
+ for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]:
354
+ for name, param in resnet_block.named_parameters():
355
+ if name.endswith("bn3.weight"):
356
+ nn.init.zeros_(param)
357
+
358
+ proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
359
+ attn_std = self.transformer.width ** -0.5
360
+ fc_std = (2 * self.transformer.width) ** -0.5
361
+ for block in self.transformer.resblocks:
362
+ nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
363
+ nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
364
+ nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
365
+ nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
366
+
367
+ if self.text_projection is not None:
368
+ nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
369
+
370
+ def build_attention_mask(self):
371
+ # lazily create causal attention mask, with full attention between the vision tokens
372
+ # pytorch uses additive attention mask; fill with -inf
373
+ mask = torch.empty(self.context_length, self.context_length)
374
+ mask.fill_(float("-inf"))
375
+ mask.triu_(1) # zero out the lower diagonal
376
+ return mask
377
+
378
+ @property
379
+ def dtype(self):
380
+ return self.visual.conv1.weight.dtype
381
+
382
+ def encode_image(self, image, H, W):
383
+ return self.visual(image.type(self.dtype), H, W)
384
+
385
+ def encode_text(self, text):
386
+ x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
387
+
388
+ x = x + self.positional_embedding.type(self.dtype)
389
+ x = x.permute(1, 0, 2) # NLD -> LND
390
+ x, attn_weight = self.transformer(x)
391
+ x = x.permute(1, 0, 2) # LND -> NLD
392
+ x = self.ln_final(x).type(self.dtype)
393
+
394
+ # x.shape = [batch_size, n_ctx, transformer.width]
395
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
396
+ x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
397
+
398
+ return x
399
+
400
+ def forward_last_layer(self, image_features, text_features):
401
+ x, attn_weight = self.visual.transformer.resblocks[self.visual.transformer.layers-1](image_features)
402
+ x = x.permute(1, 0, 2) # LND -> NLD
403
+
404
+ x = self.visual.ln_post(x)
405
+ x = torch.mean(x[:, 1:, :], dim=1)
406
+
407
+ if self.visual.proj is not None:
408
+ x = x @ self.visual.proj
409
+
410
+ image_features = x
411
+
412
+ # normalized features
413
+ image_features = image_features / image_features.norm(dim=1, keepdim=True)
414
+ text_features = text_features / text_features.norm(dim=1, keepdim=True)
415
+ # cosine similarity as logits
416
+ logit_scale = self.logit_scale.exp()
417
+ logits_per_image = logit_scale * image_features @ text_features.t()
418
+
419
+ # shape = [global_batch_size, global_batch_size]
420
+ # logits_per_image = logits_per_image.softmax(dim=-1)
421
+
422
+ return logits_per_image, attn_weight
423
+
424
+
425
+
426
+
427
+ def forward(self, image, text):
428
+ image_features, feature_map, cls_attn = self.encode_image(image)
429
+ with torch.no_grad():
430
+ text_features = self.encode_text(text)
431
+
432
+ # normalized features
433
+ image_features = image_features / image_features.norm(dim=1, keepdim=True)
434
+ text_features = text_features / text_features.norm(dim=1, keepdim=True)
435
+
436
+ # cosine similarity as logits
437
+ logit_scale = self.logit_scale.exp()
438
+ logits_per_image = logit_scale * image_features @ text_features.t()
439
+ #logits_per_text = logits_per_image.t()
440
+
441
+ # shape = [global_batch_size, global_batch_size]
442
+ return logits_per_image, logits_per_text
443
+
444
+
445
+ def convert_weights(model: nn.Module):
446
+ """Convert applicable model parameters to fp16"""
447
+
448
+ def _convert_weights_to_fp16(l):
449
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
450
+ l.weight.data = l.weight.data.half()
451
+ if l.bias is not None:
452
+ l.bias.data = l.bias.data.half()
453
+
454
+ if isinstance(l, nn.MultiheadAttention):
455
+ for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
456
+ tensor = getattr(l, attr)
457
+ if tensor is not None:
458
+ tensor.data = tensor.data.half()
459
+
460
+ for name in ["text_projection", "proj"]:
461
+ if hasattr(l, name):
462
+ attr = getattr(l, name)
463
+ if attr is not None:
464
+ attr.data = attr.data.half()
465
+
466
+ model.apply(_convert_weights_to_fp16)
467
+
468
+
469
+ def build_model(state_dict: dict):
470
+ vit = "visual.proj" in state_dict
471
+ '''
472
+ inv_freq = 1. / (10000 ** (torch.arange(0, 2048, 2, dtype=torch.float) / 2048))
473
+ position = torch.arange(50, dtype=torch.float)
474
+ sinusoid_inp = torch.einsum('i,j -> ij', position, inv_freq)
475
+ embeddings = torch.cat((sinusoid_inp.sin(), sinusoid_inp.cos()), dim=-1) / 2048 ** 0.5
476
+ state_dict["visual.attnpool.positional_embedding"] = embeddings
477
+ '''
478
+ #state_dict["visual.positional_embedding"] = upsample_pos_emb(state_dict["visual.positional_embedding"], 28)
479
+
480
+
481
+ if vit:
482
+ vision_width = state_dict["visual.conv1.weight"].shape[0]
483
+ vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
484
+ vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
485
+ grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
486
+ image_resolution = vision_patch_size * grid_size
487
+ else:
488
+ 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]]
489
+ vision_layers = tuple(counts)
490
+ vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
491
+ output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
492
+ vision_patch_size = None
493
+ assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
494
+ image_resolution = output_width * 32
495
+
496
+ embed_dim = state_dict["text_projection"].shape[1]
497
+ context_length = state_dict["positional_embedding"].shape[0]
498
+ vocab_size = state_dict["token_embedding.weight"].shape[0]
499
+ transformer_width = state_dict["ln_final.weight"].shape[0]
500
+ transformer_heads = transformer_width // 64
501
+ transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks")))
502
+
503
+ model = CLIP(
504
+ embed_dim,
505
+ image_resolution, vision_layers, vision_width, vision_patch_size,
506
+ context_length, vocab_size, transformer_width, transformer_heads, transformer_layers
507
+ )
508
+
509
+ for key in ["input_resolution", "context_length", "vocab_size"]:
510
+ if key in state_dict:
511
+ del state_dict[key]
512
+
513
+
514
+
515
+ convert_weights(model)
516
+ model.load_state_dict(state_dict)
517
+ return model.eval()
clip/simple_tokenizer.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gzip
2
+ import html
3
+ import os
4
+ from functools import lru_cache
5
+
6
+ import ftfy
7
+ import regex as re
8
+
9
+
10
+ @lru_cache()
11
+ def default_bpe():
12
+ return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")
13
+
14
+
15
+ @lru_cache()
16
+ def bytes_to_unicode():
17
+ """
18
+ Returns list of utf-8 byte and a corresponding list of unicode strings.
19
+ The reversible bpe codes work on unicode strings.
20
+ This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
21
+ When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
22
+ This is a signficant percentage of your normal, say, 32K bpe vocab.
23
+ To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
24
+ And avoids mapping to whitespace/control characters the bpe code barfs on.
25
+ """
26
+ bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1))
27
+ cs = bs[:]
28
+ n = 0
29
+ for b in range(2**8):
30
+ if b not in bs:
31
+ bs.append(b)
32
+ cs.append(2**8+n)
33
+ n += 1
34
+ cs = [chr(n) for n in cs]
35
+ return dict(zip(bs, cs))
36
+
37
+
38
+ def get_pairs(word):
39
+ """Return set of symbol pairs in a word.
40
+ Word is represented as tuple of symbols (symbols being variable-length strings).
41
+ """
42
+ pairs = set()
43
+ prev_char = word[0]
44
+ for char in word[1:]:
45
+ pairs.add((prev_char, char))
46
+ prev_char = char
47
+ return pairs
48
+
49
+
50
+ def basic_clean(text):
51
+ text = ftfy.fix_text(text)
52
+ text = html.unescape(html.unescape(text))
53
+ return text.strip()
54
+
55
+
56
+ def whitespace_clean(text):
57
+ text = re.sub(r'\s+', ' ', text)
58
+ text = text.strip()
59
+ return text
60
+
61
+
62
+ class SimpleTokenizer(object):
63
+ def __init__(self, bpe_path: str = default_bpe()):
64
+ self.byte_encoder = bytes_to_unicode()
65
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
66
+ merges = gzip.open(bpe_path).read().decode("utf-8").split('\n')
67
+ merges = merges[1:49152-256-2+1]
68
+ merges = [tuple(merge.split()) for merge in merges]
69
+ vocab = list(bytes_to_unicode().values())
70
+ vocab = vocab + [v+'</w>' for v in vocab]
71
+ for merge in merges:
72
+ vocab.append(''.join(merge))
73
+ vocab.extend(['<|startoftext|>', '<|endoftext|>'])
74
+ self.encoder = dict(zip(vocab, range(len(vocab))))
75
+ self.decoder = {v: k for k, v in self.encoder.items()}
76
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
77
+ self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'}
78
+ self.pat = re.compile(r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE)
79
+
80
+ def bpe(self, token):
81
+ if token in self.cache:
82
+ return self.cache[token]
83
+ word = tuple(token[:-1]) + ( token[-1] + '</w>',)
84
+ pairs = get_pairs(word)
85
+
86
+ if not pairs:
87
+ return token+'</w>'
88
+
89
+ while True:
90
+ bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf')))
91
+ if bigram not in self.bpe_ranks:
92
+ break
93
+ first, second = bigram
94
+ new_word = []
95
+ i = 0
96
+ while i < len(word):
97
+ try:
98
+ j = word.index(first, i)
99
+ new_word.extend(word[i:j])
100
+ i = j
101
+ except:
102
+ new_word.extend(word[i:])
103
+ break
104
+
105
+ if word[i] == first and i < len(word)-1 and word[i+1] == second:
106
+ new_word.append(first+second)
107
+ i += 2
108
+ else:
109
+ new_word.append(word[i])
110
+ i += 1
111
+ new_word = tuple(new_word)
112
+ word = new_word
113
+ if len(word) == 1:
114
+ break
115
+ else:
116
+ pairs = get_pairs(word)
117
+ word = ' '.join(word)
118
+ self.cache[token] = word
119
+ return word
120
+
121
+ def encode(self, text):
122
+ bpe_tokens = []
123
+ text = whitespace_clean(basic_clean(text)).lower()
124
+ for token in re.findall(self.pat, text):
125
+ token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))
126
+ bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))
127
+ return bpe_tokens
128
+
129
+ def decode(self, tokens):
130
+ text = ''.join([self.decoder[token] for token in tokens])
131
+ text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('</w>', ' ')
132
+ return text
data/aircraft.png ADDED

Git LFS Details

  • SHA256: 45212d5eb71a323d209ffc7967e414c915e29392ff589a365feb971c5fc80367
  • Pointer size: 132 Bytes
  • Size of remote file: 2.98 MB
data/bird.png ADDED

Git LFS Details

  • SHA256: 03a9265b8a1076ca6b0dd96ff822d6a05c7c075aa26c3d1f1f14504bf883355f
  • Pointer size: 131 Bytes
  • Size of remote file: 730 kB
data/car.png ADDED

Git LFS Details

  • SHA256: 1a542335a4efc0b910768d5775106a9a62135dfcdb414706e99b4d7b0a878c42
  • Pointer size: 131 Bytes
  • Size of remote file: 361 kB
data/car2.png ADDED

Git LFS Details

  • SHA256: 6aa84b7ea79fd1c66f068836120c2fdcc8215deb8847a03c05aaa2645d25137c
  • Pointer size: 131 Bytes
  • Size of remote file: 240 kB
data/redwing.png ADDED

Git LFS Details

  • SHA256: 8736bed06f89fb6bad50840565b14fd46028f08b76491710f386196ad8318778
  • Pointer size: 131 Bytes
  • Size of remote file: 690 kB
pytorch_grad_cam/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pytorch_grad_cam.grad_cam import GradCAM
2
+ from pytorch_grad_cam.ablation_layer import AblationLayer, AblationLayerVit, AblationLayerFasterRCNN
3
+ from pytorch_grad_cam.ablation_cam import AblationCAM
4
+ from pytorch_grad_cam.xgrad_cam import XGradCAM
5
+ from pytorch_grad_cam.grad_cam_plusplus import GradCAMPlusPlus
6
+ from pytorch_grad_cam.score_cam import ScoreCAM
7
+ from pytorch_grad_cam.layer_cam import LayerCAM
8
+ from pytorch_grad_cam.eigen_cam import EigenCAM
9
+ from pytorch_grad_cam.eigen_grad_cam import EigenGradCAM
10
+ from pytorch_grad_cam.fullgrad_cam import FullGrad
11
+ from pytorch_grad_cam.finer_cam import FinerCAM
12
+
13
+ from pytorch_grad_cam.guided_backprop import GuidedBackpropReLUModel
14
+ from pytorch_grad_cam.activations_and_gradients import ActivationsAndGradients
15
+ import pytorch_grad_cam.utils.model_targets
16
+ import pytorch_grad_cam.utils.reshape_transforms
pytorch_grad_cam/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.2 kB). View file
 
pytorch_grad_cam/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (1.2 kB). View file
 
pytorch_grad_cam/__pycache__/ablation_cam.cpython-310.pyc ADDED
Binary file (3.73 kB). View file
 
pytorch_grad_cam/__pycache__/ablation_cam.cpython-39.pyc ADDED
Binary file (3.66 kB). View file
 
pytorch_grad_cam/__pycache__/ablation_layer.cpython-310.pyc ADDED
Binary file (4.99 kB). View file
 
pytorch_grad_cam/__pycache__/ablation_layer.cpython-39.pyc ADDED
Binary file (5.07 kB). View file
 
pytorch_grad_cam/__pycache__/activations_and_gradients.cpython-310.pyc ADDED
Binary file (2.08 kB). View file
 
pytorch_grad_cam/__pycache__/activations_and_gradients.cpython-39.pyc ADDED
Binary file (2.08 kB). View file
 
pytorch_grad_cam/__pycache__/base_cam.cpython-310.pyc ADDED
Binary file (6.18 kB). View file
 
pytorch_grad_cam/__pycache__/base_cam.cpython-39.pyc ADDED
Binary file (6.14 kB). View file
 
pytorch_grad_cam/__pycache__/diff_cam.cpython-39.pyc ADDED
Binary file (3.34 kB). View file
 
pytorch_grad_cam/__pycache__/eigen_cam.cpython-310.pyc ADDED
Binary file (954 Bytes). View file
 
pytorch_grad_cam/__pycache__/eigen_cam.cpython-39.pyc ADDED
Binary file (949 Bytes). View file
 
pytorch_grad_cam/__pycache__/eigen_grad_cam.cpython-310.pyc ADDED
Binary file (948 Bytes). View file
 
pytorch_grad_cam/__pycache__/eigen_grad_cam.cpython-39.pyc ADDED
Binary file (943 Bytes). View file
 
pytorch_grad_cam/__pycache__/finer_cam.cpython-310.pyc ADDED
Binary file (3.3 kB). View file
 
pytorch_grad_cam/__pycache__/fullgrad_cam.cpython-310.pyc ADDED
Binary file (3.21 kB). View file
 
pytorch_grad_cam/__pycache__/fullgrad_cam.cpython-39.pyc ADDED
Binary file (3.2 kB). View file
 
pytorch_grad_cam/__pycache__/grad_cam.cpython-310.pyc ADDED
Binary file (897 Bytes). View file
 
pytorch_grad_cam/__pycache__/grad_cam.cpython-39.pyc ADDED
Binary file (890 Bytes). View file
 
pytorch_grad_cam/__pycache__/grad_cam_plusplus.cpython-310.pyc ADDED
Binary file (1.15 kB). View file
 
pytorch_grad_cam/__pycache__/grad_cam_plusplus.cpython-39.pyc ADDED
Binary file (1.14 kB). View file
 
pytorch_grad_cam/__pycache__/guided_backprop.cpython-310.pyc ADDED
Binary file (3.44 kB). View file
 
pytorch_grad_cam/__pycache__/guided_backprop.cpython-39.pyc ADDED
Binary file (3.43 kB). View file
 
pytorch_grad_cam/__pycache__/layer_cam.cpython-310.pyc ADDED
Binary file (1.08 kB). View file