Jonathan Malott commited on
Commit
244fae2
1 Parent(s): 257a122
.cache/minDALL-E/1.3B/config.yaml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dataset:
2
+ tokenizer_type: CharBPE
3
+ context_length: 64
4
+ image_resolution: 256
5
+
6
+ stage1:
7
+ type: vqgan
8
+ embed_dim: 256
9
+ n_embed: 16384
10
+ hparams:
11
+ double_z: False
12
+ z_channels: 256
13
+ resolution: 256
14
+ in_channels: 3
15
+ out_ch: 3
16
+ ch: 128
17
+ ch_mult: [1, 1, 2, 2, 4]
18
+ num_res_blocks: 2
19
+ attn_resolutions: [16]
20
+ pdrop: 0.0
21
+
22
+ stage2:
23
+ type: transformer1d
24
+ vocab_size_txt: 16384
25
+ vocab_size_img: 16384
26
+ hparams:
27
+ embed_dim: 1536
28
+ n_layers: 42
29
+ n_heads: 24
30
+ n_dense_layers: 42
31
+ ctx_len_img: 256
32
+ ctx_len_txt: 64
33
+ embd_pdrop: 0.0
34
+ resid_pdrop: 0.0
35
+ attn_pdrop: 0.0
36
+ mlp_bias: True
37
+ attn_bias: True
38
+ gelu_use_approx: False
.cache/minDALL-E/1.3B/tokenizer/bpe-16k-merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
.cache/minDALL-E/1.3B/tokenizer/bpe-16k-vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
.gitattributes ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ *.ftz filter=lfs diff=lfs merge=lfs -text
6
+ *.gz filter=lfs diff=lfs merge=lfs -text
7
+ *.h5 filter=lfs diff=lfs merge=lfs -text
8
+ *.joblib filter=lfs diff=lfs merge=lfs -text
9
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
10
+ *.model filter=lfs diff=lfs merge=lfs -text
11
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
12
+ *.onnx filter=lfs diff=lfs merge=lfs -text
13
+ *.ot filter=lfs diff=lfs merge=lfs -text
14
+ *.parquet filter=lfs diff=lfs merge=lfs -text
15
+ *.pb filter=lfs diff=lfs merge=lfs -text
16
+ *.pt filter=lfs diff=lfs merge=lfs -text
17
+ *.pth filter=lfs diff=lfs merge=lfs -text
18
+ *.rar filter=lfs diff=lfs merge=lfs -text
19
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
20
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
21
+ *.tflite filter=lfs diff=lfs merge=lfs -text
22
+ *.tgz filter=lfs diff=lfs merge=lfs -text
23
+ *.wasm filter=lfs diff=lfs merge=lfs -text
24
+ *.xz filter=lfs diff=lfs merge=lfs -text
25
+ *.zip filter=lfs diff=lfs merge=lfs -text
26
+ *.zstandard filter=lfs diff=lfs merge=lfs -text
27
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.gitignore CHANGED
@@ -1,20 +1,17 @@
1
  .ipynb_checkpoints/
2
 
3
-
4
  __pycache__/
5
 
6
-
7
  _archives/
8
 
9
-
10
  _exampleImages/
11
 
12
-
13
  _trash/
14
 
 
15
 
16
- minDALL-E/
17
-
18
 
 
19
 
20
- temp/
 
1
  .ipynb_checkpoints/
2
 
 
3
  __pycache__/
4
 
 
5
  _archives/
6
 
 
7
  _exampleImages/
8
 
 
9
  _trash/
10
 
11
+ temp/
12
 
13
+ 1.3B.tar.gz
 
14
 
15
+ stage1_last.ckpt
16
 
17
+ stage2_last.ckpt
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Ai Architecture
3
+ emoji: 😻
4
+ colorFrom: gray
5
+ colorTo: blue
6
+ sdk: streamlit
7
+ sdk_version: 1.10.0
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,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+
5
+ import os, random, time
6
+
7
+ from utils import footer
8
+ from page import generate, reduce
9
+
10
+
11
+ if( hasattr(st.session_state, 'page') == False):
12
+ st.session_state.page = 0
13
+
14
+ if( hasattr(st.session_state, 'results') == False):
15
+ st.session_state.results = []
16
+
17
+ p1 = st.empty()
18
+ p2 = st.empty()
19
+ p3 = st.empty()
20
+
21
+
22
+ st.session_state.stop = False
23
+ st.session_state.progress = 0
24
+ st.session_state.regenerate = False
25
+
26
+ if(st.session_state.page == 0):
27
+ p2.empty()
28
+ p3.empty()
29
+ with p1.container():
30
+ generate.app()
31
+
32
+
33
+ if(st.session_state.page == 1):
34
+ p1.empty()
35
+ p3.empty()
36
+ with p2.container():
37
+ reduce.app()
38
+
39
+ if(st.session_state.page == 2):
40
+ p1.empty()
41
+ p2.empty()
42
+ with p3.container():
43
+ st.write("This 333")
44
+ startButton = st.button("S3")
45
+ if startButton:
46
+ st.session_state.page = 0
47
+
48
+ footer()
background.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from htbuilder import HtmlElement, div, ul, li, br, hr, a, p, img, styles, classes, fonts
2
+ from htbuilder.units import percent, px
3
+ from htbuilder.funcs import rgba, rgb
4
+ import streamlit as st
5
+ import os
6
+ import sys
7
+ import argparse
8
+ import clip
9
+ import numpy as np
10
+ from PIL import Image
11
+ from dalle.models import Dalle
12
+ from dalle.utils.utils import set_seed, clip_score
13
+ import cv2
14
+ import subprocess
15
+ import signal
16
+
17
+ def signal_handler(sig, frame):
18
+ print('You pressed Ctrl+C!')
19
+ sys.exit(0)
20
+
21
+
22
+ def generate(prompt,crazy):
23
+
24
+ print("-------------------")
25
+
26
+ signal.signal(signal.SIGINT, signal_handler)
27
+
28
+ device = 'cpu'
29
+ model = Dalle.from_pretrained('minDALL-E/1.3B') # This will automatically download the pretrained model.
30
+ model.to(device=device)
31
+ num_candidates = 3
32
+
33
+ images = []
34
+
35
+ set_seed(np.random.randint(0,10000))
36
+
37
+ # Sampling
38
+ images = model.sampling(prompt=prompt,
39
+ top_k=2048,
40
+ top_p=None,
41
+ softmax_temperature=crazy,
42
+ num_candidates=num_candidates,
43
+ device=device).cpu().numpy()
44
+ images = np.transpose(images, (0, 2, 3, 1))
45
+
46
+ # CLIP Re-ranking
47
+ model_clip, preprocess_clip = clip.load("ViT-B/32", device=device)
48
+ model_clip.to(device=device)
49
+ rank = clip_score(prompt=prompt,
50
+ images=images,
51
+ model_clip=model_clip,
52
+ preprocess_clip=preprocess_clip,
53
+ device=device)
54
+
55
+ # Save images
56
+ #return images[rank]
57
+ for image in images:
58
+ cv2.imwrite('temp/'+str(np.random.randint(0,10000))+'.jpeg', image)
59
+
60
+
61
+ generate("a pink house",0.75)
clip/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .clip import *
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,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
16
+ try:
17
+ from torchvision.transforms import InterpolationMode
18
+ BICUBIC = InterpolationMode.BICUBIC
19
+ except ImportError:
20
+ BICUBIC = Image.BICUBIC
21
+
22
+
23
+ if packaging.version.parse(torch.__version__) < packaging.version.parse("1.7.1"):
24
+ warnings.warn("PyTorch version 1.7.1 or higher is recommended")
25
+
26
+
27
+ __all__ = ["available_models", "load", "tokenize"]
28
+ _tokenizer = _Tokenizer()
29
+
30
+ _MODELS = {
31
+ "RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt",
32
+ "RN101": "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt",
33
+ "RN50x4": "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt",
34
+ "RN50x16": "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt",
35
+ "RN50x64": "https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt",
36
+ "ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt",
37
+ "ViT-B/16": "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt",
38
+ "ViT-L/14": "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt",
39
+ "ViT-L/14@336px": "https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt",
40
+ }
41
+
42
+
43
+ def _download(url: str, root: str = os.path.expanduser("~/.cache/clip")):
44
+ os.makedirs(root, exist_ok=True)
45
+ filename = os.path.basename(url)
46
+
47
+ expected_sha256 = url.split("/")[-2]
48
+ download_target = os.path.join(root, filename)
49
+
50
+ if os.path.exists(download_target) and not os.path.isfile(download_target):
51
+ raise RuntimeError(f"{download_target} exists and is not a regular file")
52
+
53
+ if os.path.isfile(download_target):
54
+ if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256:
55
+ return download_target
56
+ else:
57
+ warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
58
+
59
+ with urllib.request.urlopen(url) as source, open(download_target, "wb") as output:
60
+ with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True) as loop:
61
+ while True:
62
+ buffer = source.read(8192)
63
+ if not buffer:
64
+ break
65
+
66
+ output.write(buffer)
67
+ loop.update(len(buffer))
68
+
69
+ if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256:
70
+ raise RuntimeError(f"Model has been downloaded but the SHA256 checksum does not not match")
71
+
72
+ return download_target
73
+
74
+
75
+ def _convert_image_to_rgb(image):
76
+ return image.convert("RGB")
77
+
78
+
79
+ def _transform(n_px):
80
+ return Compose([
81
+ Resize(n_px, interpolation=BICUBIC),
82
+ CenterCrop(n_px),
83
+ _convert_image_to_rgb,
84
+ ToTensor(),
85
+ Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
86
+ ])
87
+
88
+
89
+ def available_models() -> List[str]:
90
+ """Returns the names of available CLIP models"""
91
+ return list(_MODELS.keys())
92
+
93
+
94
+ def load(name: str, device: Union[str, torch.device] = None, jit=False):
95
+ """Load a CLIP model
96
+
97
+ Parameters
98
+ ----------
99
+ name : str
100
+ A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict
101
+
102
+ device : Union[str, torch.device]
103
+ The device to put the loaded model
104
+
105
+ jit : bool
106
+ Whether to load the optimized JIT model or more hackable non-JIT model (default).
107
+
108
+ Returns
109
+ -------
110
+ model : torch.nn.Module
111
+ The CLIP model
112
+
113
+ preprocess : Callable[[PIL.Image], torch.Tensor]
114
+ A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
115
+ """
116
+ if device is None:
117
+ device = "cuda" if torch.cuda.is_available() else "cpu"
118
+ if name in _MODELS:
119
+ model_path = _download(_MODELS[name])
120
+ elif os.path.isfile(name):
121
+ model_path = name
122
+ else:
123
+ raise RuntimeError(f"Model {name} not found; available models = {available_models()}")
124
+
125
+ try:
126
+ # loading JIT archive
127
+ model = torch.jit.load(model_path, map_location=device if jit else "cpu").eval()
128
+ state_dict = None
129
+ except RuntimeError:
130
+ # loading saved state dict
131
+ if jit:
132
+ warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead")
133
+ jit = False
134
+ state_dict = torch.load(model_path, map_location="cpu")
135
+
136
+ if not jit:
137
+ model = build_model(state_dict or model.state_dict()).to(device)
138
+ if str(device) == "cpu":
139
+ model.float()
140
+ return model, _transform(model.visual.input_resolution)
141
+
142
+ # patch the device names
143
+ device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[])
144
+ device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1]
145
+
146
+ def patch_device(module):
147
+ try:
148
+ graphs = [module.graph] if hasattr(module, "graph") else []
149
+ except RuntimeError:
150
+ graphs = []
151
+
152
+ if hasattr(module, "forward1"):
153
+ graphs.append(module.forward1.graph)
154
+
155
+ for graph in graphs:
156
+ for node in graph.findAllNodes("prim::Constant"):
157
+ if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"):
158
+ node.copyAttributes(device_node)
159
+
160
+ model.apply(patch_device)
161
+ patch_device(model.encode_image)
162
+ patch_device(model.encode_text)
163
+
164
+ # patch dtype to float32 on CPU
165
+ if str(device) == "cpu":
166
+ float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[])
167
+ float_input = list(float_holder.graph.findNode("aten::to").inputs())[1]
168
+ float_node = float_input.node()
169
+
170
+ def patch_float(module):
171
+ try:
172
+ graphs = [module.graph] if hasattr(module, "graph") else []
173
+ except RuntimeError:
174
+ graphs = []
175
+
176
+ if hasattr(module, "forward1"):
177
+ graphs.append(module.forward1.graph)
178
+
179
+ for graph in graphs:
180
+ for node in graph.findAllNodes("aten::to"):
181
+ inputs = list(node.inputs())
182
+ for i in [1, 2]: # dtype can be the second or third argument to aten::to()
183
+ if inputs[i].node()["value"] == 5:
184
+ inputs[i].node().copyAttributes(float_node)
185
+
186
+ model.apply(patch_float)
187
+ patch_float(model.encode_image)
188
+ patch_float(model.encode_text)
189
+
190
+ model.float()
191
+
192
+ return model, _transform(model.input_resolution.item())
193
+
194
+
195
+ def tokenize(texts: Union[str, List[str]], context_length: int = 77, truncate: bool = False) -> torch.LongTensor:
196
+ """
197
+ Returns the tokenized representation of given input string(s)
198
+
199
+ Parameters
200
+ ----------
201
+ texts : Union[str, List[str]]
202
+ An input string or a list of input strings to tokenize
203
+
204
+ context_length : int
205
+ The context length to use; all CLIP models use 77 as the context length
206
+
207
+ truncate: bool
208
+ Whether to truncate the text in case its encoding is longer than the context length
209
+
210
+ Returns
211
+ -------
212
+ A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length]
213
+ """
214
+ if isinstance(texts, str):
215
+ texts = [texts]
216
+
217
+ sot_token = _tokenizer.encoder["<|startoftext|>"]
218
+ eot_token = _tokenizer.encoder["<|endoftext|>"]
219
+ all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts]
220
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
221
+
222
+ for i, tokens in enumerate(all_tokens):
223
+ if len(tokens) > context_length:
224
+ if truncate:
225
+ tokens = tokens[:context_length]
226
+ tokens[-1] = eot_token
227
+ else:
228
+ raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}")
229
+ result[i, :len(tokens)] = torch.tensor(tokens)
230
+
231
+ return result
clip/model.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
10
+ class Bottleneck(nn.Module):
11
+ expansion = 4
12
+
13
+ def __init__(self, inplanes, planes, stride=1):
14
+ super().__init__()
15
+
16
+ # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
17
+ self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
18
+ self.bn1 = nn.BatchNorm2d(planes)
19
+
20
+ self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
21
+ self.bn2 = nn.BatchNorm2d(planes)
22
+
23
+ self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
24
+
25
+ self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
26
+ self.bn3 = nn.BatchNorm2d(planes * self.expansion)
27
+
28
+ self.relu = nn.ReLU(inplace=True)
29
+ self.downsample = None
30
+ self.stride = stride
31
+
32
+ if stride > 1 or inplanes != planes * Bottleneck.expansion:
33
+ # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
34
+ self.downsample = nn.Sequential(OrderedDict([
35
+ ("-1", nn.AvgPool2d(stride)),
36
+ ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),
37
+ ("1", nn.BatchNorm2d(planes * self.expansion))
38
+ ]))
39
+
40
+ def forward(self, x: torch.Tensor):
41
+ identity = x
42
+
43
+ out = self.relu(self.bn1(self.conv1(x)))
44
+ out = self.relu(self.bn2(self.conv2(out)))
45
+ out = self.avgpool(out)
46
+ out = self.bn3(self.conv3(out))
47
+
48
+ if self.downsample is not None:
49
+ identity = self.downsample(x)
50
+
51
+ out += identity
52
+ out = self.relu(out)
53
+ return out
54
+
55
+
56
+ class AttentionPool2d(nn.Module):
57
+ def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
58
+ super().__init__()
59
+ self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)
60
+ self.k_proj = nn.Linear(embed_dim, embed_dim)
61
+ self.q_proj = nn.Linear(embed_dim, embed_dim)
62
+ self.v_proj = nn.Linear(embed_dim, embed_dim)
63
+ self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
64
+ self.num_heads = num_heads
65
+
66
+ def forward(self, x):
67
+ x = x.reshape(x.shape[0], x.shape[1], x.shape[2] * x.shape[3]).permute(2, 0, 1) # NCHW -> (HW)NC
68
+ x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
69
+ x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
70
+ x, _ = F.multi_head_attention_forward(
71
+ query=x, key=x, value=x,
72
+ embed_dim_to_check=x.shape[-1],
73
+ num_heads=self.num_heads,
74
+ q_proj_weight=self.q_proj.weight,
75
+ k_proj_weight=self.k_proj.weight,
76
+ v_proj_weight=self.v_proj.weight,
77
+ in_proj_weight=None,
78
+ in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
79
+ bias_k=None,
80
+ bias_v=None,
81
+ add_zero_attn=False,
82
+ dropout_p=0,
83
+ out_proj_weight=self.c_proj.weight,
84
+ out_proj_bias=self.c_proj.bias,
85
+ use_separate_proj_weight=True,
86
+ training=self.training,
87
+ need_weights=False
88
+ )
89
+
90
+ return x[0]
91
+
92
+
93
+ class ModifiedResNet(nn.Module):
94
+ """
95
+ A ResNet class that is similar to torchvision's but contains the following changes:
96
+ - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
97
+ - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
98
+ - The final pooling layer is a QKV attention instead of an average pool
99
+ """
100
+
101
+ def __init__(self, layers, output_dim, heads, input_resolution=224, width=64):
102
+ super().__init__()
103
+ self.output_dim = output_dim
104
+ self.input_resolution = input_resolution
105
+
106
+ # the 3-layer stem
107
+ self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
108
+ self.bn1 = nn.BatchNorm2d(width // 2)
109
+ self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
110
+ self.bn2 = nn.BatchNorm2d(width // 2)
111
+ self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
112
+ self.bn3 = nn.BatchNorm2d(width)
113
+ self.avgpool = nn.AvgPool2d(2)
114
+ self.relu = nn.ReLU(inplace=True)
115
+
116
+ # residual layers
117
+ self._inplanes = width # this is a *mutable* variable used during construction
118
+ self.layer1 = self._make_layer(width, layers[0])
119
+ self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
120
+ self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
121
+ self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
122
+
123
+ embed_dim = width * 32 # the ResNet feature dimension
124
+ self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
125
+
126
+ def _make_layer(self, planes, blocks, stride=1):
127
+ layers = [Bottleneck(self._inplanes, planes, stride)]
128
+
129
+ self._inplanes = planes * Bottleneck.expansion
130
+ for _ in range(1, blocks):
131
+ layers.append(Bottleneck(self._inplanes, planes))
132
+
133
+ return nn.Sequential(*layers)
134
+
135
+ def forward(self, x):
136
+ def stem(x):
137
+ for conv, bn in [(self.conv1, self.bn1), (self.conv2, self.bn2), (self.conv3, self.bn3)]:
138
+ x = self.relu(bn(conv(x)))
139
+ x = self.avgpool(x)
140
+ return x
141
+
142
+ x = x.type(self.conv1.weight.dtype)
143
+ x = stem(x)
144
+ x = self.layer1(x)
145
+ x = self.layer2(x)
146
+ x = self.layer3(x)
147
+ x = self.layer4(x)
148
+ x = self.attnpool(x)
149
+
150
+ return x
151
+
152
+
153
+ class LayerNorm(nn.LayerNorm):
154
+ """Subclass torch's LayerNorm to handle fp16."""
155
+
156
+ def forward(self, x: torch.Tensor):
157
+ orig_type = x.dtype
158
+ ret = super().forward(x.type(torch.float32))
159
+ return ret.type(orig_type)
160
+
161
+
162
+ class QuickGELU(nn.Module):
163
+ def forward(self, x: torch.Tensor):
164
+ return x * torch.sigmoid(1.702 * x)
165
+
166
+
167
+ class ResidualAttentionBlock(nn.Module):
168
+ def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
169
+ super().__init__()
170
+
171
+ self.attn = nn.MultiheadAttention(d_model, n_head)
172
+ self.ln_1 = LayerNorm(d_model)
173
+ self.mlp = nn.Sequential(OrderedDict([
174
+ ("c_fc", nn.Linear(d_model, d_model * 4)),
175
+ ("gelu", QuickGELU()),
176
+ ("c_proj", nn.Linear(d_model * 4, d_model))
177
+ ]))
178
+ self.ln_2 = LayerNorm(d_model)
179
+ self.attn_mask = attn_mask
180
+
181
+ def attention(self, x: torch.Tensor):
182
+ self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
183
+ return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
184
+
185
+ def forward(self, x: torch.Tensor):
186
+ x = x + self.attention(self.ln_1(x))
187
+ x = x + self.mlp(self.ln_2(x))
188
+ return x
189
+
190
+
191
+ class Transformer(nn.Module):
192
+ def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):
193
+ super().__init__()
194
+ self.width = width
195
+ self.layers = layers
196
+ self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])
197
+
198
+ def forward(self, x: torch.Tensor):
199
+ return self.resblocks(x)
200
+
201
+
202
+ class VisionTransformer(nn.Module):
203
+ def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int):
204
+ super().__init__()
205
+ self.input_resolution = input_resolution
206
+ self.output_dim = output_dim
207
+ self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
208
+
209
+ scale = width ** -0.5
210
+ self.class_embedding = nn.Parameter(scale * torch.randn(width))
211
+ self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
212
+ self.ln_pre = LayerNorm(width)
213
+
214
+ self.transformer = Transformer(width, layers, heads)
215
+
216
+ self.ln_post = LayerNorm(width)
217
+ self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
218
+
219
+ def forward(self, x: torch.Tensor):
220
+ x = self.conv1(x) # shape = [*, width, grid, grid]
221
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
222
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
223
+ 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]
224
+ x = x + self.positional_embedding.to(x.dtype)
225
+ x = self.ln_pre(x)
226
+
227
+ x = x.permute(1, 0, 2) # NLD -> LND
228
+ x = self.transformer(x)
229
+ x = x.permute(1, 0, 2) # LND -> NLD
230
+
231
+ x = self.ln_post(x[:, 0, :])
232
+
233
+ if self.proj is not None:
234
+ x = x @ self.proj
235
+
236
+ return x
237
+
238
+
239
+ class CLIP(nn.Module):
240
+ def __init__(self,
241
+ embed_dim: int,
242
+ # vision
243
+ image_resolution: int,
244
+ vision_layers: Union[Tuple[int, int, int, int], int],
245
+ vision_width: int,
246
+ vision_patch_size: int,
247
+ # text
248
+ context_length: int,
249
+ vocab_size: int,
250
+ transformer_width: int,
251
+ transformer_heads: int,
252
+ transformer_layers: int
253
+ ):
254
+ super().__init__()
255
+
256
+ self.context_length = context_length
257
+
258
+ if isinstance(vision_layers, (tuple, list)):
259
+ vision_heads = vision_width * 32 // 64
260
+ self.visual = ModifiedResNet(
261
+ layers=vision_layers,
262
+ output_dim=embed_dim,
263
+ heads=vision_heads,
264
+ input_resolution=image_resolution,
265
+ width=vision_width
266
+ )
267
+ else:
268
+ vision_heads = vision_width // 64
269
+ self.visual = VisionTransformer(
270
+ input_resolution=image_resolution,
271
+ patch_size=vision_patch_size,
272
+ width=vision_width,
273
+ layers=vision_layers,
274
+ heads=vision_heads,
275
+ output_dim=embed_dim
276
+ )
277
+
278
+ self.transformer = Transformer(
279
+ width=transformer_width,
280
+ layers=transformer_layers,
281
+ heads=transformer_heads,
282
+ attn_mask=self.build_attention_mask()
283
+ )
284
+
285
+ self.vocab_size = vocab_size
286
+ self.token_embedding = nn.Embedding(vocab_size, transformer_width)
287
+ self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))
288
+ self.ln_final = LayerNorm(transformer_width)
289
+
290
+ self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
291
+ self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
292
+
293
+ self.initialize_parameters()
294
+
295
+ def initialize_parameters(self):
296
+ nn.init.normal_(self.token_embedding.weight, std=0.02)
297
+ nn.init.normal_(self.positional_embedding, std=0.01)
298
+
299
+ if isinstance(self.visual, ModifiedResNet):
300
+ if self.visual.attnpool is not None:
301
+ std = self.visual.attnpool.c_proj.in_features ** -0.5
302
+ nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std)
303
+ nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std)
304
+ nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std)
305
+ nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std)
306
+
307
+ for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]:
308
+ for name, param in resnet_block.named_parameters():
309
+ if name.endswith("bn3.weight"):
310
+ nn.init.zeros_(param)
311
+
312
+ proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
313
+ attn_std = self.transformer.width ** -0.5
314
+ fc_std = (2 * self.transformer.width) ** -0.5
315
+ for block in self.transformer.resblocks:
316
+ nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
317
+ nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
318
+ nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
319
+ nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
320
+
321
+ if self.text_projection is not None:
322
+ nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
323
+
324
+ def build_attention_mask(self):
325
+ # lazily create causal attention mask, with full attention between the vision tokens
326
+ # pytorch uses additive attention mask; fill with -inf
327
+ mask = torch.empty(self.context_length, self.context_length)
328
+ mask.fill_(float("-inf"))
329
+ mask.triu_(1) # zero out the lower diagonal
330
+ return mask
331
+
332
+ @property
333
+ def dtype(self):
334
+ return self.visual.conv1.weight.dtype
335
+
336
+ def encode_image(self, image):
337
+ return self.visual(image.type(self.dtype))
338
+
339
+ def encode_text(self, text):
340
+ x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
341
+
342
+ x = x + self.positional_embedding.type(self.dtype)
343
+ x = x.permute(1, 0, 2) # NLD -> LND
344
+ x = self.transformer(x)
345
+ x = x.permute(1, 0, 2) # LND -> NLD
346
+ x = self.ln_final(x).type(self.dtype)
347
+
348
+ # x.shape = [batch_size, n_ctx, transformer.width]
349
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
350
+ x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
351
+
352
+ return x
353
+
354
+ def forward(self, image, text):
355
+ image_features = self.encode_image(image)
356
+ text_features = self.encode_text(text)
357
+
358
+ # normalized features
359
+ image_features = image_features / image_features.norm(dim=-1, keepdim=True)
360
+ text_features = text_features / text_features.norm(dim=-1, keepdim=True)
361
+
362
+ # cosine similarity as logits
363
+ logit_scale = self.logit_scale.exp()
364
+ logits_per_image = logit_scale * image_features @ text_features.t()
365
+ logits_per_text = logit_scale * text_features @ image_features.t()
366
+
367
+ # shape = [global_batch_size, global_batch_size]
368
+ return logits_per_image, logits_per_text
369
+
370
+
371
+ def convert_weights(model: nn.Module):
372
+ """Convert applicable model parameters to fp16"""
373
+
374
+ def _convert_weights_to_fp16(l):
375
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
376
+ l.weight.data = l.weight.data.half()
377
+ if l.bias is not None:
378
+ l.bias.data = l.bias.data.half()
379
+
380
+ if isinstance(l, nn.MultiheadAttention):
381
+ for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
382
+ tensor = getattr(l, attr)
383
+ if tensor is not None:
384
+ tensor.data = tensor.data.half()
385
+
386
+ for name in ["text_projection", "proj"]:
387
+ if hasattr(l, name):
388
+ attr = getattr(l, name)
389
+ if attr is not None:
390
+ attr.data = attr.data.half()
391
+
392
+ model.apply(_convert_weights_to_fp16)
393
+
394
+
395
+ def build_model(state_dict: dict):
396
+ vit = "visual.proj" in state_dict
397
+
398
+ if vit:
399
+ vision_width = state_dict["visual.conv1.weight"].shape[0]
400
+ vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
401
+ vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
402
+ grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
403
+ image_resolution = vision_patch_size * grid_size
404
+ else:
405
+ 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]]
406
+ vision_layers = tuple(counts)
407
+ vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
408
+ output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
409
+ vision_patch_size = None
410
+ assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
411
+ image_resolution = output_width * 32
412
+
413
+ embed_dim = state_dict["text_projection"].shape[1]
414
+ context_length = state_dict["positional_embedding"].shape[0]
415
+ vocab_size = state_dict["token_embedding.weight"].shape[0]
416
+ transformer_width = state_dict["ln_final.weight"].shape[0]
417
+ transformer_heads = transformer_width // 64
418
+ transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks")))
419
+
420
+ model = CLIP(
421
+ embed_dim,
422
+ image_resolution, vision_layers, vision_width, vision_patch_size,
423
+ context_length, vocab_size, transformer_width, transformer_heads, transformer_layers
424
+ )
425
+
426
+ for key in ["input_resolution", "context_length", "vocab_size"]:
427
+ if key in state_dict:
428
+ del state_dict[key]
429
+
430
+ convert_weights(model)
431
+ model.load_state_dict(state_dict)
432
+ 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
dalle/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (175 Bytes). View file
 
dalle/models/__init__.py CHANGED
@@ -43,24 +43,20 @@ class Dalle(nn.Module):
43
  @classmethod
44
  def from_pretrained(cls,
45
  path: str) -> nn.Module:
46
- #path = _MODELS[path] if path in _MODELS else path
47
- #path = utils.realpath_url_or_path(path, root=os.path.expanduser(".cache/minDALL-E"))
48
- path = ''
49
 
50
  config_base = get_base_config()
51
- config_new = OmegaConf.load(os.path.join(path, '.cache/minDALL-E/1.3B/config.yaml'))
52
  config_update = OmegaConf.merge(config_base, config_new)
53
 
54
  model = cls(config_update)
55
- model.tokenizer = build_tokenizer('.cache/minDALL-E/1.3B/tokenizer',
56
  context_length=model.config_dataset.context_length,
57
  lowercase=True,
58
  dropout=None)
59
- model.stage1.from_ckpt('.cache/minDALL-E/1.3B/stage1_last.ckpt')
60
- model.stage2.from_ckpt('.cache/minDALL-E/1.3B/stage2_last.ckpt')
61
- #model.stage1.from_ckpt('https://utexas.box.com/shared/static/rpt9miyj2kikogyekpqnkd6y115xp51i.ckpt')
62
- #model.stage2.from_ckpt('https://utexas.box.com/shared/static/54jc9fw0bious5nx6wvayeqaskcrdgv4.ckpt')
63
-
64
  return model
65
 
66
  @torch.no_grad()
 
43
  @classmethod
44
  def from_pretrained(cls,
45
  path: str) -> nn.Module:
46
+ path = _MODELS[path] if path in _MODELS else path
47
+ path = utils.realpath_url_or_path(path, root=os.path.expanduser(".cache/minDALL-E"))
 
48
 
49
  config_base = get_base_config()
50
+ config_new = OmegaConf.load(os.path.join(path, 'config.yaml'))
51
  config_update = OmegaConf.merge(config_base, config_new)
52
 
53
  model = cls(config_update)
54
+ model.tokenizer = build_tokenizer(os.path.join(path, 'tokenizer'),
55
  context_length=model.config_dataset.context_length,
56
  lowercase=True,
57
  dropout=None)
58
+ model.stage1.from_ckpt(os.path.join(path, 'stage1_last.ckpt'))
59
+ model.stage2.from_ckpt(os.path.join(path, 'stage2_last.ckpt'))
 
 
 
60
  return model
61
 
62
  @torch.no_grad()
dalle/models/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (6.79 kB). View file
 
dalle/models/__pycache__/tokenizer.cpython-39.pyc ADDED
Binary file (885 Bytes). View file
 
dalle/models/stage1/__pycache__/layers.cpython-39.pyc ADDED
Binary file (7.84 kB). View file
 
dalle/models/stage1/__pycache__/vqgan.cpython-39.pyc ADDED
Binary file (4.06 kB). View file
 
dalle/models/stage1/vqgan.py CHANGED
@@ -88,12 +88,6 @@ class VQGAN(nn.Module):
88
  return codes
89
 
90
  def from_ckpt(self, path: str, strict: bool = True) -> None:
91
- #ckpt = torch.load(path, map_location='cpu')['state_dict']
92
- #self.load_state_dict(ckpt, strict=strict)
93
- #print(f'{path} successfully restored..')
94
-
95
  ckpt = torch.load(path, map_location='cpu')['state_dict']
96
- #ckpt = torch.utils.model_zoo.load_url('https://utexas.box.com/shared/static/rpt9miyj2kikogyekpqnkd6y115xp51i.ckpt', map_location='cpu')['state_dict']
97
-
98
- self.load_state_dict(ckpt, strict=True)
99
- print(f'{path} succesfully restored..')
 
88
  return codes
89
 
90
  def from_ckpt(self, path: str, strict: bool = True) -> None:
 
 
 
 
91
  ckpt = torch.load(path, map_location='cpu')['state_dict']
92
+ self.load_state_dict(ckpt, strict=strict)
93
+ print(f'{path} successfully restored..')
 
 
dalle/models/stage2/__pycache__/layers.cpython-39.pyc ADDED
Binary file (3.77 kB). View file
 
dalle/models/stage2/__pycache__/transformer.cpython-39.pyc ADDED
Binary file (7.16 kB). View file
 
dalle/models/stage2/transformer.py CHANGED
@@ -13,7 +13,7 @@ from typing import Optional, Tuple, List
13
  from torch.cuda.amp import autocast
14
  from omegaconf import OmegaConf
15
  from .layers import Block
16
- import io
17
 
18
  class Transformer1d(nn.Module):
19
 
@@ -144,7 +144,6 @@ class Transformer1d(nn.Module):
144
 
145
  def from_ckpt(self, path: str) -> None:
146
  ckpt = torch.load(path, map_location='cpu')['state_dict']
147
- #ckpt = torch.utils.model_zoo.load_url('https://utexas.box.com/shared/static/54jc9fw0bious5nx6wvayeqaskcrdgv4.ckpt', map_location='cpu')['state_dict']
148
  self.load_state_dict(ckpt, strict=True)
149
  print(f'{path} succesfully restored..')
150
 
 
13
  from torch.cuda.amp import autocast
14
  from omegaconf import OmegaConf
15
  from .layers import Block
16
+
17
 
18
  class Transformer1d(nn.Module):
19
 
 
144
 
145
  def from_ckpt(self, path: str) -> None:
146
  ckpt = torch.load(path, map_location='cpu')['state_dict']
 
147
  self.load_state_dict(ckpt, strict=True)
148
  print(f'{path} succesfully restored..')
149
 
dalle/utils/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (241 Bytes). View file
 
dalle/utils/__pycache__/config.cpython-39.pyc ADDED
Binary file (4.97 kB). View file
 
dalle/utils/__pycache__/sampling.cpython-39.pyc ADDED
Binary file (3.72 kB). View file
 
dalle/utils/__pycache__/utils.cpython-39.pyc ADDED
Binary file (2.98 kB). View file
 
dalle/utils/sampling.py CHANGED
@@ -68,8 +68,6 @@ def sampling(model: torch.nn.Module,
68
  pbar = tqdm(range(max_seq_len), total=max_seq_len) if is_tqdm else range(max_seq_len)
69
  pos_enc_tokens = get_positional_encoding(tokens, mode='1d')
70
 
71
- #my_bar = st.progress(0)
72
-
73
  for cnt, h in enumerate(pbar):
74
  if code is None:
75
  code_ = None
@@ -95,6 +93,8 @@ def sampling(model: torch.nn.Module,
95
  else:
96
  past.append(present)
97
 
 
 
98
  logits = cutoff_topk_logits(logits, top_k)
99
  probs = F.softmax(logits, dim=-1)
100
  probs = cutoff_topp_probs(probs, top_p)
@@ -102,14 +102,6 @@ def sampling(model: torch.nn.Module,
102
  idx = torch.multinomial(probs, num_samples=1).clone().detach()
103
  code = idx if code is None else torch.cat([code, idx], axis=1)
104
 
105
- #print(cnt/max_seq_len)
106
- if(st.session_state.page != 0):
107
- break
108
-
109
- st.session_state.bar.progress(cnt/max_seq_len)
110
-
111
- #my_bar.progress(cnt/max_seq_len)
112
-
113
  del past
114
  return code
115
 
 
68
  pbar = tqdm(range(max_seq_len), total=max_seq_len) if is_tqdm else range(max_seq_len)
69
  pos_enc_tokens = get_positional_encoding(tokens, mode='1d')
70
 
 
 
71
  for cnt, h in enumerate(pbar):
72
  if code is None:
73
  code_ = None
 
93
  else:
94
  past.append(present)
95
 
96
+ st.session_state.bar = cnt/max_seq_len
97
+
98
  logits = cutoff_topk_logits(logits, top_k)
99
  probs = F.softmax(logits, dim=-1)
100
  probs = cutoff_topp_probs(probs, top_p)
 
102
  idx = torch.multinomial(probs, num_samples=1).clone().detach()
103
  code = idx if code is None else torch.cat([code, idx], axis=1)
104
 
 
 
 
 
 
 
 
 
105
  del past
106
  return code
107
 
minDALL-E ADDED
@@ -0,0 +1 @@
 
 
1
+ Subproject commit e5480076b9634e9dc097e1892157ed2cf15a2f86
page/__pycache__/generate.cpython-39.pyc ADDED
Binary file (2.34 kB). View file
 
page/__pycache__/reduce.cpython-39.pyc ADDED
Binary file (1.63 kB). View file
 
test ADDED
@@ -0,0 +1 @@
 
 
1
+ Subproject commit bfb917d14f50035f23f8d57c751e5f0c6e7f7277
utils.py CHANGED
@@ -84,7 +84,7 @@ def generate(prompt,crazy,k):
84
 
85
  device = 'cpu'
86
  print("-2-")
87
- model = Dalle.from_pretrained('.cache/minDALL-E/1.3B') # This will automatically download the pretrained model.
88
  print("-3-")
89
  model.to(device=device)
90
  num_candidates = 1
 
84
 
85
  device = 'cpu'
86
  print("-2-")
87
+ model = Dalle.from_pretrained('minDALL-E/1.3B') # This will automatically download the pretrained model.
88
  print("-3-")
89
  model.to(device=device)
90
  num_candidates = 1