yuxinjiang11 commited on
Commit
8d34a07
·
verified ·
1 Parent(s): 25ba35e

Upload 5 files

Browse files
model/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .longclip import *
model/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
model/longclip.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from torch import nn
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_longclip 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__ = ["load", "tokenize"]
28
+ _tokenizer = _Tokenizer()
29
+
30
+
31
+ def _convert_image_to_rgb(image):
32
+ return image.convert("RGB")
33
+
34
+
35
+ def _transform(n_px):
36
+ return Compose([
37
+ Resize(n_px, interpolation=BICUBIC),
38
+ CenterCrop(n_px),
39
+ _convert_image_to_rgb,
40
+ ToTensor(),
41
+ Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
42
+ ])
43
+
44
+
45
+
46
+ def load(name: str, device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", download_root: str = None):
47
+ """Load a long CLIP model
48
+
49
+ Parameters
50
+ ----------
51
+ name : str
52
+ A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict
53
+
54
+ device : Union[str, torch.device]
55
+ The device to put the loaded model
56
+
57
+ Returns
58
+ -------
59
+ model : torch.nn.Module
60
+ The CLIP model
61
+
62
+ preprocess : Callable[[PIL.Image], torch.Tensor]
63
+ A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
64
+ """
65
+
66
+ model_path = name
67
+
68
+ state_dict = torch.load(model_path, map_location="cpu")
69
+
70
+ model = build_model(state_dict or model.state_dict(), load_from_clip = False).to(device)
71
+
72
+ if str(device) == "cpu":
73
+ model.float()
74
+
75
+ return model, _transform(model.visual.input_resolution)
76
+
77
+
78
+
79
+ def _node_get(node: torch._C.Node, key: str):
80
+ """Gets attributes of a node which is polymorphic over return type.
81
+
82
+ From https://github.com/pytorch/pytorch/pull/82628
83
+ """
84
+ sel = node.kindOf(key)
85
+ return getattr(node, sel)(key)
86
+
87
+ def patch_device(module):
88
+ try:
89
+ graphs = [module.graph] if hasattr(module, "graph") else []
90
+ except RuntimeError:
91
+ graphs = []
92
+
93
+ if hasattr(module, "forward1"):
94
+ graphs.append(module.forward1.graph)
95
+
96
+ for graph in graphs:
97
+ for node in graph.findAllNodes("prim::Constant"):
98
+ if "value" in node.attributeNames() and str(_node_get(node, "value")).startswith("cuda"):
99
+ node.copyAttributes(device_node)
100
+
101
+ model.apply(patch_device)
102
+ patch_device(model.encode_image)
103
+ patch_device(model.encode_text)
104
+
105
+ # patch dtype to float32 on CPU
106
+ if str(device) == "cpu":
107
+ float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[])
108
+ float_input = list(float_holder.graph.findNode("aten::to").inputs())[1]
109
+ float_node = float_input.node()
110
+
111
+ def patch_float(module):
112
+ try:
113
+ graphs = [module.graph] if hasattr(module, "graph") else []
114
+ except RuntimeError:
115
+ graphs = []
116
+
117
+ if hasattr(module, "forward1"):
118
+ graphs.append(module.forward1.graph)
119
+
120
+ for graph in graphs:
121
+ for node in graph.findAllNodes("aten::to"):
122
+ inputs = list(node.inputs())
123
+ for i in [1, 2]: # dtype can be the second or third argument to aten::to()
124
+ if _node_get(inputs[i].node(), "value") == 5:
125
+ inputs[i].node().copyAttributes(float_node)
126
+
127
+ model.apply(patch_float)
128
+ patch_float(model.encode_image)
129
+ patch_float(model.encode_text)
130
+
131
+ model.float()
132
+
133
+ return model, _transform(model.input_resolution.item())
134
+
135
+
136
+ def load_from_clip(name: str, device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", jit: bool = False, download_root: str = None):
137
+ """Load from CLIP model for fine-tuning
138
+
139
+ Parameters
140
+ ----------
141
+ name : str
142
+ A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict
143
+
144
+ device : Union[str, torch.device]
145
+ The device to put the loaded model
146
+
147
+ jit : bool
148
+ Whether to load the optimized JIT model or more hackable non-JIT model (default).
149
+
150
+ download_root: str
151
+ path to download the model files; by default, it uses "~/.cache/clip"
152
+
153
+ Returns
154
+ -------
155
+ model : torch.nn.Module
156
+ The CLIP model
157
+
158
+ preprocess : Callable[[PIL.Image], torch.Tensor]
159
+ A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
160
+ """
161
+
162
+ _MODELS = {
163
+ "RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt",
164
+ "RN101": "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt",
165
+ "RN50x4": "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt",
166
+ "RN50x16": "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt",
167
+ "RN50x64": "https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt",
168
+ "ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt",
169
+ "ViT-B/16": "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt",
170
+ "ViT-L/14": "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt",
171
+ "ViT-L/14@336px": "https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt",
172
+ }
173
+
174
+ def available_models() -> List[str]:
175
+ """Returns the names of available CLIP models"""
176
+ return list(_MODELS.keys())
177
+
178
+ def _download(url: str, root: str):
179
+ os.makedirs(root, exist_ok=True)
180
+ filename = os.path.basename(url)
181
+
182
+ expected_sha256 = url.split("/")[-2]
183
+ download_target = os.path.join(root, filename)
184
+
185
+ if os.path.exists(download_target) and not os.path.isfile(download_target):
186
+ raise RuntimeError(f"{download_target} exists and is not a regular file")
187
+
188
+ if os.path.isfile(download_target):
189
+ if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256:
190
+ return download_target
191
+ else:
192
+ warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
193
+
194
+ with urllib.request.urlopen(url) as source, open(download_target, "wb") as output:
195
+ with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True, unit_divisor=1024) as loop:
196
+ while True:
197
+ buffer = source.read(8192)
198
+ if not buffer:
199
+ break
200
+
201
+ output.write(buffer)
202
+ loop.update(len(buffer))
203
+
204
+ if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256:
205
+ raise RuntimeError("Model has been downloaded but the SHA256 checksum does not not match")
206
+
207
+ return download_target
208
+
209
+ if name in _MODELS:
210
+ model_path = _download(_MODELS[name], download_root or os.path.expanduser("~/.cache/clip"))
211
+ elif os.path.isfile(name):
212
+ model_path = name
213
+ else:
214
+ raise RuntimeError(f"Model {name} not found; available models = {available_models()}")
215
+
216
+ with open(model_path, 'rb') as opened_file:
217
+ try:
218
+ # loading JIT archive
219
+ model = torch.jit.load(opened_file, map_location=device if jit else "cpu").eval()
220
+ state_dict = None
221
+ except RuntimeError:
222
+ # loading saved state dict
223
+ if jit:
224
+ warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead")
225
+ jit = False
226
+ state_dict = torch.load(opened_file, map_location="cpu")
227
+
228
+ model = build_model(state_dict or model.state_dict(), load_from_clip = True).to(device)
229
+
230
+ positional_embedding_pre = model.positional_embedding.type(model.dtype)
231
+
232
+ length, dim = positional_embedding_pre.shape
233
+ keep_len = 20
234
+ posisitonal_embedding_new = torch.zeros([4*length-3*keep_len, dim], dtype=model.dtype)
235
+ for i in range(keep_len):
236
+ posisitonal_embedding_new[i] = positional_embedding_pre[i]
237
+ for i in range(length-1-keep_len):
238
+ posisitonal_embedding_new[4*i + keep_len] = positional_embedding_pre[i + keep_len]
239
+ posisitonal_embedding_new[4*i + 1 + keep_len] = 3*positional_embedding_pre[i + keep_len]/4 + 1*positional_embedding_pre[i+1+keep_len]/4
240
+ posisitonal_embedding_new[4*i + 2+keep_len] = 2*positional_embedding_pre[i+keep_len]/4 + 2*positional_embedding_pre[i+1+keep_len]/4
241
+ posisitonal_embedding_new[4*i + 3+keep_len] = 1*positional_embedding_pre[i+keep_len]/4 + 3*positional_embedding_pre[i+1+keep_len]/4
242
+
243
+ posisitonal_embedding_new[4*length -3*keep_len - 4] = positional_embedding_pre[length-1] + 0*(positional_embedding_pre[length-1] - positional_embedding_pre[length-2])/4
244
+ posisitonal_embedding_new[4*length -3*keep_len - 3] = positional_embedding_pre[length-1] + 1*(positional_embedding_pre[length-1] - positional_embedding_pre[length-2])/4
245
+ posisitonal_embedding_new[4*length -3*keep_len - 2] = positional_embedding_pre[length-1] + 2*(positional_embedding_pre[length-1] - positional_embedding_pre[length-2])/4
246
+ posisitonal_embedding_new[4*length -3*keep_len - 1] = positional_embedding_pre[length-1] + 3*(positional_embedding_pre[length-1] - positional_embedding_pre[length-2])/4
247
+
248
+ positional_embedding_res = posisitonal_embedding_new.clone()
249
+
250
+ model.positional_embedding = nn.Parameter(posisitonal_embedding_new, requires_grad=False)
251
+ model.positional_embedding_res = nn.Parameter(positional_embedding_res, requires_grad=True)
252
+
253
+ if str(device) == "cpu":
254
+ model.float()
255
+ return model, _transform(model.visual.input_resolution)
256
+
257
+ def _node_get(node: torch._C.Node, key: str):
258
+ """Gets attributes of a node which is polymorphic over return type.
259
+
260
+ From https://github.com/pytorch/pytorch/pull/82628
261
+ """
262
+ sel = node.kindOf(key)
263
+ return getattr(node, sel)(key)
264
+
265
+ def patch_device(module):
266
+ try:
267
+ graphs = [module.graph] if hasattr(module, "graph") else []
268
+ except RuntimeError:
269
+ graphs = []
270
+
271
+ if hasattr(module, "forward1"):
272
+ graphs.append(module.forward1.graph)
273
+
274
+ for graph in graphs:
275
+ for node in graph.findAllNodes("prim::Constant"):
276
+ if "value" in node.attributeNames() and str(_node_get(node, "value")).startswith("cuda"):
277
+ node.copyAttributes(device_node)
278
+
279
+ model.apply(patch_device)
280
+ patch_device(model.encode_image)
281
+ patch_device(model.encode_text)
282
+
283
+ # patch dtype to float32 on CPU
284
+ if str(device) == "cpu":
285
+ float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[])
286
+ float_input = list(float_holder.graph.findNode("aten::to").inputs())[1]
287
+ float_node = float_input.node()
288
+
289
+ def patch_float(module):
290
+ try:
291
+ graphs = [module.graph] if hasattr(module, "graph") else []
292
+ except RuntimeError:
293
+ graphs = []
294
+
295
+ if hasattr(module, "forward1"):
296
+ graphs.append(module.forward1.graph)
297
+
298
+ for graph in graphs:
299
+ for node in graph.findAllNodes("aten::to"):
300
+ inputs = list(node.inputs())
301
+ for i in [1, 2]: # dtype can be the second or third argument to aten::to()
302
+ if _node_get(inputs[i].node(), "value") == 5:
303
+ inputs[i].node().copyAttributes(float_node)
304
+
305
+ model.apply(patch_float)
306
+ patch_float(model.encode_image)
307
+ patch_float(model.encode_text)
308
+
309
+ model.float()
310
+
311
+ return model, _transform(model.input_resolution.item())
312
+
313
+ def tokenize(texts: Union[str, List[str]], context_length: int = 77*4-60, truncate: bool = False) -> Union[torch.IntTensor, torch.LongTensor]:
314
+ """
315
+ Returns the tokenized representation of given input string(s)
316
+
317
+ Parameters
318
+ ----------
319
+ texts : Union[str, List[str]]
320
+ An input string or a list of input strings to tokenize
321
+
322
+ context_length : int
323
+ The context length to use; all CLIP models use 77 as the context length
324
+
325
+ truncate: bool
326
+ Whether to truncate the text in case its encoding is longer than the context length
327
+
328
+ Returns
329
+ -------
330
+ A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length].
331
+ We return LongTensor when torch version is <1.8.0, since older index_select requires indices to be long.
332
+ """
333
+ if isinstance(texts, str):
334
+ texts = [texts]
335
+
336
+ sot_token = _tokenizer.encoder["<|startoftext|>"]
337
+ eot_token = _tokenizer.encoder["<|endoftext|>"]
338
+ all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts]
339
+ if packaging.version.parse(torch.__version__) < packaging.version.parse("1.8.0"):
340
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
341
+ else:
342
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.int)
343
+
344
+ for i, tokens in enumerate(all_tokens):
345
+ if len(tokens) > context_length:
346
+ if truncate:
347
+ tokens = tokens[:context_length]
348
+ tokens[-1] = eot_token
349
+ else:
350
+ raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}")
351
+ result[i, :len(tokens)] = torch.tensor(tokens)
352
+
353
+ return result
model/model_longclip.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from typing import Tuple, Union, List
3
+ import numpy as np
4
+ import torch
5
+ import torch.nn.functional as F
6
+ from torch import nn
7
+
8
+
9
+ class Bottleneck(nn.Module):
10
+ expansion = 4
11
+
12
+ def __init__(self, inplanes, planes, stride=1):
13
+ super().__init__()
14
+ self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
15
+ self.bn1 = nn.BatchNorm2d(planes)
16
+ self.relu1 = nn.ReLU(inplace=True)
17
+
18
+ self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
19
+ self.bn2 = nn.BatchNorm2d(planes)
20
+ self.relu2 = nn.ReLU(inplace=True)
21
+
22
+ self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
23
+ self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
24
+ self.bn3 = nn.BatchNorm2d(planes * self.expansion)
25
+ self.relu3 = nn.ReLU(inplace=True)
26
+
27
+ self.downsample = None
28
+ self.stride = stride
29
+
30
+ if stride > 1 or inplanes != planes * Bottleneck.expansion:
31
+ self.downsample = nn.Sequential(OrderedDict([
32
+ ("-1", nn.AvgPool2d(stride)),
33
+ ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),
34
+ ("1", nn.BatchNorm2d(planes * self.expansion))
35
+ ]))
36
+
37
+ def forward(self, x: torch.Tensor):
38
+ identity = x
39
+ out = self.relu1(self.bn1(self.conv1(x)))
40
+ out = self.relu2(self.bn2(self.conv2(out)))
41
+ out = self.avgpool(out)
42
+ out = self.bn3(self.conv3(out))
43
+
44
+ if self.downsample is not None:
45
+ identity = self.downsample(x)
46
+
47
+ out += identity
48
+ out = self.relu3(out)
49
+ return out
50
+
51
+
52
+ class AttentionPool2d(nn.Module):
53
+ def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
54
+ super().__init__()
55
+ self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)
56
+ self.k_proj = nn.Linear(embed_dim, embed_dim)
57
+ self.q_proj = nn.Linear(embed_dim, embed_dim)
58
+ self.v_proj = nn.Linear(embed_dim, embed_dim)
59
+ self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
60
+ self.num_heads = num_heads
61
+
62
+ def forward(self, x):
63
+ x = x.flatten(start_dim=2).permute(2, 0, 1) # NCHW -> (HW)NC
64
+ x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
65
+ x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
66
+ x, _ = F.multi_head_attention_forward(
67
+ query=x[:1], key=x, value=x,
68
+ embed_dim_to_check=x.shape[-1],
69
+ num_heads=self.num_heads,
70
+ q_proj_weight=self.q_proj.weight,
71
+ k_proj_weight=self.k_proj.weight,
72
+ v_proj_weight=self.v_proj.weight,
73
+ in_proj_weight=None,
74
+ in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
75
+ bias_k=None,
76
+ bias_v=None,
77
+ add_zero_attn=False,
78
+ dropout_p=0,
79
+ out_proj_weight=self.c_proj.weight,
80
+ out_proj_bias=self.c_proj.bias,
81
+ use_separate_proj_weight=True,
82
+ training=self.training,
83
+ need_weights=False
84
+ )
85
+ return x.squeeze(0)
86
+
87
+
88
+ class ModifiedResNet(nn.Module):
89
+ def __init__(self, layers, output_dim, heads, input_resolution=224, width=64):
90
+ super().__init__()
91
+ self.output_dim = output_dim
92
+ self.input_resolution = input_resolution
93
+ self.intermediate_features = []
94
+
95
+ # 3-layer stem
96
+ self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
97
+ self.bn1 = nn.BatchNorm2d(width // 2)
98
+ self.relu1 = nn.ReLU(inplace=True)
99
+ self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
100
+ self.bn2 = nn.BatchNorm2d(width // 2)
101
+ self.relu2 = nn.ReLU(inplace=True)
102
+ self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
103
+ self.bn3 = nn.BatchNorm2d(width)
104
+ self.relu3 = nn.ReLU(inplace=True)
105
+ self.avgpool = nn.AvgPool2d(2)
106
+
107
+ # Residual layers
108
+ self._inplanes = width
109
+ self.layer1 = self._make_layer(width, layers[0])
110
+ self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
111
+ self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
112
+ self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
113
+
114
+ embed_dim = width * 32
115
+ self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
116
+
117
+ def _make_layer(self, planes, blocks, stride=1):
118
+ layers = [Bottleneck(self._inplanes, planes, stride)]
119
+ self._inplanes = planes * Bottleneck.expansion
120
+ for _ in range(1, blocks):
121
+ layers.append(Bottleneck(self._inplanes, planes))
122
+ return nn.Sequential(*layers)
123
+
124
+ def forward(self, x):
125
+ self.intermediate_features = []
126
+
127
+ def stem(x):
128
+ x = self.relu1(self.bn1(self.conv1(x)))
129
+ x = self.relu2(self.bn2(self.conv2(x)))
130
+ x = self.relu3(self.bn3(self.conv3(x)))
131
+ x = self.avgpool(x)
132
+ return x
133
+
134
+ x = x.type(self.conv1.weight.dtype)
135
+ x = stem(x)
136
+ self.intermediate_features.append(x) # After stem
137
+
138
+ x = self.layer1(x)
139
+ self.intermediate_features.append(x) # After layer1
140
+
141
+ x = self.layer2(x)
142
+ self.intermediate_features.append(x) # After layer2
143
+
144
+ x = self.layer3(x)
145
+ self.intermediate_features.append(x) # After layer3
146
+
147
+ x = self.layer4(x)
148
+ self.intermediate_features.append(x) # After layer4
149
+
150
+ x = self.attnpool(x)
151
+ return x, self.intermediate_features
152
+
153
+
154
+ class LayerNorm(nn.LayerNorm):
155
+ def forward(self, x: torch.Tensor):
156
+ orig_type = x.dtype
157
+ ret = super().forward(x.type(torch.float32))
158
+ return ret.type(orig_type)
159
+
160
+
161
+ class QuickGELU(nn.Module):
162
+ def forward(self, x: torch.Tensor):
163
+ return x * torch.sigmoid(1.702 * x)
164
+
165
+
166
+ class ResidualAttentionBlock(nn.Module):
167
+ def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
168
+ super().__init__()
169
+ self.attn = nn.MultiheadAttention(d_model, n_head)
170
+ self.ln_1 = LayerNorm(d_model)
171
+ self.mlp = nn.Sequential(OrderedDict([
172
+ ("c_fc", nn.Linear(d_model, d_model * 4)),
173
+ ("gelu", QuickGELU()),
174
+ ("c_proj", nn.Linear(d_model * 4, d_model))
175
+ ]))
176
+ self.ln_2 = LayerNorm(d_model)
177
+ self.attn_mask = attn_mask
178
+
179
+ def attention(self, x: torch.Tensor):
180
+ self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
181
+ return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
182
+
183
+ def forward(self, x: torch.Tensor):
184
+ x = x + self.attention(self.ln_1(x))
185
+ x = x + self.mlp(self.ln_2(x))
186
+ return x
187
+
188
+
189
+ class Transformer(nn.Module):
190
+ def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):
191
+ super().__init__()
192
+ self.width = width
193
+ self.layers = layers
194
+ self.attn_mask = attn_mask
195
+ # 使用 ModuleList 管理残差块,便于迭代访问
196
+ self.resblocks = nn.ModuleList([
197
+ ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)
198
+ ])
199
+
200
+ def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, List[torch.Tensor]]:
201
+ """
202
+ 返回:
203
+ - x: 文本编码器最终输出(形状:[L, N, D])
204
+ - intermediate_layers: 各层中间输出列表(每层形状:[L, N, D])
205
+ """
206
+ intermediate_layers = []
207
+ for block in self.resblocks:
208
+ x = block(x)
209
+ intermediate_layers.append(x.clone()) # 记录每一层的输出
210
+ return x, intermediate_layers
211
+
212
+
213
+ class VisionTransformer(nn.Module):
214
+ def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int):
215
+ super().__init__()
216
+ self.input_resolution = input_resolution
217
+ self.output_dim = output_dim
218
+ self.conv1 = nn.Conv2d(3, width, kernel_size=patch_size, stride=patch_size, bias=False)
219
+ self.intermediate_features = []
220
+
221
+ scale = width ** -0.5
222
+ self.class_embedding = nn.Parameter(scale * torch.randn(width))
223
+ self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
224
+ self.ln_pre = LayerNorm(width)
225
+
226
+ self.transformer = Transformer(width, layers, heads)
227
+ self.ln_post = LayerNorm(width)
228
+ self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
229
+
230
+ def forward(self, x: torch.Tensor):
231
+ self.intermediate_features = []
232
+
233
+ x = self.conv1(x) # [*, width, grid, grid]
234
+ self.intermediate_features.append(x) # After conv1
235
+
236
+ x = x.reshape(x.shape[0], x.shape[1], -1) # [*, width, grid**2]
237
+ x = x.permute(0, 2, 1) # [*, grid**2, width]
238
+ x = torch.cat([
239
+ self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device),
240
+ x
241
+ ], dim=1) # [*, grid**2 + 1, width]
242
+
243
+ x = x + self.positional_embedding.to(x.dtype)
244
+ x = self.ln_pre(x)
245
+ self.intermediate_features.append(x) # After positional embedding
246
+
247
+ x = x.permute(1, 0, 2) # NLD -> LND
248
+ x, transformer_intermediate = self.transformer(x) # 获取transformer每层的输出
249
+ self.intermediate_features.extend([t.permute(1, 0, 2) for t in transformer_intermediate]) # 添加transformer各层输出
250
+
251
+ x = x.permute(1, 0, 2) # LND -> NLD
252
+ x = self.ln_post(x[:, 0, :]) # 只取[CLS] token
253
+
254
+ if self.proj is not None:
255
+ x = x @ self.proj
256
+
257
+ return x, self.intermediate_features
258
+
259
+
260
+ class CLIP(nn.Module):
261
+ def __init__(self,
262
+ embed_dim: int,
263
+ image_resolution: int,
264
+ vision_layers: Union[Tuple[int, int, int, int], int],
265
+ vision_width: int,
266
+ vision_patch_size: int,
267
+ context_length: int,
268
+ vocab_size: int,
269
+ transformer_width: int,
270
+ transformer_heads: int,
271
+ transformer_layers: int,
272
+ load_from_clip: bool):
273
+ super().__init__()
274
+ self.context_length = 248
275
+
276
+ if isinstance(vision_layers, (tuple, list)):
277
+ vision_heads = vision_width * 32 // 64
278
+ self.visual = ModifiedResNet(
279
+ layers=vision_layers,
280
+ output_dim=embed_dim,
281
+ heads=vision_heads,
282
+ input_resolution=image_resolution,
283
+ width=vision_width
284
+ )
285
+ else:
286
+ vision_heads = vision_width // 64
287
+ self.visual = VisionTransformer(
288
+ input_resolution=image_resolution,
289
+ patch_size=vision_patch_size,
290
+ width=vision_width,
291
+ layers=vision_layers,
292
+ heads=vision_heads,
293
+ output_dim=embed_dim
294
+ )
295
+
296
+ self.text_transformer = Transformer( # 重命名为text_transformer避免与视觉transformer混淆
297
+ width=transformer_width,
298
+ layers=transformer_layers,
299
+ heads=transformer_heads,
300
+ attn_mask=self.build_attention_mask()
301
+ )
302
+
303
+ self.vocab_size = vocab_size
304
+ self.token_embedding = nn.Embedding(vocab_size, transformer_width)
305
+
306
+ if load_from_clip == False:
307
+ self.positional_embedding = nn.Parameter(torch.empty(248, transformer_width))
308
+ self.positional_embedding_res = nn.Parameter(torch.empty(248, transformer_width))
309
+ else:
310
+ self.positional_embedding = nn.Parameter(torch.empty(77, transformer_width))
311
+
312
+ self.ln_final = LayerNorm(transformer_width)
313
+ self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
314
+ self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
315
+
316
+ self.initialize_parameters()
317
+ self.mask1 = torch.zeros([248, 1])
318
+ self.mask1[:20, :] = 1
319
+ self.mask2 = torch.zeros([248, 1])
320
+ self.mask2[20:, :] = 1
321
+
322
+ def initialize_parameters(self):
323
+ nn.init.normal_(self.token_embedding.weight, std=0.02)
324
+ nn.init.normal_(self.positional_embedding, std=0.01)
325
+
326
+ if isinstance(self.visual, ModifiedResNet):
327
+ if self.visual.attnpool is not None:
328
+ std = self.visual.attnpool.c_proj.in_features ** -0.5
329
+ nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std)
330
+ nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std)
331
+ nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std)
332
+ nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std)
333
+
334
+ for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]:
335
+ for name, param in resnet_block.named_parameters():
336
+ if name.endswith("bn3.weight"):
337
+ nn.init.zeros_(param)
338
+
339
+ proj_std = (self.text_transformer.width ** -0.5) * ((2 * self.text_transformer.layers) ** -0.5)
340
+ attn_std = self.text_transformer.width ** -0.5
341
+ fc_std = (2 * self.text_transformer.width) ** -0.5
342
+ for block in self.text_transformer.resblocks:
343
+ nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
344
+ nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
345
+ nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
346
+ nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
347
+
348
+ if self.text_projection is not None:
349
+ nn.init.normal_(self.text_projection, std=self.text_transformer.width ** -0.5)
350
+
351
+ def build_attention_mask(self):
352
+ mask = torch.empty(self.context_length, self.context_length)
353
+ mask.fill_(float("-inf"))
354
+ mask.triu_(1)
355
+ return mask
356
+
357
+ @property
358
+ def dtype(self):
359
+ return self.visual.conv1.weight.dtype
360
+
361
+ def encode_image(self, image, return_intermediate=False):
362
+ if isinstance(self.visual, ModifiedResNet):
363
+ features, intermediate_features = self.visual(image.type(self.dtype))
364
+ else:
365
+ features, intermediate_features = self.visual(image.type(self.dtype))
366
+
367
+ if return_intermediate:
368
+ return features, intermediate_features
369
+ return features
370
+
371
+ def encode_text(self, text, return_intermediate=False):
372
+ x = self.token_embedding(text).type(self.dtype)
373
+ x = x + (self.positional_embedding.to(x.device) * self.mask1.to(x.device)).type(self.dtype).to(x.device) + \
374
+ (self.positional_embedding_res.to(x.device) * self.mask2.to(x.device)).type(self.dtype).to(x.device)
375
+ x = x.permute(1, 0, 2) # [seq_len, batch, embed_dim]
376
+
377
+ # ���取transformer各层的输出
378
+ x, transformer_intermediate = self.text_transformer(x)
379
+
380
+ x = x.permute(1, 0, 2) # [batch, seq_len, embed_dim]
381
+ x = self.ln_final(x).type(self.dtype)
382
+
383
+ # 只取[EOS] token位置的特征(这里假设text中最大索引处是[EOS])
384
+ x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
385
+
386
+ if return_intermediate:
387
+ # 返回文本特征和transformer各层的中间输出
388
+ return x, [t.permute(1, 0, 2) for t in transformer_intermediate]
389
+ return x
390
+
391
+ def encode_text_full(self, text):
392
+ # 类似encode_text,但返回完整序列的特征
393
+ x = self.token_embedding(text).type(self.dtype)
394
+ x = x + (self.positional_embedding.to(x.device) * self.mask1.to(x.device)).type(self.dtype).to(x.device) + \
395
+ (self.positional_embedding_res.to(x.device) * self.mask2.to(x.device)).type(self.dtype).to(x.device)
396
+ x = x.permute(1, 0, 2)
397
+ x, _ = self.text_transformer(x)
398
+ x = x.permute(1, 0, 2)
399
+ x = self.ln_final(x).type(self.dtype)
400
+ return x
401
+
402
+ def PCA(self, input_tensor, PCA_dim):
403
+ mean = torch.mean(input_tensor, dim=0)
404
+ X_centered = input_tensor - mean.unsqueeze(0)
405
+ X_centered = X_centered.float()
406
+ U, S, Vt = torch.linalg.svd(X_centered, full_matrices=False)
407
+ principal_components = Vt.T[:, :PCA_dim]
408
+ X_transformed = torch.mm(X_centered, principal_components)
409
+ X_reversed = torch.mm(X_transformed, principal_components.T)
410
+ X_reversed += mean
411
+ return X_reversed
412
+
413
+ def forward(self, image, text_long, text_short, rank=None):
414
+ # 获取图像特征和视觉transformer的中间层
415
+ image_features_long, visual_intermediate = self.encode_image(image, return_intermediate=True)
416
+
417
+ # 获取文本特征和文本transformer的中间层
418
+ text_features_long, text_intermediate = self.encode_text(text_long, return_intermediate=True)
419
+ text_features_short = self.encode_text(text_short) # 短文本不需要中间层
420
+
421
+ # 特征归一化
422
+ image_features_long = image_features_long / image_features_long.norm(dim=1, keepdim=True)
423
+ text_features_long = text_features_long / text_features_long.norm(dim=1, keepdim=True)
424
+ text_features_short = text_features_short / text_features_short.norm(dim=1, keepdim=True)
425
+
426
+ # 使用PCA降维获取短图像特征
427
+ image_features_short = self.PCA(image_features_long, 32)
428
+
429
+ # 计算相似度矩阵
430
+ sim_i2tl = torch.matmul(image_features_long, text_features_long.T)
431
+ sim_tl2i = torch.matmul(image_features_long, text_features_long.T).T
432
+
433
+ sim_i2ts = torch.matmul(image_features_short, text_features_short.T)
434
+ sim_ts2i = torch.matmul(image_features_short, text_features_short.T).T
435
+
436
+ # 应用温度缩放
437
+ sim_i2tl = self.logit_scale.exp() * sim_i2tl
438
+ sim_tl2i = self.logit_scale.exp() * sim_tl2i
439
+ sim_i2ts = self.logit_scale.exp() * sim_i2ts
440
+ sim_ts2i = self.logit_scale.exp() * sim_ts2i
441
+
442
+ # 计算对比损失
443
+ bs = image.size(0)
444
+ targets = torch.arange(bs, dtype=torch.long).to(image.device)
445
+
446
+ loss_itcl = (F.cross_entropy(sim_i2tl, targets, label_smoothing=0.1) +
447
+ F.cross_entropy(sim_tl2i, targets, label_smoothing=0.1)) / 2
448
+ loss_itcs = (F.cross_entropy(sim_i2ts, targets, label_smoothing=0.1) +
449
+ F.cross_entropy(sim_ts2i, targets, label_smoothing=0.1)) / 2
450
+
451
+ # 返回损失和中间层特征
452
+ return loss_itcl, loss_itcs, {
453
+ 'visual': visual_intermediate,
454
+ 'text': text_intermediate
455
+ }
456
+
457
+ def convert_weights(model: nn.Module):
458
+ def _convert_weights_to_fp16(l):
459
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
460
+ l.weight.data = l.weight.data.half()
461
+ if l.bias is not None:
462
+ l.bias.data = l.bias.data.half()
463
+
464
+ if isinstance(l, nn.MultiheadAttention):
465
+ for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
466
+ tensor = getattr(l, attr)
467
+ if tensor is not None:
468
+ tensor.data = tensor.data.half()
469
+
470
+ for name in ["text_projection", "proj"]:
471
+ if hasattr(l, name):
472
+ attr = getattr(l, name)
473
+ if attr is not None:
474
+ attr.data = attr.data.half()
475
+
476
+ model.apply(_convert_weights_to_fp16)
477
+
478
+
479
+ def build_model(state_dict: dict, load_from_clip: bool):
480
+ vit = "visual.proj" in state_dict
481
+
482
+ if vit:
483
+ vision_width = state_dict["visual.conv1.weight"].shape[0]
484
+ vision_layers = len(
485
+ [k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
486
+ vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
487
+ grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
488
+ image_resolution = vision_patch_size * grid_size
489
+ else:
490
+ counts = [len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in
491
+ [1, 2, 3, 4]]
492
+ vision_layers = tuple(counts)
493
+ vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
494
+ output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
495
+ vision_patch_size = None
496
+ image_resolution = output_width * 32
497
+
498
+ embed_dim = state_dict["text_projection"].shape[1]
499
+ context_length = state_dict["positional_embedding"].shape[0]
500
+ vocab_size = state_dict["token_embedding.weight"].shape[0]
501
+ transformer_width = state_dict["ln_final.weight"].shape[0]
502
+ transformer_heads = transformer_width // 64
503
+ transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith("transformer.resblocks")))
504
+
505
+ model = CLIP(
506
+ embed_dim,
507
+ image_resolution, vision_layers, vision_width, vision_patch_size,
508
+ context_length, vocab_size, transformer_width, transformer_heads, transformer_layers, load_from_clip
509
+ )
510
+
511
+ for key in ["input_resolution", "context_length", "vocab_size"]:
512
+ if key in state_dict:
513
+ del state_dict[key]
514
+
515
+ convert_weights(model)
516
+ model.load_state_dict(state_dict)
517
+ return model.eval()
model/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