y8lc2wpi commited on
Commit
1ec36f8
1 Parent(s): e6b3ddd

Upload folder using huggingface_hub

Browse files
.ipynb_checkpoints/config-checkpoint.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/notebooks/qwenv",
3
+ "architectures": [
4
+ "LlamaForCausalLM"
5
+ ],
6
+ "bos_token_id": 151643,
7
+ "eos_token_id": 151643,
8
+ "hidden_act": "silu",
9
+ "hidden_size": 4096,
10
+ "initializer_range": 0.02,
11
+ "intermediate_size": 11008,
12
+ "max_position_embeddings": 6144,
13
+ "model_type": "llama",
14
+ "num_attention_heads": 32,
15
+ "num_hidden_layers": 32,
16
+ "num_key_value_heads": 32,
17
+ "pad_token_id": 0,
18
+ "pretraining_tp": 1,
19
+ "rms_norm_eps": 1e-05,
20
+ "rope_scaling": null,
21
+ "tie_word_embeddings": false,
22
+ "torch_dtype": "float16",
23
+ "transformers_version": "4.32.0.dev0",
24
+ "use_cache": false,
25
+ "vocab_size": 151936
26
+ }
.ipynb_checkpoints/generation_config-checkpoint.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "chat_format": "chatml",
3
+ "decay_bound": 0.0,
4
+ "decay_factor": 1.0,
5
+ "do_sample": true,
6
+ "eos_token_id": 151643,
7
+ "factual_nucleus_sampling": false,
8
+ "max_context_size": 1024,
9
+ "max_generate_size": 512,
10
+ "max_new_tokens": 512,
11
+ "pad_token_id": 151643,
12
+ "stop_words_ids": [
13
+ [
14
+ 151643
15
+ ]
16
+ ],
17
+ "top_k": 0,
18
+ "top_p": 0.8,
19
+ "transformers_version": "4.32.0.dev0"
20
+ }
.ipynb_checkpoints/special_tokens_map-checkpoint.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<|endoftext|>",
3
+ "eos_token": "<|endoftext|>",
4
+ "unk_token": "<|endoftext|>"
5
+ }
.ipynb_checkpoints/tokenization_qwen-checkpoint.py ADDED
@@ -0,0 +1,566 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Alibaba Cloud.
2
+ #
3
+ # This source code is licensed under the license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ """Tokenization classes for QWen."""
7
+
8
+ import base64
9
+ import logging
10
+ import os
11
+ import requests
12
+ import unicodedata
13
+ from typing import Collection, Dict, List, Set, Tuple, Union, Any, Callable, Optional
14
+
15
+ import tiktoken
16
+ import numpy as np
17
+ from PIL import Image
18
+ from PIL import ImageFont
19
+ from PIL import ImageDraw
20
+ from transformers import PreTrainedTokenizer, AddedToken
21
+ from transformers.utils import try_to_load_from_cache
22
+
23
+ import matplotlib.pyplot as plt
24
+ import matplotlib.colors as mcolors
25
+ from matplotlib.font_manager import FontProperties
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+
30
+ VOCAB_FILES_NAMES = {"vocab_file": "qwen.tiktoken", "ttf": "SimSun.ttf"}
31
+
32
+ PAT_STR = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
33
+ ENDOFTEXT = "<|endoftext|>"
34
+ IMSTART = "<|im_start|>"
35
+ IMEND = "<|im_end|>"
36
+ # as the default behavior is changed to allow special tokens in
37
+ # regular texts, the surface forms of special tokens need to be
38
+ # as different as possible to minimize the impact
39
+ EXTRAS = tuple((f"<|extra_{i}|>" for i in range(205)))
40
+ SPECIAL_TOKENS = (
41
+ ENDOFTEXT,
42
+ IMSTART,
43
+ IMEND,
44
+ ) + EXTRAS
45
+ IMG_TOKEN_SPAN = 256
46
+
47
+
48
+ def _load_tiktoken_bpe(tiktoken_bpe_file: str) -> Dict[bytes, int]:
49
+ with open(tiktoken_bpe_file, "rb") as f:
50
+ contents = f.read()
51
+ return {
52
+ base64.b64decode(token): int(rank)
53
+ for token, rank in (line.split() for line in contents.splitlines() if line)
54
+ }
55
+
56
+ def _list_find(
57
+ input_list: List[Any],
58
+ candidates: Tuple[Any],
59
+ start: int = 0,
60
+ ):
61
+ for i in range(start, len(input_list)):
62
+ if input_list[i] in candidates:
63
+ return i
64
+ return -1
65
+
66
+ def _replace_closed_tag(
67
+ input_tokens: List[Any],
68
+ start_tags: Union[Any, Tuple[Any]],
69
+ end_tags: Union[Any, Tuple[Any]],
70
+ inclusive_replace_func: Callable,
71
+ exclusive_replace_func: Callable = lambda x: x,
72
+ ):
73
+ if isinstance(start_tags, (str, int)):
74
+ start_tags = (start_tags,)
75
+ if isinstance(end_tags, (str, int)):
76
+ end_tags = (end_tags,)
77
+ assert len(start_tags) == len(end_tags)
78
+
79
+ output_tokens = []
80
+ end = 0
81
+ while True:
82
+ start = _list_find(input_tokens, start_tags, end)
83
+ if start == -1:
84
+ break
85
+ output_tokens.extend(exclusive_replace_func(input_tokens[end : start]))
86
+ tag_idx = start_tags.index(input_tokens[start])
87
+ end = _list_find(input_tokens, (end_tags[tag_idx],), start)
88
+ if end == -1:
89
+ raise ValueError("Unclosed image token")
90
+ output_tokens.extend(inclusive_replace_func(input_tokens[start : end + 1]))
91
+ end += 1
92
+ output_tokens.extend(exclusive_replace_func(input_tokens[end : ]))
93
+ return output_tokens
94
+
95
+ class QWenTokenizer(PreTrainedTokenizer):
96
+ """QWen tokenizer."""
97
+
98
+ vocab_files_names = VOCAB_FILES_NAMES
99
+
100
+ def __init__(
101
+ self,
102
+ vocab_file,
103
+ errors="replace",
104
+ image_start_tag='<img>',
105
+ image_end_tag='</img>',
106
+ image_pad_tag='<imgpad>',
107
+ ref_start_tag='<ref>',
108
+ ref_end_tag='</ref>',
109
+ box_start_tag='<box>',
110
+ box_end_tag='</box>',
111
+ quad_start_tag='<quad>',
112
+ quad_end_tag='</quad>',
113
+ **kwargs,
114
+ ):
115
+ super().__init__(**kwargs)
116
+ self.image_start_tag = image_start_tag
117
+ self.image_end_tag = image_end_tag
118
+ self.image_pad_tag = image_pad_tag
119
+ self.ref_start_tag = ref_start_tag
120
+ self.ref_end_tag = ref_end_tag
121
+ self.box_start_tag = box_start_tag
122
+ self.box_end_tag = box_end_tag
123
+ self.quad_start_tag = quad_start_tag
124
+ self.quad_end_tag = quad_end_tag
125
+ self.IMAGE_ST = (
126
+ ref_start_tag, ref_end_tag,
127
+ box_start_tag, box_end_tag,
128
+ quad_start_tag, quad_end_tag,
129
+ image_start_tag, image_end_tag,
130
+ image_pad_tag
131
+ )
132
+
133
+ self.errors = errors # how to handle errors in decoding
134
+
135
+ self.mergeable_ranks = _load_tiktoken_bpe(vocab_file) # type: dict[bytes, int]
136
+ self.special_tokens = {
137
+ token: index
138
+ for index, token in enumerate(
139
+ SPECIAL_TOKENS + self.IMAGE_ST, start=len(self.mergeable_ranks)
140
+ )
141
+ }
142
+ self.img_start_id = self.special_tokens[self.image_start_tag]
143
+ self.img_end_id = self.special_tokens[self.image_end_tag]
144
+ self.img_pad_id = self.special_tokens[self.image_pad_tag]
145
+ self.ref_start_id = self.special_tokens[self.ref_start_tag]
146
+ self.ref_end_id = self.special_tokens[self.ref_end_tag]
147
+ self.box_start_id = self.special_tokens[self.box_start_tag]
148
+ self.box_end_id = self.special_tokens[self.box_end_tag]
149
+ self.quad_start_id = self.special_tokens[self.quad_start_tag]
150
+ self.quad_end_id = self.special_tokens[self.quad_end_tag]
151
+
152
+ enc = tiktoken.Encoding(
153
+ "Qwen",
154
+ pat_str=PAT_STR,
155
+ mergeable_ranks=self.mergeable_ranks,
156
+ special_tokens=self.special_tokens,
157
+ )
158
+ assert (
159
+ len(self.mergeable_ranks) + len(self.special_tokens) == enc.n_vocab
160
+ ), f"{len(self.mergeable_ranks) + len(self.special_tokens)} != {enc.n_vocab} in encoding"
161
+
162
+ self.decoder = {
163
+ v: k for k, v in self.mergeable_ranks.items()
164
+ } # type: dict[int, bytes|str]
165
+ self.decoder.update({v: k for k, v in self.special_tokens.items()})
166
+
167
+ self.tokenizer = enc # type: tiktoken.Encoding
168
+
169
+ self.eod_id = self.tokenizer.eot_token
170
+ self.im_start_id = self.special_tokens[IMSTART]
171
+ self.im_end_id = self.special_tokens[IMEND]
172
+
173
+ def __len__(self) -> int:
174
+ return self.tokenizer.n_vocab
175
+
176
+ def get_vocab(self) -> Dict[bytes, int]:
177
+ return self.mergeable_ranks
178
+
179
+ def convert_tokens_to_ids(
180
+ self, tokens: Union[bytes, str, List[Union[bytes, str]]]
181
+ ) -> List[int]:
182
+ ids = []
183
+ if isinstance(tokens, (str, bytes)):
184
+ if tokens in self.special_tokens:
185
+ return self.special_tokens[tokens]
186
+ else:
187
+ return self.mergeable_ranks.get(tokens)
188
+ for token in tokens:
189
+ if token in self.special_tokens:
190
+ ids.append(self.special_tokens[token])
191
+ else:
192
+ ids.append(self.mergeable_ranks.get(token))
193
+ return ids
194
+
195
+ def _add_tokens(self, new_tokens: Union[List[str], List[AddedToken]], special_tokens: bool = False) -> int:
196
+ if not special_tokens and new_tokens:
197
+ raise ValueError('Adding regular tokens is not supported')
198
+ for token in new_tokens:
199
+ surface_form = token.content if isinstance(token, AddedToken) else token
200
+ if surface_form not in SPECIAL_TOKENS + self.IMAGE_ST:
201
+ raise ValueError('Adding unknown special tokens is not supported')
202
+ return 0
203
+
204
+ def save_vocabulary(self, save_directory: str, **kwargs) -> Tuple[str]:
205
+ """
206
+ Save only the vocabulary of the tokenizer (vocabulary).
207
+
208
+ Returns:
209
+ `Tuple(str)`: Paths to the files saved.
210
+ """
211
+ file_path = os.path.join(save_directory, "qwen.tiktoken")
212
+ with open(file_path, "w", encoding="utf8") as w:
213
+ for k, v in self.mergeable_ranks.items():
214
+ line = base64.b64encode(k).decode("utf8") + " " + str(v) + "\n"
215
+ w.write(line)
216
+ return (file_path,)
217
+
218
+ def tokenize(
219
+ self,
220
+ text: str,
221
+ allowed_special: Union[Set, str] = "all",
222
+ disallowed_special: Union[Collection, str] = (),
223
+ **kwargs,
224
+ ) -> List[Union[bytes, str]]:
225
+ """
226
+ Converts a string in a sequence of tokens.
227
+
228
+ Args:
229
+ text (`str`):
230
+ The sequence to be encoded.
231
+ allowed_special (`Literal["all"]` or `set`):
232
+ The surface forms of the tokens to be encoded as special tokens in regular texts.
233
+ Default to "all".
234
+ disallowed_special (`Literal["all"]` or `Collection`):
235
+ The surface forms of the tokens that should not be in regular texts and trigger errors.
236
+ Default to an empty tuple.
237
+
238
+ kwargs (additional keyword arguments, *optional*):
239
+ Will be passed to the underlying model specific encode method.
240
+
241
+ Returns:
242
+ `List[bytes|str]`: The list of tokens.
243
+ """
244
+ tokens = []
245
+ text = unicodedata.normalize("NFC", text)
246
+
247
+ # this implementation takes a detour: text -> token id -> token surface forms
248
+ for t in self.tokenizer.encode(
249
+ text, allowed_special=allowed_special, disallowed_special=disallowed_special
250
+ ):
251
+ tokens.append(self.decoder[t])
252
+
253
+ def _encode_imgurl(img_tokens):
254
+ assert img_tokens[0] == self.image_start_tag and img_tokens[-1] == self.image_end_tag
255
+ img_tokens = img_tokens[1:-1]
256
+ img_url = b''.join(img_tokens)
257
+ out_img_tokens = list(map(self.decoder.get, img_url))
258
+ if len(out_img_tokens) > IMG_TOKEN_SPAN:
259
+ raise ValueError("The content in {}..{} is too long".format(
260
+ self.image_start_tag, self.image_end_tag))
261
+ out_img_tokens.extend([self.image_pad_tag] * (IMG_TOKEN_SPAN - len(out_img_tokens)))
262
+ out_img_tokens = [self.image_start_tag] + out_img_tokens + [self.image_end_tag]
263
+ return out_img_tokens
264
+
265
+ return _replace_closed_tag(tokens, self.image_start_tag, self.image_end_tag, _encode_imgurl)
266
+
267
+ def convert_tokens_to_string(self, tokens: List[Union[bytes, str]]) -> str:
268
+ """
269
+ Converts a sequence of tokens in a single string.
270
+ """
271
+ text = ""
272
+ temp = b""
273
+ for t in tokens:
274
+ if isinstance(t, str):
275
+ if temp:
276
+ text += temp.decode("utf-8", errors=self.errors)
277
+ temp = b""
278
+ text += t
279
+ elif isinstance(t, bytes):
280
+ temp += t
281
+ else:
282
+ raise TypeError("token should only be of type types or str")
283
+ if temp:
284
+ text += temp.decode("utf-8", errors=self.errors)
285
+ return text
286
+
287
+ @property
288
+ def vocab_size(self):
289
+ return self.tokenizer.n_vocab
290
+
291
+ def _convert_id_to_token(self, index: int) -> Union[bytes, str]:
292
+ """Converts an id to a token, special tokens included"""
293
+ if index in self.decoder:
294
+ return self.decoder[index]
295
+ raise ValueError("unknown ids")
296
+
297
+ def _convert_token_to_id(self, token: Union[bytes, str]) -> int:
298
+ """Converts a token to an id using the vocab, special tokens included"""
299
+ if token in self.special_tokens:
300
+ return self.special_tokens[token]
301
+ if token in self.mergeable_ranks:
302
+ return self.mergeable_ranks[token]
303
+ raise ValueError("unknown token")
304
+
305
+ def _tokenize(self, text: str, **kwargs):
306
+ """
307
+ Converts a string in a sequence of tokens (string), using the tokenizer. Split in words for word-based
308
+ vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces).
309
+
310
+ Do NOT take care of added tokens.
311
+ """
312
+ raise NotImplementedError
313
+
314
+ def _decode(
315
+ self,
316
+ token_ids: Union[int, List[int]],
317
+ skip_special_tokens: bool = False,
318
+ errors: str = None,
319
+ **kwargs,
320
+ ) -> str:
321
+ if isinstance(token_ids, int):
322
+ token_ids = [token_ids]
323
+
324
+ def _decode_imgurl(img_token_ids):
325
+ assert img_token_ids[0] == self.img_start_id and img_token_ids[-1] == self.img_end_id
326
+ img_token_ids = img_token_ids[1:-1]
327
+ img_token_ids = img_token_ids[ : img_token_ids.index(self.img_pad_id)]
328
+ img_url = bytes(img_token_ids).decode('utf-8')
329
+ return [self.img_start_id] + self.tokenizer.encode(img_url) + [self.img_end_id]
330
+
331
+ token_ids = _replace_closed_tag(token_ids, self.img_start_id, self.img_end_id, _decode_imgurl)
332
+
333
+ if skip_special_tokens:
334
+ token_ids = [i for i in token_ids if i < self.eod_id]
335
+ return self.tokenizer.decode(token_ids, errors=errors or self.errors)
336
+
337
+ def to_list_format(self, text: str):
338
+ text = unicodedata.normalize("NFC", text)
339
+ token_ids = self.tokenizer.encode(
340
+ text, allowed_special=set(self.IMAGE_ST + (ENDOFTEXT,)))
341
+
342
+ def _encode_vl_info(tokens):
343
+ if len(tokens) == 0:
344
+ return []
345
+ if tokens[0] == self.img_start_id and tokens[-1] == self.img_end_id:
346
+ key = 'image'
347
+ elif tokens[0] == self.ref_start_id and tokens[-1] == self.ref_end_id:
348
+ key = 'ref'
349
+ elif tokens[0] == self.box_start_id and tokens[-1] == self.box_end_id:
350
+ key = 'box'
351
+ elif tokens[0] == self.quad_start_id and tokens[-1] == self.quad_end_id:
352
+ key = 'quad'
353
+ else:
354
+ _tobytes = lambda x: x.encode('utf-8') if isinstance(x, str) else x
355
+ return [{'text': b''.join(map(_tobytes, map(self.decoder.get, tokens))).decode('utf-8')}]
356
+ val = b''.join(map(self.decoder.get, tokens[1:-1])).decode('utf-8')
357
+ return [{key: val}]
358
+
359
+ return _replace_closed_tag(
360
+ token_ids,
361
+ (self.img_start_id, self.ref_start_id, self.box_start_id, self.quad_start_id),
362
+ (self.img_end_id, self.ref_end_id, self.box_end_id, self.quad_end_id),
363
+ _encode_vl_info,
364
+ _encode_vl_info,
365
+ )
366
+
367
+ def from_list_format(self, list_format: List[Dict]):
368
+ text = ''
369
+ num_images = 0
370
+ for ele in list_format:
371
+ if 'image' in ele:
372
+ num_images += 1
373
+ text += f'Picture {num_images}:'
374
+ text += self.image_start_tag + ele['image'] + self.image_end_tag
375
+ text += '\n'
376
+ elif 'text' in ele:
377
+ text += ele['text']
378
+ elif 'box' in ele:
379
+ if 'ref' in ele:
380
+ text += self.ref_start_tag + ele['ref'] + self.ref_end_tag
381
+ for box in ele['box']:
382
+ text += self.box_start_tag + '(%d,%d),(%d,%d)' % (box[0], box[1], box[2], box[3]) + self.box_end_tag
383
+ else:
384
+ raise ValueError("Unsupport element: " + str(ele))
385
+ return text
386
+
387
+ def _fetch_latest_picture(self, response, history):
388
+ if history is None:
389
+ history = []
390
+ _history = history + [(response, None)]
391
+ for q, r in _history[::-1]:
392
+ for ele in self.to_list_format(q)[::-1]:
393
+ if 'image' in ele:
394
+ return ele['image']
395
+ return None
396
+
397
+ def _fetch_all_box_with_ref(self, text):
398
+ list_format = self.to_list_format(text)
399
+ output = []
400
+ for i, ele in enumerate(list_format):
401
+ if 'box' in ele:
402
+ bbox = tuple(map(int, ele['box'].replace('(', '').replace(')', '').split(',')))
403
+ assert len(bbox) == 4
404
+ output.append({'box': bbox})
405
+ if i > 0 and 'ref' in list_format[i-1]:
406
+ output[-1]['ref'] = list_format[i-1]['ref'].strip()
407
+ return output
408
+
409
+ def draw_bbox_on_latest_picture(
410
+ self,
411
+ response,
412
+ history=None,
413
+ ) -> Optional[Image.Image]:
414
+ image = self._fetch_latest_picture(response, history)
415
+ if image is None:
416
+ return None
417
+ if image.startswith("http://") or image.startswith("https://"):
418
+ image = Image.open(requests.get(image, stream=True).raw).convert("RGB")
419
+ h, w = image.height, image.width
420
+ else:
421
+ image = plt.imread(image)
422
+ h, w = image.shape[0], image.shape[1]
423
+ visualizer = Visualizer(image)
424
+
425
+ boxes = self._fetch_all_box_with_ref(response)
426
+ if not boxes:
427
+ return None
428
+ color = random.choice([_ for _ in mcolors.TABLEAU_COLORS.keys()]) # init color
429
+ for box in boxes:
430
+ if 'ref' in box: # random new color for new refexps
431
+ color = random.choice([_ for _ in mcolors.TABLEAU_COLORS.keys()])
432
+ x1, y1, x2, y2 = box['box']
433
+ x1, y1, x2, y2 = (int(x1 / 1000 * w), int(y1 / 1000 * h), int(x2 / 1000 * w), int(y2 / 1000 * h))
434
+ visualizer.draw_box((x1, y1, x2, y2), alpha=1, edge_color=color)
435
+ if 'ref' in box:
436
+ visualizer.draw_text(box['ref'], (x1, y1), color=color, horizontal_alignment="left")
437
+ return visualizer.output
438
+
439
+
440
+ import colorsys
441
+ import logging
442
+ import math
443
+ import numpy as np
444
+ import matplotlib as mpl
445
+ import matplotlib.colors as mplc
446
+ import matplotlib.figure as mplfigure
447
+ import torch
448
+ from matplotlib.backends.backend_agg import FigureCanvasAgg
449
+ from PIL import Image
450
+ import random
451
+
452
+ logger = logging.getLogger(__name__)
453
+
454
+
455
+ class VisImage:
456
+ def __init__(self, img, scale=1.0):
457
+ self.img = img
458
+ self.scale = scale
459
+ self.width, self.height = img.shape[1], img.shape[0]
460
+ self._setup_figure(img)
461
+
462
+ def _setup_figure(self, img):
463
+ fig = mplfigure.Figure(frameon=False)
464
+ self.dpi = fig.get_dpi()
465
+ # add a small 1e-2 to avoid precision lost due to matplotlib's truncation
466
+ # (https://github.com/matplotlib/matplotlib/issues/15363)
467
+ fig.set_size_inches(
468
+ (self.width * self.scale + 1e-2) / self.dpi,
469
+ (self.height * self.scale + 1e-2) / self.dpi,
470
+ )
471
+ self.canvas = FigureCanvasAgg(fig)
472
+ # self.canvas = mpl.backends.backend_cairo.FigureCanvasCairo(fig)
473
+ ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
474
+ ax.axis("off")
475
+ self.fig = fig
476
+ self.ax = ax
477
+ self.reset_image(img)
478
+
479
+ def reset_image(self, img):
480
+ img = img.astype("uint8")
481
+ self.ax.imshow(img, extent=(0, self.width, self.height, 0), interpolation="nearest")
482
+
483
+ def save(self, filepath):
484
+ self.fig.savefig(filepath)
485
+
486
+ def get_image(self):
487
+ canvas = self.canvas
488
+ s, (width, height) = canvas.print_to_buffer()
489
+
490
+ buffer = np.frombuffer(s, dtype="uint8")
491
+
492
+ img_rgba = buffer.reshape(height, width, 4)
493
+ rgb, alpha = np.split(img_rgba, [3], axis=2)
494
+ return rgb.astype("uint8")
495
+
496
+
497
+ class Visualizer:
498
+ def __init__(self, img_rgb, metadata=None, scale=1.0):
499
+ self.img = np.asarray(img_rgb).clip(0, 255).astype(np.uint8)
500
+ self.font_path = try_to_load_from_cache("Qwen/Qwen-VL-Chat", "SimSun.ttf")
501
+ self.output = VisImage(self.img, scale=scale)
502
+ self.cpu_device = torch.device("cpu")
503
+
504
+ # too small texts are useless, therefore clamp to 14
505
+ self._default_font_size = max(
506
+ np.sqrt(self.output.height * self.output.width) // 30, 15 // scale
507
+ )
508
+
509
+ def draw_text(
510
+ self,
511
+ text,
512
+ position,
513
+ *,
514
+ font_size=None,
515
+ color="g",
516
+ horizontal_alignment="center",
517
+ rotation=0,
518
+ ):
519
+ if not font_size:
520
+ font_size = self._default_font_size
521
+
522
+ # since the text background is dark, we don't want the text to be dark
523
+ color = np.maximum(list(mplc.to_rgb(color)), 0.2)
524
+ color[np.argmax(color)] = max(0.8, np.max(color))
525
+
526
+ x, y = position
527
+ self.output.ax.text(
528
+ x,
529
+ y,
530
+ text,
531
+ size=font_size * self.output.scale,
532
+ fontproperties=FontProperties(fname=self.font_path),
533
+ bbox={"facecolor": "black", "alpha": 0.8, "pad": 0.7, "edgecolor": "none"},
534
+ verticalalignment="top",
535
+ horizontalalignment=horizontal_alignment,
536
+ color=color,
537
+ zorder=10,
538
+ rotation=rotation,
539
+ )
540
+ return self.output
541
+
542
+ def draw_box(self, box_coord, alpha=0.5, edge_color="g", line_style="-"):
543
+
544
+ x0, y0, x1, y1 = box_coord
545
+ width = x1 - x0
546
+ height = y1 - y0
547
+
548
+ linewidth = max(self._default_font_size / 4, 1)
549
+
550
+ self.output.ax.add_patch(
551
+ mpl.patches.Rectangle(
552
+ (x0, y0),
553
+ width,
554
+ height,
555
+ fill=False,
556
+ edgecolor=edge_color,
557
+ linewidth=linewidth * self.output.scale,
558
+ alpha=alpha,
559
+ linestyle=line_style,
560
+ )
561
+ )
562
+ return self.output
563
+
564
+ def get_output(self):
565
+
566
+ return self.output
.ipynb_checkpoints/tokenizer_config-checkpoint.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_max_length": 999999999999999999,
3
+ "tokenizer_class": "QWenTokenizer",
4
+ "auto_map": {
5
+ "AutoTokenizer": [
6
+ "tokenization_qwen.QWenTokenizer",
7
+ null
8
+ ]
9
+ }
10
+ }
config.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/notebooks/pub1",
3
+ "architectures": [
4
+ "LlamaForCausalLM"
5
+ ],
6
+ "bos_token_id": 151643,
7
+ "eos_token_id": 151643,
8
+ "hidden_act": "silu",
9
+ "hidden_size": 4096,
10
+ "initializer_range": 0.02,
11
+ "intermediate_size": 11008,
12
+ "max_position_embeddings": 6144,
13
+ "model_type": "llama",
14
+ "num_attention_heads": 32,
15
+ "num_hidden_layers": 32,
16
+ "num_key_value_heads": 32,
17
+ "pad_token_id": 0,
18
+ "pretraining_tp": 1,
19
+ "rms_norm_eps": 1e-05,
20
+ "rope_scaling": null,
21
+ "tie_word_embeddings": false,
22
+ "torch_dtype": "float16",
23
+ "transformers_version": "4.32.0.dev0",
24
+ "use_cache": false,
25
+ "vocab_size": 151936
26
+ }
generation_config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "chat_format": "chatml",
3
+ "decay_bound": 0.0,
4
+ "decay_factor": 1.0,
5
+ "do_sample": true,
6
+ "eos_token_id": 151643,
7
+ "factual_nucleus_sampling": false,
8
+ "max_context_size": 1024,
9
+ "max_generate_size": 512,
10
+ "max_new_tokens": 512,
11
+ "pad_token_id": 151643,
12
+ "stop_words_ids": [
13
+ [
14
+ 151643
15
+ ]
16
+ ],
17
+ "top_k": 0,
18
+ "top_p": 0.8,
19
+ "transformers_version": "4.32.0.dev0"
20
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
pytorch_model-00001-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:530544f45e358bdef6e89de90b1080ae00539242bee59bd5b620c867842a068f
3
+ size 1964005971
pytorch_model-00002-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b0788b211ea06307fc12af22c67f40b4da7413dfe3d3b3bfba67f1562e3697b7
3
+ size 1933673729
pytorch_model-00003-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c11031bababa6d8628fba295ffbe78206e25b86ba746460e0fb3eda9fe98060d
3
+ size 1933673729
pytorch_model-00004-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3a7f9275ddb70230b630f2fdd5ea902cc651a117737bbb960c3d57c201bb9f08
3
+ size 1990296303
pytorch_model-00005-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:648cca7986994ccdb372dd88208f6670f12dfc6d596f2011e5b1560e48481654
3
+ size 1990296897
pytorch_model-00006-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cd7e821703872b76a9e4055362a449e030e6b5c1301be5464df9b37cebfc2657
3
+ size 1990296897
pytorch_model-00007-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2876ed1f592aabb3c02dde1441e3cf486029d02287280146c69f60dad81c46d9
3
+ size 1990296897
pytorch_model-00008-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4d4cd3230172a536631e7e29e72508a7fb517cef05d94f3bac8f59fa67da6ca3
3
+ size 1649439207
pytorch_model.bin.index.json ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 15441870848
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "pytorch_model-00008-of-00008.bin",
7
+ "model.embed_tokens.weight": "pytorch_model-00001-of-00008.bin",
8
+ "model.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00008.bin",
9
+ "model.layers.0.mlp.down_proj.weight": "pytorch_model-00001-of-00008.bin",
10
+ "model.layers.0.mlp.gate_proj.weight": "pytorch_model-00001-of-00008.bin",
11
+ "model.layers.0.mlp.up_proj.weight": "pytorch_model-00001-of-00008.bin",
12
+ "model.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00008.bin",
13
+ "model.layers.0.self_attn.k_proj.weight": "pytorch_model-00001-of-00008.bin",
14
+ "model.layers.0.self_attn.o_proj.weight": "pytorch_model-00001-of-00008.bin",
15
+ "model.layers.0.self_attn.q_proj.weight": "pytorch_model-00001-of-00008.bin",
16
+ "model.layers.0.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00008.bin",
17
+ "model.layers.0.self_attn.v_proj.weight": "pytorch_model-00001-of-00008.bin",
18
+ "model.layers.1.input_layernorm.weight": "pytorch_model-00002-of-00008.bin",
19
+ "model.layers.1.mlp.down_proj.weight": "pytorch_model-00002-of-00008.bin",
20
+ "model.layers.1.mlp.gate_proj.weight": "pytorch_model-00001-of-00008.bin",
21
+ "model.layers.1.mlp.up_proj.weight": "pytorch_model-00001-of-00008.bin",
22
+ "model.layers.1.post_attention_layernorm.weight": "pytorch_model-00002-of-00008.bin",
23
+ "model.layers.1.self_attn.k_proj.weight": "pytorch_model-00001-of-00008.bin",
24
+ "model.layers.1.self_attn.o_proj.weight": "pytorch_model-00001-of-00008.bin",
25
+ "model.layers.1.self_attn.q_proj.weight": "pytorch_model-00001-of-00008.bin",
26
+ "model.layers.1.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00008.bin",
27
+ "model.layers.1.self_attn.v_proj.weight": "pytorch_model-00001-of-00008.bin",
28
+ "model.layers.10.input_layernorm.weight": "pytorch_model-00003-of-00008.bin",
29
+ "model.layers.10.mlp.down_proj.weight": "pytorch_model-00003-of-00008.bin",
30
+ "model.layers.10.mlp.gate_proj.weight": "pytorch_model-00003-of-00008.bin",
31
+ "model.layers.10.mlp.up_proj.weight": "pytorch_model-00003-of-00008.bin",
32
+ "model.layers.10.post_attention_layernorm.weight": "pytorch_model-00003-of-00008.bin",
33
+ "model.layers.10.self_attn.k_proj.weight": "pytorch_model-00003-of-00008.bin",
34
+ "model.layers.10.self_attn.o_proj.weight": "pytorch_model-00003-of-00008.bin",
35
+ "model.layers.10.self_attn.q_proj.weight": "pytorch_model-00003-of-00008.bin",
36
+ "model.layers.10.self_attn.rotary_emb.inv_freq": "pytorch_model-00003-of-00008.bin",
37
+ "model.layers.10.self_attn.v_proj.weight": "pytorch_model-00003-of-00008.bin",
38
+ "model.layers.11.input_layernorm.weight": "pytorch_model-00004-of-00008.bin",
39
+ "model.layers.11.mlp.down_proj.weight": "pytorch_model-00004-of-00008.bin",
40
+ "model.layers.11.mlp.gate_proj.weight": "pytorch_model-00004-of-00008.bin",
41
+ "model.layers.11.mlp.up_proj.weight": "pytorch_model-00004-of-00008.bin",
42
+ "model.layers.11.post_attention_layernorm.weight": "pytorch_model-00004-of-00008.bin",
43
+ "model.layers.11.self_attn.k_proj.weight": "pytorch_model-00003-of-00008.bin",
44
+ "model.layers.11.self_attn.o_proj.weight": "pytorch_model-00003-of-00008.bin",
45
+ "model.layers.11.self_attn.q_proj.weight": "pytorch_model-00003-of-00008.bin",
46
+ "model.layers.11.self_attn.rotary_emb.inv_freq": "pytorch_model-00003-of-00008.bin",
47
+ "model.layers.11.self_attn.v_proj.weight": "pytorch_model-00003-of-00008.bin",
48
+ "model.layers.12.input_layernorm.weight": "pytorch_model-00004-of-00008.bin",
49
+ "model.layers.12.mlp.down_proj.weight": "pytorch_model-00004-of-00008.bin",
50
+ "model.layers.12.mlp.gate_proj.weight": "pytorch_model-00004-of-00008.bin",
51
+ "model.layers.12.mlp.up_proj.weight": "pytorch_model-00004-of-00008.bin",
52
+ "model.layers.12.post_attention_layernorm.weight": "pytorch_model-00004-of-00008.bin",
53
+ "model.layers.12.self_attn.k_proj.weight": "pytorch_model-00004-of-00008.bin",
54
+ "model.layers.12.self_attn.o_proj.weight": "pytorch_model-00004-of-00008.bin",
55
+ "model.layers.12.self_attn.q_proj.weight": "pytorch_model-00004-of-00008.bin",
56
+ "model.layers.12.self_attn.rotary_emb.inv_freq": "pytorch_model-00004-of-00008.bin",
57
+ "model.layers.12.self_attn.v_proj.weight": "pytorch_model-00004-of-00008.bin",
58
+ "model.layers.13.input_layernorm.weight": "pytorch_model-00004-of-00008.bin",
59
+ "model.layers.13.mlp.down_proj.weight": "pytorch_model-00004-of-00008.bin",
60
+ "model.layers.13.mlp.gate_proj.weight": "pytorch_model-00004-of-00008.bin",
61
+ "model.layers.13.mlp.up_proj.weight": "pytorch_model-00004-of-00008.bin",
62
+ "model.layers.13.post_attention_layernorm.weight": "pytorch_model-00004-of-00008.bin",
63
+ "model.layers.13.self_attn.k_proj.weight": "pytorch_model-00004-of-00008.bin",
64
+ "model.layers.13.self_attn.o_proj.weight": "pytorch_model-00004-of-00008.bin",
65
+ "model.layers.13.self_attn.q_proj.weight": "pytorch_model-00004-of-00008.bin",
66
+ "model.layers.13.self_attn.rotary_emb.inv_freq": "pytorch_model-00004-of-00008.bin",
67
+ "model.layers.13.self_attn.v_proj.weight": "pytorch_model-00004-of-00008.bin",
68
+ "model.layers.14.input_layernorm.weight": "pytorch_model-00004-of-00008.bin",
69
+ "model.layers.14.mlp.down_proj.weight": "pytorch_model-00004-of-00008.bin",
70
+ "model.layers.14.mlp.gate_proj.weight": "pytorch_model-00004-of-00008.bin",
71
+ "model.layers.14.mlp.up_proj.weight": "pytorch_model-00004-of-00008.bin",
72
+ "model.layers.14.post_attention_layernorm.weight": "pytorch_model-00004-of-00008.bin",
73
+ "model.layers.14.self_attn.k_proj.weight": "pytorch_model-00004-of-00008.bin",
74
+ "model.layers.14.self_attn.o_proj.weight": "pytorch_model-00004-of-00008.bin",
75
+ "model.layers.14.self_attn.q_proj.weight": "pytorch_model-00004-of-00008.bin",
76
+ "model.layers.14.self_attn.rotary_emb.inv_freq": "pytorch_model-00004-of-00008.bin",
77
+ "model.layers.14.self_attn.v_proj.weight": "pytorch_model-00004-of-00008.bin",
78
+ "model.layers.15.input_layernorm.weight": "pytorch_model-00004-of-00008.bin",
79
+ "model.layers.15.mlp.down_proj.weight": "pytorch_model-00004-of-00008.bin",
80
+ "model.layers.15.mlp.gate_proj.weight": "pytorch_model-00004-of-00008.bin",
81
+ "model.layers.15.mlp.up_proj.weight": "pytorch_model-00004-of-00008.bin",
82
+ "model.layers.15.post_attention_layernorm.weight": "pytorch_model-00004-of-00008.bin",
83
+ "model.layers.15.self_attn.k_proj.weight": "pytorch_model-00004-of-00008.bin",
84
+ "model.layers.15.self_attn.o_proj.weight": "pytorch_model-00004-of-00008.bin",
85
+ "model.layers.15.self_attn.q_proj.weight": "pytorch_model-00004-of-00008.bin",
86
+ "model.layers.15.self_attn.rotary_emb.inv_freq": "pytorch_model-00004-of-00008.bin",
87
+ "model.layers.15.self_attn.v_proj.weight": "pytorch_model-00004-of-00008.bin",
88
+ "model.layers.16.input_layernorm.weight": "pytorch_model-00005-of-00008.bin",
89
+ "model.layers.16.mlp.down_proj.weight": "pytorch_model-00005-of-00008.bin",
90
+ "model.layers.16.mlp.gate_proj.weight": "pytorch_model-00005-of-00008.bin",
91
+ "model.layers.16.mlp.up_proj.weight": "pytorch_model-00005-of-00008.bin",
92
+ "model.layers.16.post_attention_layernorm.weight": "pytorch_model-00005-of-00008.bin",
93
+ "model.layers.16.self_attn.k_proj.weight": "pytorch_model-00004-of-00008.bin",
94
+ "model.layers.16.self_attn.o_proj.weight": "pytorch_model-00005-of-00008.bin",
95
+ "model.layers.16.self_attn.q_proj.weight": "pytorch_model-00004-of-00008.bin",
96
+ "model.layers.16.self_attn.rotary_emb.inv_freq": "pytorch_model-00005-of-00008.bin",
97
+ "model.layers.16.self_attn.v_proj.weight": "pytorch_model-00004-of-00008.bin",
98
+ "model.layers.17.input_layernorm.weight": "pytorch_model-00005-of-00008.bin",
99
+ "model.layers.17.mlp.down_proj.weight": "pytorch_model-00005-of-00008.bin",
100
+ "model.layers.17.mlp.gate_proj.weight": "pytorch_model-00005-of-00008.bin",
101
+ "model.layers.17.mlp.up_proj.weight": "pytorch_model-00005-of-00008.bin",
102
+ "model.layers.17.post_attention_layernorm.weight": "pytorch_model-00005-of-00008.bin",
103
+ "model.layers.17.self_attn.k_proj.weight": "pytorch_model-00005-of-00008.bin",
104
+ "model.layers.17.self_attn.o_proj.weight": "pytorch_model-00005-of-00008.bin",
105
+ "model.layers.17.self_attn.q_proj.weight": "pytorch_model-00005-of-00008.bin",
106
+ "model.layers.17.self_attn.rotary_emb.inv_freq": "pytorch_model-00005-of-00008.bin",
107
+ "model.layers.17.self_attn.v_proj.weight": "pytorch_model-00005-of-00008.bin",
108
+ "model.layers.18.input_layernorm.weight": "pytorch_model-00005-of-00008.bin",
109
+ "model.layers.18.mlp.down_proj.weight": "pytorch_model-00005-of-00008.bin",
110
+ "model.layers.18.mlp.gate_proj.weight": "pytorch_model-00005-of-00008.bin",
111
+ "model.layers.18.mlp.up_proj.weight": "pytorch_model-00005-of-00008.bin",
112
+ "model.layers.18.post_attention_layernorm.weight": "pytorch_model-00005-of-00008.bin",
113
+ "model.layers.18.self_attn.k_proj.weight": "pytorch_model-00005-of-00008.bin",
114
+ "model.layers.18.self_attn.o_proj.weight": "pytorch_model-00005-of-00008.bin",
115
+ "model.layers.18.self_attn.q_proj.weight": "pytorch_model-00005-of-00008.bin",
116
+ "model.layers.18.self_attn.rotary_emb.inv_freq": "pytorch_model-00005-of-00008.bin",
117
+ "model.layers.18.self_attn.v_proj.weight": "pytorch_model-00005-of-00008.bin",
118
+ "model.layers.19.input_layernorm.weight": "pytorch_model-00005-of-00008.bin",
119
+ "model.layers.19.mlp.down_proj.weight": "pytorch_model-00005-of-00008.bin",
120
+ "model.layers.19.mlp.gate_proj.weight": "pytorch_model-00005-of-00008.bin",
121
+ "model.layers.19.mlp.up_proj.weight": "pytorch_model-00005-of-00008.bin",
122
+ "model.layers.19.post_attention_layernorm.weight": "pytorch_model-00005-of-00008.bin",
123
+ "model.layers.19.self_attn.k_proj.weight": "pytorch_model-00005-of-00008.bin",
124
+ "model.layers.19.self_attn.o_proj.weight": "pytorch_model-00005-of-00008.bin",
125
+ "model.layers.19.self_attn.q_proj.weight": "pytorch_model-00005-of-00008.bin",
126
+ "model.layers.19.self_attn.rotary_emb.inv_freq": "pytorch_model-00005-of-00008.bin",
127
+ "model.layers.19.self_attn.v_proj.weight": "pytorch_model-00005-of-00008.bin",
128
+ "model.layers.2.input_layernorm.weight": "pytorch_model-00002-of-00008.bin",
129
+ "model.layers.2.mlp.down_proj.weight": "pytorch_model-00002-of-00008.bin",
130
+ "model.layers.2.mlp.gate_proj.weight": "pytorch_model-00002-of-00008.bin",
131
+ "model.layers.2.mlp.up_proj.weight": "pytorch_model-00002-of-00008.bin",
132
+ "model.layers.2.post_attention_layernorm.weight": "pytorch_model-00002-of-00008.bin",
133
+ "model.layers.2.self_attn.k_proj.weight": "pytorch_model-00002-of-00008.bin",
134
+ "model.layers.2.self_attn.o_proj.weight": "pytorch_model-00002-of-00008.bin",
135
+ "model.layers.2.self_attn.q_proj.weight": "pytorch_model-00002-of-00008.bin",
136
+ "model.layers.2.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00008.bin",
137
+ "model.layers.2.self_attn.v_proj.weight": "pytorch_model-00002-of-00008.bin",
138
+ "model.layers.20.input_layernorm.weight": "pytorch_model-00005-of-00008.bin",
139
+ "model.layers.20.mlp.down_proj.weight": "pytorch_model-00005-of-00008.bin",
140
+ "model.layers.20.mlp.gate_proj.weight": "pytorch_model-00005-of-00008.bin",
141
+ "model.layers.20.mlp.up_proj.weight": "pytorch_model-00005-of-00008.bin",
142
+ "model.layers.20.post_attention_layernorm.weight": "pytorch_model-00005-of-00008.bin",
143
+ "model.layers.20.self_attn.k_proj.weight": "pytorch_model-00005-of-00008.bin",
144
+ "model.layers.20.self_attn.o_proj.weight": "pytorch_model-00005-of-00008.bin",
145
+ "model.layers.20.self_attn.q_proj.weight": "pytorch_model-00005-of-00008.bin",
146
+ "model.layers.20.self_attn.rotary_emb.inv_freq": "pytorch_model-00005-of-00008.bin",
147
+ "model.layers.20.self_attn.v_proj.weight": "pytorch_model-00005-of-00008.bin",
148
+ "model.layers.21.input_layernorm.weight": "pytorch_model-00006-of-00008.bin",
149
+ "model.layers.21.mlp.down_proj.weight": "pytorch_model-00006-of-00008.bin",
150
+ "model.layers.21.mlp.gate_proj.weight": "pytorch_model-00006-of-00008.bin",
151
+ "model.layers.21.mlp.up_proj.weight": "pytorch_model-00006-of-00008.bin",
152
+ "model.layers.21.post_attention_layernorm.weight": "pytorch_model-00006-of-00008.bin",
153
+ "model.layers.21.self_attn.k_proj.weight": "pytorch_model-00005-of-00008.bin",
154
+ "model.layers.21.self_attn.o_proj.weight": "pytorch_model-00006-of-00008.bin",
155
+ "model.layers.21.self_attn.q_proj.weight": "pytorch_model-00005-of-00008.bin",
156
+ "model.layers.21.self_attn.rotary_emb.inv_freq": "pytorch_model-00006-of-00008.bin",
157
+ "model.layers.21.self_attn.v_proj.weight": "pytorch_model-00006-of-00008.bin",
158
+ "model.layers.22.input_layernorm.weight": "pytorch_model-00006-of-00008.bin",
159
+ "model.layers.22.mlp.down_proj.weight": "pytorch_model-00006-of-00008.bin",
160
+ "model.layers.22.mlp.gate_proj.weight": "pytorch_model-00006-of-00008.bin",
161
+ "model.layers.22.mlp.up_proj.weight": "pytorch_model-00006-of-00008.bin",
162
+ "model.layers.22.post_attention_layernorm.weight": "pytorch_model-00006-of-00008.bin",
163
+ "model.layers.22.self_attn.k_proj.weight": "pytorch_model-00006-of-00008.bin",
164
+ "model.layers.22.self_attn.o_proj.weight": "pytorch_model-00006-of-00008.bin",
165
+ "model.layers.22.self_attn.q_proj.weight": "pytorch_model-00006-of-00008.bin",
166
+ "model.layers.22.self_attn.rotary_emb.inv_freq": "pytorch_model-00006-of-00008.bin",
167
+ "model.layers.22.self_attn.v_proj.weight": "pytorch_model-00006-of-00008.bin",
168
+ "model.layers.23.input_layernorm.weight": "pytorch_model-00006-of-00008.bin",
169
+ "model.layers.23.mlp.down_proj.weight": "pytorch_model-00006-of-00008.bin",
170
+ "model.layers.23.mlp.gate_proj.weight": "pytorch_model-00006-of-00008.bin",
171
+ "model.layers.23.mlp.up_proj.weight": "pytorch_model-00006-of-00008.bin",
172
+ "model.layers.23.post_attention_layernorm.weight": "pytorch_model-00006-of-00008.bin",
173
+ "model.layers.23.self_attn.k_proj.weight": "pytorch_model-00006-of-00008.bin",
174
+ "model.layers.23.self_attn.o_proj.weight": "pytorch_model-00006-of-00008.bin",
175
+ "model.layers.23.self_attn.q_proj.weight": "pytorch_model-00006-of-00008.bin",
176
+ "model.layers.23.self_attn.rotary_emb.inv_freq": "pytorch_model-00006-of-00008.bin",
177
+ "model.layers.23.self_attn.v_proj.weight": "pytorch_model-00006-of-00008.bin",
178
+ "model.layers.24.input_layernorm.weight": "pytorch_model-00006-of-00008.bin",
179
+ "model.layers.24.mlp.down_proj.weight": "pytorch_model-00006-of-00008.bin",
180
+ "model.layers.24.mlp.gate_proj.weight": "pytorch_model-00006-of-00008.bin",
181
+ "model.layers.24.mlp.up_proj.weight": "pytorch_model-00006-of-00008.bin",
182
+ "model.layers.24.post_attention_layernorm.weight": "pytorch_model-00006-of-00008.bin",
183
+ "model.layers.24.self_attn.k_proj.weight": "pytorch_model-00006-of-00008.bin",
184
+ "model.layers.24.self_attn.o_proj.weight": "pytorch_model-00006-of-00008.bin",
185
+ "model.layers.24.self_attn.q_proj.weight": "pytorch_model-00006-of-00008.bin",
186
+ "model.layers.24.self_attn.rotary_emb.inv_freq": "pytorch_model-00006-of-00008.bin",
187
+ "model.layers.24.self_attn.v_proj.weight": "pytorch_model-00006-of-00008.bin",
188
+ "model.layers.25.input_layernorm.weight": "pytorch_model-00006-of-00008.bin",
189
+ "model.layers.25.mlp.down_proj.weight": "pytorch_model-00006-of-00008.bin",
190
+ "model.layers.25.mlp.gate_proj.weight": "pytorch_model-00006-of-00008.bin",
191
+ "model.layers.25.mlp.up_proj.weight": "pytorch_model-00006-of-00008.bin",
192
+ "model.layers.25.post_attention_layernorm.weight": "pytorch_model-00006-of-00008.bin",
193
+ "model.layers.25.self_attn.k_proj.weight": "pytorch_model-00006-of-00008.bin",
194
+ "model.layers.25.self_attn.o_proj.weight": "pytorch_model-00006-of-00008.bin",
195
+ "model.layers.25.self_attn.q_proj.weight": "pytorch_model-00006-of-00008.bin",
196
+ "model.layers.25.self_attn.rotary_emb.inv_freq": "pytorch_model-00006-of-00008.bin",
197
+ "model.layers.25.self_attn.v_proj.weight": "pytorch_model-00006-of-00008.bin",
198
+ "model.layers.26.input_layernorm.weight": "pytorch_model-00007-of-00008.bin",
199
+ "model.layers.26.mlp.down_proj.weight": "pytorch_model-00007-of-00008.bin",
200
+ "model.layers.26.mlp.gate_proj.weight": "pytorch_model-00007-of-00008.bin",
201
+ "model.layers.26.mlp.up_proj.weight": "pytorch_model-00007-of-00008.bin",
202
+ "model.layers.26.post_attention_layernorm.weight": "pytorch_model-00007-of-00008.bin",
203
+ "model.layers.26.self_attn.k_proj.weight": "pytorch_model-00007-of-00008.bin",
204
+ "model.layers.26.self_attn.o_proj.weight": "pytorch_model-00007-of-00008.bin",
205
+ "model.layers.26.self_attn.q_proj.weight": "pytorch_model-00006-of-00008.bin",
206
+ "model.layers.26.self_attn.rotary_emb.inv_freq": "pytorch_model-00007-of-00008.bin",
207
+ "model.layers.26.self_attn.v_proj.weight": "pytorch_model-00007-of-00008.bin",
208
+ "model.layers.27.input_layernorm.weight": "pytorch_model-00007-of-00008.bin",
209
+ "model.layers.27.mlp.down_proj.weight": "pytorch_model-00007-of-00008.bin",
210
+ "model.layers.27.mlp.gate_proj.weight": "pytorch_model-00007-of-00008.bin",
211
+ "model.layers.27.mlp.up_proj.weight": "pytorch_model-00007-of-00008.bin",
212
+ "model.layers.27.post_attention_layernorm.weight": "pytorch_model-00007-of-00008.bin",
213
+ "model.layers.27.self_attn.k_proj.weight": "pytorch_model-00007-of-00008.bin",
214
+ "model.layers.27.self_attn.o_proj.weight": "pytorch_model-00007-of-00008.bin",
215
+ "model.layers.27.self_attn.q_proj.weight": "pytorch_model-00007-of-00008.bin",
216
+ "model.layers.27.self_attn.rotary_emb.inv_freq": "pytorch_model-00007-of-00008.bin",
217
+ "model.layers.27.self_attn.v_proj.weight": "pytorch_model-00007-of-00008.bin",
218
+ "model.layers.28.input_layernorm.weight": "pytorch_model-00007-of-00008.bin",
219
+ "model.layers.28.mlp.down_proj.weight": "pytorch_model-00007-of-00008.bin",
220
+ "model.layers.28.mlp.gate_proj.weight": "pytorch_model-00007-of-00008.bin",
221
+ "model.layers.28.mlp.up_proj.weight": "pytorch_model-00007-of-00008.bin",
222
+ "model.layers.28.post_attention_layernorm.weight": "pytorch_model-00007-of-00008.bin",
223
+ "model.layers.28.self_attn.k_proj.weight": "pytorch_model-00007-of-00008.bin",
224
+ "model.layers.28.self_attn.o_proj.weight": "pytorch_model-00007-of-00008.bin",
225
+ "model.layers.28.self_attn.q_proj.weight": "pytorch_model-00007-of-00008.bin",
226
+ "model.layers.28.self_attn.rotary_emb.inv_freq": "pytorch_model-00007-of-00008.bin",
227
+ "model.layers.28.self_attn.v_proj.weight": "pytorch_model-00007-of-00008.bin",
228
+ "model.layers.29.input_layernorm.weight": "pytorch_model-00007-of-00008.bin",
229
+ "model.layers.29.mlp.down_proj.weight": "pytorch_model-00007-of-00008.bin",
230
+ "model.layers.29.mlp.gate_proj.weight": "pytorch_model-00007-of-00008.bin",
231
+ "model.layers.29.mlp.up_proj.weight": "pytorch_model-00007-of-00008.bin",
232
+ "model.layers.29.post_attention_layernorm.weight": "pytorch_model-00007-of-00008.bin",
233
+ "model.layers.29.self_attn.k_proj.weight": "pytorch_model-00007-of-00008.bin",
234
+ "model.layers.29.self_attn.o_proj.weight": "pytorch_model-00007-of-00008.bin",
235
+ "model.layers.29.self_attn.q_proj.weight": "pytorch_model-00007-of-00008.bin",
236
+ "model.layers.29.self_attn.rotary_emb.inv_freq": "pytorch_model-00007-of-00008.bin",
237
+ "model.layers.29.self_attn.v_proj.weight": "pytorch_model-00007-of-00008.bin",
238
+ "model.layers.3.input_layernorm.weight": "pytorch_model-00002-of-00008.bin",
239
+ "model.layers.3.mlp.down_proj.weight": "pytorch_model-00002-of-00008.bin",
240
+ "model.layers.3.mlp.gate_proj.weight": "pytorch_model-00002-of-00008.bin",
241
+ "model.layers.3.mlp.up_proj.weight": "pytorch_model-00002-of-00008.bin",
242
+ "model.layers.3.post_attention_layernorm.weight": "pytorch_model-00002-of-00008.bin",
243
+ "model.layers.3.self_attn.k_proj.weight": "pytorch_model-00002-of-00008.bin",
244
+ "model.layers.3.self_attn.o_proj.weight": "pytorch_model-00002-of-00008.bin",
245
+ "model.layers.3.self_attn.q_proj.weight": "pytorch_model-00002-of-00008.bin",
246
+ "model.layers.3.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00008.bin",
247
+ "model.layers.3.self_attn.v_proj.weight": "pytorch_model-00002-of-00008.bin",
248
+ "model.layers.30.input_layernorm.weight": "pytorch_model-00007-of-00008.bin",
249
+ "model.layers.30.mlp.down_proj.weight": "pytorch_model-00007-of-00008.bin",
250
+ "model.layers.30.mlp.gate_proj.weight": "pytorch_model-00007-of-00008.bin",
251
+ "model.layers.30.mlp.up_proj.weight": "pytorch_model-00007-of-00008.bin",
252
+ "model.layers.30.post_attention_layernorm.weight": "pytorch_model-00007-of-00008.bin",
253
+ "model.layers.30.self_attn.k_proj.weight": "pytorch_model-00007-of-00008.bin",
254
+ "model.layers.30.self_attn.o_proj.weight": "pytorch_model-00007-of-00008.bin",
255
+ "model.layers.30.self_attn.q_proj.weight": "pytorch_model-00007-of-00008.bin",
256
+ "model.layers.30.self_attn.rotary_emb.inv_freq": "pytorch_model-00007-of-00008.bin",
257
+ "model.layers.30.self_attn.v_proj.weight": "pytorch_model-00007-of-00008.bin",
258
+ "model.layers.31.input_layernorm.weight": "pytorch_model-00008-of-00008.bin",
259
+ "model.layers.31.mlp.down_proj.weight": "pytorch_model-00008-of-00008.bin",
260
+ "model.layers.31.mlp.gate_proj.weight": "pytorch_model-00008-of-00008.bin",
261
+ "model.layers.31.mlp.up_proj.weight": "pytorch_model-00008-of-00008.bin",
262
+ "model.layers.31.post_attention_layernorm.weight": "pytorch_model-00008-of-00008.bin",
263
+ "model.layers.31.self_attn.k_proj.weight": "pytorch_model-00008-of-00008.bin",
264
+ "model.layers.31.self_attn.o_proj.weight": "pytorch_model-00008-of-00008.bin",
265
+ "model.layers.31.self_attn.q_proj.weight": "pytorch_model-00008-of-00008.bin",
266
+ "model.layers.31.self_attn.rotary_emb.inv_freq": "pytorch_model-00008-of-00008.bin",
267
+ "model.layers.31.self_attn.v_proj.weight": "pytorch_model-00008-of-00008.bin",
268
+ "model.layers.4.input_layernorm.weight": "pytorch_model-00002-of-00008.bin",
269
+ "model.layers.4.mlp.down_proj.weight": "pytorch_model-00002-of-00008.bin",
270
+ "model.layers.4.mlp.gate_proj.weight": "pytorch_model-00002-of-00008.bin",
271
+ "model.layers.4.mlp.up_proj.weight": "pytorch_model-00002-of-00008.bin",
272
+ "model.layers.4.post_attention_layernorm.weight": "pytorch_model-00002-of-00008.bin",
273
+ "model.layers.4.self_attn.k_proj.weight": "pytorch_model-00002-of-00008.bin",
274
+ "model.layers.4.self_attn.o_proj.weight": "pytorch_model-00002-of-00008.bin",
275
+ "model.layers.4.self_attn.q_proj.weight": "pytorch_model-00002-of-00008.bin",
276
+ "model.layers.4.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00008.bin",
277
+ "model.layers.4.self_attn.v_proj.weight": "pytorch_model-00002-of-00008.bin",
278
+ "model.layers.5.input_layernorm.weight": "pytorch_model-00002-of-00008.bin",
279
+ "model.layers.5.mlp.down_proj.weight": "pytorch_model-00002-of-00008.bin",
280
+ "model.layers.5.mlp.gate_proj.weight": "pytorch_model-00002-of-00008.bin",
281
+ "model.layers.5.mlp.up_proj.weight": "pytorch_model-00002-of-00008.bin",
282
+ "model.layers.5.post_attention_layernorm.weight": "pytorch_model-00002-of-00008.bin",
283
+ "model.layers.5.self_attn.k_proj.weight": "pytorch_model-00002-of-00008.bin",
284
+ "model.layers.5.self_attn.o_proj.weight": "pytorch_model-00002-of-00008.bin",
285
+ "model.layers.5.self_attn.q_proj.weight": "pytorch_model-00002-of-00008.bin",
286
+ "model.layers.5.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00008.bin",
287
+ "model.layers.5.self_attn.v_proj.weight": "pytorch_model-00002-of-00008.bin",
288
+ "model.layers.6.input_layernorm.weight": "pytorch_model-00003-of-00008.bin",
289
+ "model.layers.6.mlp.down_proj.weight": "pytorch_model-00003-of-00008.bin",
290
+ "model.layers.6.mlp.gate_proj.weight": "pytorch_model-00002-of-00008.bin",
291
+ "model.layers.6.mlp.up_proj.weight": "pytorch_model-00003-of-00008.bin",
292
+ "model.layers.6.post_attention_layernorm.weight": "pytorch_model-00003-of-00008.bin",
293
+ "model.layers.6.self_attn.k_proj.weight": "pytorch_model-00002-of-00008.bin",
294
+ "model.layers.6.self_attn.o_proj.weight": "pytorch_model-00002-of-00008.bin",
295
+ "model.layers.6.self_attn.q_proj.weight": "pytorch_model-00002-of-00008.bin",
296
+ "model.layers.6.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00008.bin",
297
+ "model.layers.6.self_attn.v_proj.weight": "pytorch_model-00002-of-00008.bin",
298
+ "model.layers.7.input_layernorm.weight": "pytorch_model-00003-of-00008.bin",
299
+ "model.layers.7.mlp.down_proj.weight": "pytorch_model-00003-of-00008.bin",
300
+ "model.layers.7.mlp.gate_proj.weight": "pytorch_model-00003-of-00008.bin",
301
+ "model.layers.7.mlp.up_proj.weight": "pytorch_model-00003-of-00008.bin",
302
+ "model.layers.7.post_attention_layernorm.weight": "pytorch_model-00003-of-00008.bin",
303
+ "model.layers.7.self_attn.k_proj.weight": "pytorch_model-00003-of-00008.bin",
304
+ "model.layers.7.self_attn.o_proj.weight": "pytorch_model-00003-of-00008.bin",
305
+ "model.layers.7.self_attn.q_proj.weight": "pytorch_model-00003-of-00008.bin",
306
+ "model.layers.7.self_attn.rotary_emb.inv_freq": "pytorch_model-00003-of-00008.bin",
307
+ "model.layers.7.self_attn.v_proj.weight": "pytorch_model-00003-of-00008.bin",
308
+ "model.layers.8.input_layernorm.weight": "pytorch_model-00003-of-00008.bin",
309
+ "model.layers.8.mlp.down_proj.weight": "pytorch_model-00003-of-00008.bin",
310
+ "model.layers.8.mlp.gate_proj.weight": "pytorch_model-00003-of-00008.bin",
311
+ "model.layers.8.mlp.up_proj.weight": "pytorch_model-00003-of-00008.bin",
312
+ "model.layers.8.post_attention_layernorm.weight": "pytorch_model-00003-of-00008.bin",
313
+ "model.layers.8.self_attn.k_proj.weight": "pytorch_model-00003-of-00008.bin",
314
+ "model.layers.8.self_attn.o_proj.weight": "pytorch_model-00003-of-00008.bin",
315
+ "model.layers.8.self_attn.q_proj.weight": "pytorch_model-00003-of-00008.bin",
316
+ "model.layers.8.self_attn.rotary_emb.inv_freq": "pytorch_model-00003-of-00008.bin",
317
+ "model.layers.8.self_attn.v_proj.weight": "pytorch_model-00003-of-00008.bin",
318
+ "model.layers.9.input_layernorm.weight": "pytorch_model-00003-of-00008.bin",
319
+ "model.layers.9.mlp.down_proj.weight": "pytorch_model-00003-of-00008.bin",
320
+ "model.layers.9.mlp.gate_proj.weight": "pytorch_model-00003-of-00008.bin",
321
+ "model.layers.9.mlp.up_proj.weight": "pytorch_model-00003-of-00008.bin",
322
+ "model.layers.9.post_attention_layernorm.weight": "pytorch_model-00003-of-00008.bin",
323
+ "model.layers.9.self_attn.k_proj.weight": "pytorch_model-00003-of-00008.bin",
324
+ "model.layers.9.self_attn.o_proj.weight": "pytorch_model-00003-of-00008.bin",
325
+ "model.layers.9.self_attn.q_proj.weight": "pytorch_model-00003-of-00008.bin",
326
+ "model.layers.9.self_attn.rotary_emb.inv_freq": "pytorch_model-00003-of-00008.bin",
327
+ "model.layers.9.self_attn.v_proj.weight": "pytorch_model-00003-of-00008.bin",
328
+ "model.norm.weight": "pytorch_model-00008-of-00008.bin"
329
+ }
330
+ }
qwen.tiktoken ADDED
The diff for this file is too large to render. See raw diff
 
special_tokens_map.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<|endoftext|>",
3
+ "eos_token": "<|endoftext|>",
4
+ "unk_token": "<|endoftext|>"
5
+ }
tokenization_qwen.py ADDED
@@ -0,0 +1,566 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Alibaba Cloud.
2
+ #
3
+ # This source code is licensed under the license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ """Tokenization classes for QWen."""
7
+
8
+ import base64
9
+ import logging
10
+ import os
11
+ import requests
12
+ import unicodedata
13
+ from typing import Collection, Dict, List, Set, Tuple, Union, Any, Callable, Optional
14
+
15
+ import tiktoken
16
+ import numpy as np
17
+ from PIL import Image
18
+ from PIL import ImageFont
19
+ from PIL import ImageDraw
20
+ from transformers import PreTrainedTokenizer, AddedToken
21
+ from transformers.utils import try_to_load_from_cache
22
+
23
+ import matplotlib.pyplot as plt
24
+ import matplotlib.colors as mcolors
25
+ from matplotlib.font_manager import FontProperties
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+
30
+ VOCAB_FILES_NAMES = {"vocab_file": "qwen.tiktoken", "ttf": "SimSun.ttf"}
31
+
32
+ PAT_STR = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
33
+ ENDOFTEXT = "<|endoftext|>"
34
+ IMSTART = "<|im_start|>"
35
+ IMEND = "<|im_end|>"
36
+ # as the default behavior is changed to allow special tokens in
37
+ # regular texts, the surface forms of special tokens need to be
38
+ # as different as possible to minimize the impact
39
+ EXTRAS = tuple((f"<|extra_{i}|>" for i in range(205)))
40
+ SPECIAL_TOKENS = (
41
+ ENDOFTEXT,
42
+ IMSTART,
43
+ IMEND,
44
+ ) + EXTRAS
45
+ IMG_TOKEN_SPAN = 256
46
+
47
+
48
+ def _load_tiktoken_bpe(tiktoken_bpe_file: str) -> Dict[bytes, int]:
49
+ with open(tiktoken_bpe_file, "rb") as f:
50
+ contents = f.read()
51
+ return {
52
+ base64.b64decode(token): int(rank)
53
+ for token, rank in (line.split() for line in contents.splitlines() if line)
54
+ }
55
+
56
+ def _list_find(
57
+ input_list: List[Any],
58
+ candidates: Tuple[Any],
59
+ start: int = 0,
60
+ ):
61
+ for i in range(start, len(input_list)):
62
+ if input_list[i] in candidates:
63
+ return i
64
+ return -1
65
+
66
+ def _replace_closed_tag(
67
+ input_tokens: List[Any],
68
+ start_tags: Union[Any, Tuple[Any]],
69
+ end_tags: Union[Any, Tuple[Any]],
70
+ inclusive_replace_func: Callable,
71
+ exclusive_replace_func: Callable = lambda x: x,
72
+ ):
73
+ if isinstance(start_tags, (str, int)):
74
+ start_tags = (start_tags,)
75
+ if isinstance(end_tags, (str, int)):
76
+ end_tags = (end_tags,)
77
+ assert len(start_tags) == len(end_tags)
78
+
79
+ output_tokens = []
80
+ end = 0
81
+ while True:
82
+ start = _list_find(input_tokens, start_tags, end)
83
+ if start == -1:
84
+ break
85
+ output_tokens.extend(exclusive_replace_func(input_tokens[end : start]))
86
+ tag_idx = start_tags.index(input_tokens[start])
87
+ end = _list_find(input_tokens, (end_tags[tag_idx],), start)
88
+ if end == -1:
89
+ raise ValueError("Unclosed image token")
90
+ output_tokens.extend(inclusive_replace_func(input_tokens[start : end + 1]))
91
+ end += 1
92
+ output_tokens.extend(exclusive_replace_func(input_tokens[end : ]))
93
+ return output_tokens
94
+
95
+ class QWenTokenizer(PreTrainedTokenizer):
96
+ """QWen tokenizer."""
97
+
98
+ vocab_files_names = VOCAB_FILES_NAMES
99
+
100
+ def __init__(
101
+ self,
102
+ vocab_file,
103
+ errors="replace",
104
+ image_start_tag='<img>',
105
+ image_end_tag='</img>',
106
+ image_pad_tag='<imgpad>',
107
+ ref_start_tag='<ref>',
108
+ ref_end_tag='</ref>',
109
+ box_start_tag='<box>',
110
+ box_end_tag='</box>',
111
+ quad_start_tag='<quad>',
112
+ quad_end_tag='</quad>',
113
+ **kwargs,
114
+ ):
115
+ super().__init__(**kwargs)
116
+ self.image_start_tag = image_start_tag
117
+ self.image_end_tag = image_end_tag
118
+ self.image_pad_tag = image_pad_tag
119
+ self.ref_start_tag = ref_start_tag
120
+ self.ref_end_tag = ref_end_tag
121
+ self.box_start_tag = box_start_tag
122
+ self.box_end_tag = box_end_tag
123
+ self.quad_start_tag = quad_start_tag
124
+ self.quad_end_tag = quad_end_tag
125
+ self.IMAGE_ST = (
126
+ ref_start_tag, ref_end_tag,
127
+ box_start_tag, box_end_tag,
128
+ quad_start_tag, quad_end_tag,
129
+ image_start_tag, image_end_tag,
130
+ image_pad_tag
131
+ )
132
+
133
+ self.errors = errors # how to handle errors in decoding
134
+
135
+ self.mergeable_ranks = _load_tiktoken_bpe(vocab_file) # type: dict[bytes, int]
136
+ self.special_tokens = {
137
+ token: index
138
+ for index, token in enumerate(
139
+ SPECIAL_TOKENS + self.IMAGE_ST, start=len(self.mergeable_ranks)
140
+ )
141
+ }
142
+ self.img_start_id = self.special_tokens[self.image_start_tag]
143
+ self.img_end_id = self.special_tokens[self.image_end_tag]
144
+ self.img_pad_id = self.special_tokens[self.image_pad_tag]
145
+ self.ref_start_id = self.special_tokens[self.ref_start_tag]
146
+ self.ref_end_id = self.special_tokens[self.ref_end_tag]
147
+ self.box_start_id = self.special_tokens[self.box_start_tag]
148
+ self.box_end_id = self.special_tokens[self.box_end_tag]
149
+ self.quad_start_id = self.special_tokens[self.quad_start_tag]
150
+ self.quad_end_id = self.special_tokens[self.quad_end_tag]
151
+
152
+ enc = tiktoken.Encoding(
153
+ "Qwen",
154
+ pat_str=PAT_STR,
155
+ mergeable_ranks=self.mergeable_ranks,
156
+ special_tokens=self.special_tokens,
157
+ )
158
+ assert (
159
+ len(self.mergeable_ranks) + len(self.special_tokens) == enc.n_vocab
160
+ ), f"{len(self.mergeable_ranks) + len(self.special_tokens)} != {enc.n_vocab} in encoding"
161
+
162
+ self.decoder = {
163
+ v: k for k, v in self.mergeable_ranks.items()
164
+ } # type: dict[int, bytes|str]
165
+ self.decoder.update({v: k for k, v in self.special_tokens.items()})
166
+
167
+ self.tokenizer = enc # type: tiktoken.Encoding
168
+
169
+ self.eod_id = self.tokenizer.eot_token
170
+ self.im_start_id = self.special_tokens[IMSTART]
171
+ self.im_end_id = self.special_tokens[IMEND]
172
+
173
+ def __len__(self) -> int:
174
+ return self.tokenizer.n_vocab
175
+
176
+ def get_vocab(self) -> Dict[bytes, int]:
177
+ return self.mergeable_ranks
178
+
179
+ def convert_tokens_to_ids(
180
+ self, tokens: Union[bytes, str, List[Union[bytes, str]]]
181
+ ) -> List[int]:
182
+ ids = []
183
+ if isinstance(tokens, (str, bytes)):
184
+ if tokens in self.special_tokens:
185
+ return self.special_tokens[tokens]
186
+ else:
187
+ return self.mergeable_ranks.get(tokens)
188
+ for token in tokens:
189
+ if token in self.special_tokens:
190
+ ids.append(self.special_tokens[token])
191
+ else:
192
+ ids.append(self.mergeable_ranks.get(token))
193
+ return ids
194
+
195
+ def _add_tokens(self, new_tokens: Union[List[str], List[AddedToken]], special_tokens: bool = False) -> int:
196
+ if not special_tokens and new_tokens:
197
+ raise ValueError('Adding regular tokens is not supported')
198
+ for token in new_tokens:
199
+ surface_form = token.content if isinstance(token, AddedToken) else token
200
+ if surface_form not in SPECIAL_TOKENS + self.IMAGE_ST:
201
+ raise ValueError('Adding unknown special tokens is not supported')
202
+ return 0
203
+
204
+ def save_vocabulary(self, save_directory: str, **kwargs) -> Tuple[str]:
205
+ """
206
+ Save only the vocabulary of the tokenizer (vocabulary).
207
+
208
+ Returns:
209
+ `Tuple(str)`: Paths to the files saved.
210
+ """
211
+ file_path = os.path.join(save_directory, "qwen.tiktoken")
212
+ with open(file_path, "w", encoding="utf8") as w:
213
+ for k, v in self.mergeable_ranks.items():
214
+ line = base64.b64encode(k).decode("utf8") + " " + str(v) + "\n"
215
+ w.write(line)
216
+ return (file_path,)
217
+
218
+ def tokenize(
219
+ self,
220
+ text: str,
221
+ allowed_special: Union[Set, str] = "all",
222
+ disallowed_special: Union[Collection, str] = (),
223
+ **kwargs,
224
+ ) -> List[Union[bytes, str]]:
225
+ """
226
+ Converts a string in a sequence of tokens.
227
+
228
+ Args:
229
+ text (`str`):
230
+ The sequence to be encoded.
231
+ allowed_special (`Literal["all"]` or `set`):
232
+ The surface forms of the tokens to be encoded as special tokens in regular texts.
233
+ Default to "all".
234
+ disallowed_special (`Literal["all"]` or `Collection`):
235
+ The surface forms of the tokens that should not be in regular texts and trigger errors.
236
+ Default to an empty tuple.
237
+
238
+ kwargs (additional keyword arguments, *optional*):
239
+ Will be passed to the underlying model specific encode method.
240
+
241
+ Returns:
242
+ `List[bytes|str]`: The list of tokens.
243
+ """
244
+ tokens = []
245
+ text = unicodedata.normalize("NFC", text)
246
+
247
+ # this implementation takes a detour: text -> token id -> token surface forms
248
+ for t in self.tokenizer.encode(
249
+ text, allowed_special=allowed_special, disallowed_special=disallowed_special
250
+ ):
251
+ tokens.append(self.decoder[t])
252
+
253
+ def _encode_imgurl(img_tokens):
254
+ assert img_tokens[0] == self.image_start_tag and img_tokens[-1] == self.image_end_tag
255
+ img_tokens = img_tokens[1:-1]
256
+ img_url = b''.join(img_tokens)
257
+ out_img_tokens = list(map(self.decoder.get, img_url))
258
+ if len(out_img_tokens) > IMG_TOKEN_SPAN:
259
+ raise ValueError("The content in {}..{} is too long".format(
260
+ self.image_start_tag, self.image_end_tag))
261
+ out_img_tokens.extend([self.image_pad_tag] * (IMG_TOKEN_SPAN - len(out_img_tokens)))
262
+ out_img_tokens = [self.image_start_tag] + out_img_tokens + [self.image_end_tag]
263
+ return out_img_tokens
264
+
265
+ return _replace_closed_tag(tokens, self.image_start_tag, self.image_end_tag, _encode_imgurl)
266
+
267
+ def convert_tokens_to_string(self, tokens: List[Union[bytes, str]]) -> str:
268
+ """
269
+ Converts a sequence of tokens in a single string.
270
+ """
271
+ text = ""
272
+ temp = b""
273
+ for t in tokens:
274
+ if isinstance(t, str):
275
+ if temp:
276
+ text += temp.decode("utf-8", errors=self.errors)
277
+ temp = b""
278
+ text += t
279
+ elif isinstance(t, bytes):
280
+ temp += t
281
+ else:
282
+ raise TypeError("token should only be of type types or str")
283
+ if temp:
284
+ text += temp.decode("utf-8", errors=self.errors)
285
+ return text
286
+
287
+ @property
288
+ def vocab_size(self):
289
+ return self.tokenizer.n_vocab
290
+
291
+ def _convert_id_to_token(self, index: int) -> Union[bytes, str]:
292
+ """Converts an id to a token, special tokens included"""
293
+ if index in self.decoder:
294
+ return self.decoder[index]
295
+ raise ValueError("unknown ids")
296
+
297
+ def _convert_token_to_id(self, token: Union[bytes, str]) -> int:
298
+ """Converts a token to an id using the vocab, special tokens included"""
299
+ if token in self.special_tokens:
300
+ return self.special_tokens[token]
301
+ if token in self.mergeable_ranks:
302
+ return self.mergeable_ranks[token]
303
+ raise ValueError("unknown token")
304
+
305
+ def _tokenize(self, text: str, **kwargs):
306
+ """
307
+ Converts a string in a sequence of tokens (string), using the tokenizer. Split in words for word-based
308
+ vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces).
309
+
310
+ Do NOT take care of added tokens.
311
+ """
312
+ raise NotImplementedError
313
+
314
+ def _decode(
315
+ self,
316
+ token_ids: Union[int, List[int]],
317
+ skip_special_tokens: bool = False,
318
+ errors: str = None,
319
+ **kwargs,
320
+ ) -> str:
321
+ if isinstance(token_ids, int):
322
+ token_ids = [token_ids]
323
+
324
+ def _decode_imgurl(img_token_ids):
325
+ assert img_token_ids[0] == self.img_start_id and img_token_ids[-1] == self.img_end_id
326
+ img_token_ids = img_token_ids[1:-1]
327
+ img_token_ids = img_token_ids[ : img_token_ids.index(self.img_pad_id)]
328
+ img_url = bytes(img_token_ids).decode('utf-8')
329
+ return [self.img_start_id] + self.tokenizer.encode(img_url) + [self.img_end_id]
330
+
331
+ token_ids = _replace_closed_tag(token_ids, self.img_start_id, self.img_end_id, _decode_imgurl)
332
+
333
+ if skip_special_tokens:
334
+ token_ids = [i for i in token_ids if i < self.eod_id]
335
+ return self.tokenizer.decode(token_ids, errors=errors or self.errors)
336
+
337
+ def to_list_format(self, text: str):
338
+ text = unicodedata.normalize("NFC", text)
339
+ token_ids = self.tokenizer.encode(
340
+ text, allowed_special=set(self.IMAGE_ST + (ENDOFTEXT,)))
341
+
342
+ def _encode_vl_info(tokens):
343
+ if len(tokens) == 0:
344
+ return []
345
+ if tokens[0] == self.img_start_id and tokens[-1] == self.img_end_id:
346
+ key = 'image'
347
+ elif tokens[0] == self.ref_start_id and tokens[-1] == self.ref_end_id:
348
+ key = 'ref'
349
+ elif tokens[0] == self.box_start_id and tokens[-1] == self.box_end_id:
350
+ key = 'box'
351
+ elif tokens[0] == self.quad_start_id and tokens[-1] == self.quad_end_id:
352
+ key = 'quad'
353
+ else:
354
+ _tobytes = lambda x: x.encode('utf-8') if isinstance(x, str) else x
355
+ return [{'text': b''.join(map(_tobytes, map(self.decoder.get, tokens))).decode('utf-8')}]
356
+ val = b''.join(map(self.decoder.get, tokens[1:-1])).decode('utf-8')
357
+ return [{key: val}]
358
+
359
+ return _replace_closed_tag(
360
+ token_ids,
361
+ (self.img_start_id, self.ref_start_id, self.box_start_id, self.quad_start_id),
362
+ (self.img_end_id, self.ref_end_id, self.box_end_id, self.quad_end_id),
363
+ _encode_vl_info,
364
+ _encode_vl_info,
365
+ )
366
+
367
+ def from_list_format(self, list_format: List[Dict]):
368
+ text = ''
369
+ num_images = 0
370
+ for ele in list_format:
371
+ if 'image' in ele:
372
+ num_images += 1
373
+ text += f'Picture {num_images}:'
374
+ text += self.image_start_tag + ele['image'] + self.image_end_tag
375
+ text += '\n'
376
+ elif 'text' in ele:
377
+ text += ele['text']
378
+ elif 'box' in ele:
379
+ if 'ref' in ele:
380
+ text += self.ref_start_tag + ele['ref'] + self.ref_end_tag
381
+ for box in ele['box']:
382
+ text += self.box_start_tag + '(%d,%d),(%d,%d)' % (box[0], box[1], box[2], box[3]) + self.box_end_tag
383
+ else:
384
+ raise ValueError("Unsupport element: " + str(ele))
385
+ return text
386
+
387
+ def _fetch_latest_picture(self, response, history):
388
+ if history is None:
389
+ history = []
390
+ _history = history + [(response, None)]
391
+ for q, r in _history[::-1]:
392
+ for ele in self.to_list_format(q)[::-1]:
393
+ if 'image' in ele:
394
+ return ele['image']
395
+ return None
396
+
397
+ def _fetch_all_box_with_ref(self, text):
398
+ list_format = self.to_list_format(text)
399
+ output = []
400
+ for i, ele in enumerate(list_format):
401
+ if 'box' in ele:
402
+ bbox = tuple(map(int, ele['box'].replace('(', '').replace(')', '').split(',')))
403
+ assert len(bbox) == 4
404
+ output.append({'box': bbox})
405
+ if i > 0 and 'ref' in list_format[i-1]:
406
+ output[-1]['ref'] = list_format[i-1]['ref'].strip()
407
+ return output
408
+
409
+ def draw_bbox_on_latest_picture(
410
+ self,
411
+ response,
412
+ history=None,
413
+ ) -> Optional[Image.Image]:
414
+ image = self._fetch_latest_picture(response, history)
415
+ if image is None:
416
+ return None
417
+ if image.startswith("http://") or image.startswith("https://"):
418
+ image = Image.open(requests.get(image, stream=True).raw).convert("RGB")
419
+ h, w = image.height, image.width
420
+ else:
421
+ image = plt.imread(image)
422
+ h, w = image.shape[0], image.shape[1]
423
+ visualizer = Visualizer(image)
424
+
425
+ boxes = self._fetch_all_box_with_ref(response)
426
+ if not boxes:
427
+ return None
428
+ color = random.choice([_ for _ in mcolors.TABLEAU_COLORS.keys()]) # init color
429
+ for box in boxes:
430
+ if 'ref' in box: # random new color for new refexps
431
+ color = random.choice([_ for _ in mcolors.TABLEAU_COLORS.keys()])
432
+ x1, y1, x2, y2 = box['box']
433
+ x1, y1, x2, y2 = (int(x1 / 1000 * w), int(y1 / 1000 * h), int(x2 / 1000 * w), int(y2 / 1000 * h))
434
+ visualizer.draw_box((x1, y1, x2, y2), alpha=1, edge_color=color)
435
+ if 'ref' in box:
436
+ visualizer.draw_text(box['ref'], (x1, y1), color=color, horizontal_alignment="left")
437
+ return visualizer.output
438
+
439
+
440
+ import colorsys
441
+ import logging
442
+ import math
443
+ import numpy as np
444
+ import matplotlib as mpl
445
+ import matplotlib.colors as mplc
446
+ import matplotlib.figure as mplfigure
447
+ import torch
448
+ from matplotlib.backends.backend_agg import FigureCanvasAgg
449
+ from PIL import Image
450
+ import random
451
+
452
+ logger = logging.getLogger(__name__)
453
+
454
+
455
+ class VisImage:
456
+ def __init__(self, img, scale=1.0):
457
+ self.img = img
458
+ self.scale = scale
459
+ self.width, self.height = img.shape[1], img.shape[0]
460
+ self._setup_figure(img)
461
+
462
+ def _setup_figure(self, img):
463
+ fig = mplfigure.Figure(frameon=False)
464
+ self.dpi = fig.get_dpi()
465
+ # add a small 1e-2 to avoid precision lost due to matplotlib's truncation
466
+ # (https://github.com/matplotlib/matplotlib/issues/15363)
467
+ fig.set_size_inches(
468
+ (self.width * self.scale + 1e-2) / self.dpi,
469
+ (self.height * self.scale + 1e-2) / self.dpi,
470
+ )
471
+ self.canvas = FigureCanvasAgg(fig)
472
+ # self.canvas = mpl.backends.backend_cairo.FigureCanvasCairo(fig)
473
+ ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
474
+ ax.axis("off")
475
+ self.fig = fig
476
+ self.ax = ax
477
+ self.reset_image(img)
478
+
479
+ def reset_image(self, img):
480
+ img = img.astype("uint8")
481
+ self.ax.imshow(img, extent=(0, self.width, self.height, 0), interpolation="nearest")
482
+
483
+ def save(self, filepath):
484
+ self.fig.savefig(filepath)
485
+
486
+ def get_image(self):
487
+ canvas = self.canvas
488
+ s, (width, height) = canvas.print_to_buffer()
489
+
490
+ buffer = np.frombuffer(s, dtype="uint8")
491
+
492
+ img_rgba = buffer.reshape(height, width, 4)
493
+ rgb, alpha = np.split(img_rgba, [3], axis=2)
494
+ return rgb.astype("uint8")
495
+
496
+
497
+ class Visualizer:
498
+ def __init__(self, img_rgb, metadata=None, scale=1.0):
499
+ self.img = np.asarray(img_rgb).clip(0, 255).astype(np.uint8)
500
+ self.font_path = try_to_load_from_cache("Qwen/Qwen-VL-Chat", "SimSun.ttf")
501
+ self.output = VisImage(self.img, scale=scale)
502
+ self.cpu_device = torch.device("cpu")
503
+
504
+ # too small texts are useless, therefore clamp to 14
505
+ self._default_font_size = max(
506
+ np.sqrt(self.output.height * self.output.width) // 30, 15 // scale
507
+ )
508
+
509
+ def draw_text(
510
+ self,
511
+ text,
512
+ position,
513
+ *,
514
+ font_size=None,
515
+ color="g",
516
+ horizontal_alignment="center",
517
+ rotation=0,
518
+ ):
519
+ if not font_size:
520
+ font_size = self._default_font_size
521
+
522
+ # since the text background is dark, we don't want the text to be dark
523
+ color = np.maximum(list(mplc.to_rgb(color)), 0.2)
524
+ color[np.argmax(color)] = max(0.8, np.max(color))
525
+
526
+ x, y = position
527
+ self.output.ax.text(
528
+ x,
529
+ y,
530
+ text,
531
+ size=font_size * self.output.scale,
532
+ fontproperties=FontProperties(fname=self.font_path),
533
+ bbox={"facecolor": "black", "alpha": 0.8, "pad": 0.7, "edgecolor": "none"},
534
+ verticalalignment="top",
535
+ horizontalalignment=horizontal_alignment,
536
+ color=color,
537
+ zorder=10,
538
+ rotation=rotation,
539
+ )
540
+ return self.output
541
+
542
+ def draw_box(self, box_coord, alpha=0.5, edge_color="g", line_style="-"):
543
+
544
+ x0, y0, x1, y1 = box_coord
545
+ width = x1 - x0
546
+ height = y1 - y0
547
+
548
+ linewidth = max(self._default_font_size / 4, 1)
549
+
550
+ self.output.ax.add_patch(
551
+ mpl.patches.Rectangle(
552
+ (x0, y0),
553
+ width,
554
+ height,
555
+ fill=False,
556
+ edgecolor=edge_color,
557
+ linewidth=linewidth * self.output.scale,
558
+ alpha=alpha,
559
+ linestyle=line_style,
560
+ )
561
+ )
562
+ return self.output
563
+
564
+ def get_output(self):
565
+
566
+ return self.output
tokenizer_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_max_length": 999999999999999999,
3
+ "tokenizer_class": "QWenTokenizer",
4
+ "auto_map": {
5
+ "AutoTokenizer": [
6
+ "tokenization_qwen.QWenTokenizer",
7
+ null
8
+ ]
9
+ }
10
+ }
vision.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f293b74085184879a81aa6b67301fd7156ffff8eaee4fa4ea65a1f75a4b44f5d
3
+ size 3871409417
visual.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Alibaba Cloud.
2
+ #
3
+ # This source code is licensed under the license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ from collections import OrderedDict
7
+ import math
8
+ import requests
9
+ from io import BytesIO
10
+ from functools import partial
11
+ from PIL import Image
12
+ from typing import Callable, Optional, Sequence, Tuple, List
13
+ import numpy as np
14
+
15
+ import torch
16
+ from torch import nn
17
+ from torch.nn import functional as F
18
+ from torch.nn.init import trunc_normal_
19
+ from torchvision import transforms
20
+ from torchvision.transforms import InterpolationMode
21
+
22
+
23
+ def get_abs_pos(abs_pos, tgt_size):
24
+ # abs_pos: L, C
25
+ # tgt_size: M
26
+ # return: M, C
27
+ src_size = int(math.sqrt(abs_pos.size(0)))
28
+ tgt_size = int(math.sqrt(tgt_size))
29
+ dtype = abs_pos.dtype
30
+
31
+ if src_size != tgt_size:
32
+ return F.interpolate(
33
+ abs_pos.float().reshape(1, src_size, src_size, -1).permute(0, 3, 1, 2),
34
+ size=(tgt_size, tgt_size),
35
+ mode="bicubic",
36
+ align_corners=False,
37
+ ).permute(0, 2, 3, 1).flatten(0, 2).to(dtype=dtype)
38
+ else:
39
+ return abs_pos
40
+
41
+ # https://github.com/facebookresearch/mae/blob/efb2a8062c206524e35e47d04501ed4f544c0ae8/util/pos_embed.py#L20
42
+ def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False):
43
+ """
44
+ grid_size: int of the grid height and width
45
+ return:
46
+ pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
47
+ """
48
+ grid_h = np.arange(grid_size, dtype=np.float32)
49
+ grid_w = np.arange(grid_size, dtype=np.float32)
50
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
51
+ grid = np.stack(grid, axis=0)
52
+
53
+ grid = grid.reshape([2, 1, grid_size, grid_size])
54
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
55
+ if cls_token:
56
+ pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
57
+ return pos_embed
58
+
59
+
60
+ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
61
+ assert embed_dim % 2 == 0
62
+
63
+ # use half of dimensions to encode grid_h
64
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
65
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
66
+
67
+ emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
68
+ return emb
69
+
70
+
71
+ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
72
+ """
73
+ embed_dim: output dimension for each position
74
+ pos: a list of positions to be encoded: size (M,)
75
+ out: (M, D)
76
+ """
77
+ assert embed_dim % 2 == 0
78
+ omega = np.arange(embed_dim // 2, dtype=np.float32)
79
+ omega /= embed_dim / 2.
80
+ omega = 1. / 10000**omega # (D/2,)
81
+
82
+ pos = pos.reshape(-1) # (M,)
83
+ out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
84
+
85
+ emb_sin = np.sin(out) # (M, D/2)
86
+ emb_cos = np.cos(out) # (M, D/2)
87
+
88
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
89
+ return emb
90
+
91
+
92
+ class Resampler(nn.Module):
93
+ """
94
+ A 2D perceiver-resampler network with one cross attention layers by
95
+ (grid_size**2) learnable queries and 2d sincos pos_emb
96
+ Outputs:
97
+ A tensor with the shape of (grid_size**2, embed_dim)
98
+ """
99
+ def __init__(
100
+ self,
101
+ grid_size,
102
+ embed_dim,
103
+ num_heads,
104
+ kv_dim=None,
105
+ norm_layer=nn.LayerNorm
106
+ ):
107
+ super().__init__()
108
+ self.num_queries = grid_size ** 2
109
+ self.embed_dim = embed_dim
110
+ self.num_heads = num_heads
111
+
112
+ self.pos_embed = nn.Parameter(
113
+ torch.from_numpy(get_2d_sincos_pos_embed(embed_dim, grid_size)).float()
114
+ ).requires_grad_(False)
115
+
116
+ self.query = nn.Parameter(torch.zeros(self.num_queries, embed_dim))
117
+ trunc_normal_(self.query, std=.02)
118
+
119
+ if kv_dim is not None and kv_dim != embed_dim:
120
+ self.kv_proj = nn.Linear(kv_dim, embed_dim, bias=False)
121
+ else:
122
+ self.kv_proj = nn.Identity()
123
+
124
+ self.attn = nn.MultiheadAttention(embed_dim, num_heads)
125
+ self.ln_q = norm_layer(embed_dim)
126
+ self.ln_kv = norm_layer(embed_dim)
127
+
128
+ self.apply(self._init_weights)
129
+
130
+ def _init_weights(self, m):
131
+ if isinstance(m, nn.Linear):
132
+ trunc_normal_(m.weight, std=.02)
133
+ if isinstance(m, nn.Linear) and m.bias is not None:
134
+ nn.init.constant_(m.bias, 0)
135
+ elif isinstance(m, nn.LayerNorm):
136
+ nn.init.constant_(m.bias, 0)
137
+ nn.init.constant_(m.weight, 1.0)
138
+
139
+ def forward(self, x, attn_mask=None):
140
+
141
+ pos_embed = get_abs_pos(self.pos_embed, x.size(1))
142
+
143
+ x = self.kv_proj(x)
144
+ x = self.ln_kv(x).permute(1, 0, 2)
145
+
146
+ N = x.shape[1]
147
+ q = self.ln_q(self.query)
148
+ out = self.attn(
149
+ self._repeat(q, N) + self.pos_embed.unsqueeze(1),
150
+ x + pos_embed.unsqueeze(1),
151
+ x,
152
+ attn_mask=attn_mask)[0]
153
+ return out.permute(1, 0, 2)
154
+
155
+ def _repeat(self, query, N: int):
156
+ return query.unsqueeze(1).repeat(1, N, 1)
157
+
158
+
159
+ class VisualAttention(nn.Module):
160
+ """self-attention layer class.
161
+
162
+ Self-attention layer takes input with size [s, b, h]
163
+ and returns output of the same size.
164
+ """
165
+
166
+ def __init__(self, embed_dim, num_heads,
167
+ bias=True, kdim=None, vdim=None):
168
+ super(VisualAttention, self).__init__()
169
+ self.embed_dim = embed_dim
170
+ self.kdim = kdim if kdim is not None else embed_dim
171
+ self.vdim = vdim if vdim is not None else embed_dim
172
+ self._qkv_same_embed_dim = self.kdim == embed_dim and self.vdim == embed_dim
173
+
174
+ self.num_heads = num_heads
175
+
176
+ # Per attention head and per partition values.
177
+ assert embed_dim % num_heads == 0
178
+ self.hidden_size_per_attention_head = embed_dim // num_heads
179
+ self.num_attention_heads_per_partition = num_heads
180
+ self.hidden_size_per_partition = embed_dim
181
+
182
+ # Strided linear layer.
183
+ assert self._qkv_same_embed_dim, 'Only Support SelfAttention Currently'
184
+ self.in_proj = nn.Linear(embed_dim, 3 * embed_dim)
185
+ self.out_proj = nn.Linear(embed_dim, embed_dim)
186
+ self.norm_factor = math.sqrt(self.hidden_size_per_attention_head)
187
+
188
+ def forward(self, query, key, value, attn_mask = None):
189
+ # query/key/value: [sq, b, h]
190
+ sq, b, _ = query.size()
191
+
192
+ assert query is key, 'Only Support Self-Attention Currently'
193
+ sk = sq
194
+ mixed_x_layer = self.in_proj(query)
195
+
196
+ # [sq, b, (np * 3 * hn)] --> [sq, b, np, 3 * hn]
197
+ new_tensor_shape = mixed_x_layer.size()[:-1] + \
198
+ (self.num_attention_heads_per_partition,
199
+ 3 * self.hidden_size_per_attention_head)
200
+ mixed_x_layer = mixed_x_layer.view(*new_tensor_shape)
201
+
202
+ # [sq, b, np, 3 * hn] --> 3 [sq, b, np, hn]
203
+ query_layer, key_layer, value_layer = mixed_x_layer.split(
204
+ self.hidden_size_per_attention_head, dim=-1)
205
+
206
+ # [sq, b, np, hn] -> [sq, b * np, hn]
207
+ query_layer = query_layer.view(sq,
208
+ b * self.num_attention_heads_per_partition,
209
+ self.hidden_size_per_attention_head).transpose(0, 1)
210
+ # [sk, b, np, hn] -> [sk, b * np, hn]
211
+ key_layer = key_layer.view(sk,
212
+ b * self.num_attention_heads_per_partition,
213
+ self.hidden_size_per_attention_head).transpose(0, 1)
214
+
215
+ q_scaled = query_layer / self.norm_factor
216
+ if attn_mask is not None:
217
+ attention_probs = torch.baddbmm(attn_mask, q_scaled, key_layer.transpose(-2, -1))
218
+ else:
219
+ attention_probs = torch.bmm(q_scaled, key_layer.transpose(-2, -1))
220
+ attention_probs = attention_probs.softmax(dim=-1)
221
+
222
+ value_layer = value_layer.view(sk,
223
+ b * self.num_attention_heads_per_partition,
224
+ self.hidden_size_per_attention_head).transpose(0, 1)
225
+
226
+ # matmul: [b * np, sq, hn]
227
+ context_layer = torch.bmm(attention_probs, value_layer)
228
+
229
+ # change view [b, np, sq, hn]
230
+ context_layer = context_layer.view(b,
231
+ self.num_attention_heads_per_partition,
232
+ sq, self.hidden_size_per_attention_head)
233
+
234
+ # [b, np, sq, hn] --> [sq, b, np, hn]
235
+ context_layer = context_layer.permute(2, 0, 1, 3).contiguous()
236
+
237
+ # [sq, b, np, hn] --> [sq, b, hp]
238
+ new_context_layer_shape = context_layer.size()[:-2] + \
239
+ (self.hidden_size_per_partition,)
240
+ context_layer = context_layer.view(*new_context_layer_shape)
241
+
242
+ output = self.out_proj(context_layer)
243
+
244
+ return output
245
+
246
+
247
+ class VisualAttentionBlock(nn.Module):
248
+ def __init__(
249
+ self,
250
+ d_model: int,
251
+ n_head: int,
252
+ mlp_ratio: float = 4.0,
253
+ act_layer: Callable = nn.GELU,
254
+ norm_layer: Callable = nn.LayerNorm,
255
+ is_cross_attention: bool = False,
256
+ ):
257
+ super().__init__()
258
+
259
+ self.ln_1 = norm_layer(d_model)
260
+ if is_cross_attention:
261
+ self.ln_1_kv = norm_layer(d_model)
262
+
263
+ self.ln_2 = norm_layer(d_model)
264
+ mlp_width = int(d_model * mlp_ratio)
265
+ self.attn = VisualAttention(d_model, n_head)
266
+ self.mlp = nn.Sequential(OrderedDict([
267
+ ("c_fc", nn.Linear(d_model, mlp_width)),
268
+ ("gelu", act_layer()),
269
+ ("c_proj", nn.Linear(mlp_width, d_model))
270
+ ]))
271
+
272
+ def attention(
273
+ self,
274
+ q_x: torch.Tensor,
275
+ k_x: Optional[torch.Tensor] = None,
276
+ v_x: Optional[torch.Tensor] = None,
277
+ attn_mask: Optional[torch.Tensor] = None,
278
+ ):
279
+ k_x = k_x if k_x is not None else q_x
280
+ v_x = v_x if v_x is not None else q_x
281
+
282
+ attn_mask = attn_mask.to(q_x.dtype) if attn_mask is not None else None
283
+ return self.attn(q_x, k_x, v_x, attn_mask=attn_mask)
284
+
285
+ def forward(
286
+ self,
287
+ q_x: torch.Tensor,
288
+ k_x: Optional[torch.Tensor] = None,
289
+ v_x: Optional[torch.Tensor] = None,
290
+ attn_mask: Optional[torch.Tensor] = None,
291
+ ):
292
+ k_x = self.ln_1_kv(k_x) if hasattr(self, "ln_1_kv") and k_x is not None else None
293
+ v_x = self.ln_1_kv(v_x) if hasattr(self, "ln_1_kv") and v_x is not None else None
294
+
295
+ x = q_x + self.attention(q_x=self.ln_1(q_x), k_x=k_x, v_x=v_x, attn_mask=attn_mask)
296
+ x = x + self.mlp(self.ln_2(x))
297
+ return x
298
+
299
+
300
+ class TransformerBlock(nn.Module):
301
+ def __init__(
302
+ self,
303
+ width: int,
304
+ layers: int,
305
+ heads: int,
306
+ mlp_ratio: float = 4.0,
307
+ act_layer: Callable = nn.GELU,
308
+ norm_layer: Callable = nn.LayerNorm,
309
+ ):
310
+ super().__init__()
311
+ self.width = width
312
+ self.layers = layers
313
+
314
+ self.resblocks = nn.ModuleList([
315
+ VisualAttentionBlock(
316
+ width, heads, mlp_ratio, act_layer=act_layer, norm_layer=norm_layer)
317
+ for _ in range(layers)
318
+ ])
319
+
320
+ def get_cast_dtype(self) -> torch.dtype:
321
+ return self.resblocks[0].mlp.c_fc.weight.dtype
322
+
323
+ def get_cast_device(self) -> torch.device:
324
+ return self.resblocks[0].mlp.c_fc.weight.device
325
+
326
+ def forward(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None):
327
+ for r in self.resblocks:
328
+ x = r(x, attn_mask=attn_mask)
329
+ return x
330
+
331
+
332
+ class VisionTransformer(nn.Module):
333
+
334
+ def __init__(
335
+ self,
336
+ image_size: int,
337
+ patch_size: int,
338
+ width: int,
339
+ layers: int,
340
+ heads: int,
341
+ mlp_ratio: float,
342
+ n_queries: int = 256,
343
+ output_dim: int = 512,
344
+ **kwargs
345
+ ):
346
+ super().__init__()
347
+ image_height, image_width = self.image_size = (image_size, image_size)
348
+ patch_height, patch_width = self.patch_size = (patch_size, patch_size)
349
+ self.grid_size = (image_height // patch_height, image_width // patch_width)
350
+ self.output_dim = output_dim
351
+
352
+ mean = (0.48145466, 0.4578275, 0.40821073)
353
+ std = (0.26862954, 0.26130258, 0.27577711)
354
+ self.image_transform = transforms.Compose([
355
+ transforms.Resize(
356
+ (image_size, image_size),
357
+ interpolation=InterpolationMode.BICUBIC
358
+ ),
359
+ transforms.ToTensor(),
360
+ transforms.Normalize(mean=mean, std=std),
361
+ ])
362
+
363
+ self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
364
+
365
+ # class embeddings and positional embeddings
366
+ scale = width ** -0.5
367
+ self.positional_embedding = nn.Parameter(scale * torch.randn(256, width))
368
+
369
+ norm_layer = partial(nn.LayerNorm, eps=1e-6)
370
+ act_layer = nn.GELU
371
+
372
+ self.ln_pre = norm_layer(width)
373
+ self.transformer = TransformerBlock(
374
+ width,
375
+ layers,
376
+ heads,
377
+ mlp_ratio,
378
+ act_layer=act_layer,
379
+ norm_layer=norm_layer,
380
+ )
381
+
382
+ self.attn_pool = Resampler(
383
+ grid_size=int(math.sqrt(n_queries)),
384
+ embed_dim=output_dim,
385
+ num_heads=output_dim // 128,
386
+ kv_dim=width,
387
+ norm_layer=norm_layer,
388
+ )
389
+ self.ln_post = norm_layer(output_dim)
390
+ self.proj = nn.Parameter((output_dim** -0.5) * torch.randn(output_dim, output_dim))
391
+
392
+ def forward(self, x: torch.Tensor):
393
+ x = x.to(
394
+ dtype=self.transformer.get_cast_dtype(),
395
+ device=self.transformer.get_cast_device(),
396
+ )
397
+ # to patches
398
+ x = self.conv1(x) # shape = [*, width, grid, grid]
399
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
400
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
401
+
402
+ x = x + get_abs_pos(self.positional_embedding, x.size(1))
403
+
404
+ x = self.ln_pre(x)
405
+
406
+ x = x.permute(1, 0, 2) # NLD -> LND
407
+ x = self.transformer(x)
408
+ x = x.permute(1, 0, 2) # LND -> NLD
409
+
410
+ x = self.attn_pool(x)
411
+ x = self.ln_post(x)
412
+ x = x @ self.proj
413
+
414
+ return x
415
+
416
+ def encode(self, image_paths):
417
+ images = []
418
+ for image_path in image_paths:
419
+ if isinstance(image_path, Image.Image):
420
+ image = image_path
421
+ elif image_path.startswith("http://") or image_path.startswith("https://"):
422
+ image = Image.open(requests.get(image_path, stream=True).raw)
423
+ else:
424
+ image = Image.open(image_path)
425
+ image = image.convert("RGB")
426
+ images.append(self.image_transform(image))
427
+ images = torch.stack(images, dim=0)
428
+ return self(images)
vocab.json ADDED
The diff for this file is too large to render. See raw diff