hflqf88888 commited on
Commit
97f37ed
·
verified ·
1 Parent(s): a70fb01

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "../OdysseyAgent",
3
+ "architectures": [
4
+ "QWenLMHeadModel"
5
+ ],
6
+ "attn_dropout_prob": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_qwen.QWenConfig",
9
+ "AutoModelForCausalLM": "modeling_qwen.QWenLMHeadModel"
10
+ },
11
+ "bf16": true,
12
+ "emb_dropout_prob": 0.0,
13
+ "fp16": false,
14
+ "fp32": false,
15
+ "hidden_size": 4096,
16
+ "his_len": 4,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 22016,
19
+ "kv_channels": 128,
20
+ "layer_norm_epsilon": 1e-06,
21
+ "max_position_embeddings": 8192,
22
+ "model_type": "qwen",
23
+ "no_bias": true,
24
+ "num_attention_heads": 32,
25
+ "num_hidden_layers": 32,
26
+ "onnx_safe": null,
27
+ "rotary_emb_base": 10000,
28
+ "rotary_pct": 1.0,
29
+ "scale_attn_weights": true,
30
+ "seq_length": 2048,
31
+ "tie_word_embeddings": false,
32
+ "tokenizer_type": "QWenTokenizer",
33
+ "torch_dtype": "float16",
34
+ "transformers_version": "4.32.0",
35
+ "use_cache": false,
36
+ "use_dynamic_ntk": true,
37
+ "use_flash_attn": false,
38
+ "use_logn_attn": true,
39
+ "visual": {
40
+ "heads": 16,
41
+ "image_size": 448,
42
+ "image_start_id": 151857,
43
+ "layers": 48,
44
+ "mlp_ratio": 4.9231,
45
+ "output_dim": 4096,
46
+ "patch_size": 14,
47
+ "width": 1664
48
+ },
49
+ "vocab_size": 151936
50
+ }
configuration_qwen.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 transformers import PretrainedConfig
7
+
8
+
9
+ class QWenConfig(PretrainedConfig):
10
+ model_type = "qwen"
11
+ keys_to_ignore_at_inference = ["past_key_values"]
12
+
13
+ def __init__(
14
+ self,
15
+ vocab_size=151936,
16
+ hidden_size=4096,
17
+ num_hidden_layers=32,
18
+ num_attention_heads=32,
19
+ emb_dropout_prob=0.0,
20
+ attn_dropout_prob=0.0,
21
+ layer_norm_epsilon=1e-6,
22
+ initializer_range=0.02,
23
+ max_position_embeddings=8192,
24
+ scale_attn_weights=True,
25
+ use_cache=True,
26
+ bf16=False,
27
+ fp16=False,
28
+ fp32=False,
29
+ kv_channels=128,
30
+ rotary_pct=1.0,
31
+ rotary_emb_base=10000,
32
+ use_dynamic_ntk=True,
33
+ use_logn_attn=True,
34
+ use_flash_attn="auto",
35
+ intermediate_size=22016,
36
+ no_bias=True,
37
+ tie_word_embeddings=False,
38
+ **kwargs,
39
+ ):
40
+ self.vocab_size = vocab_size
41
+ self.hidden_size = hidden_size
42
+ self.intermediate_size = intermediate_size
43
+ self.num_hidden_layers = num_hidden_layers
44
+ self.num_attention_heads = num_attention_heads
45
+ self.emb_dropout_prob = emb_dropout_prob
46
+ self.attn_dropout_prob = attn_dropout_prob
47
+ self.layer_norm_epsilon = layer_norm_epsilon
48
+ self.initializer_range = initializer_range
49
+ self.scale_attn_weights = scale_attn_weights
50
+ self.use_cache = use_cache
51
+ self.max_position_embeddings = max_position_embeddings
52
+ self.bf16 = bf16
53
+ self.fp16 = fp16
54
+ self.fp32 = fp32
55
+ self.kv_channels = kv_channels
56
+ self.rotary_pct = rotary_pct
57
+ self.rotary_emb_base = rotary_emb_base
58
+ self.use_dynamic_ntk = use_dynamic_ntk
59
+ self.use_logn_attn = use_logn_attn
60
+ self.use_flash_attn = use_flash_attn
61
+ self.no_bias = no_bias
62
+ super().__init__(
63
+ tie_word_embeddings=tie_word_embeddings,
64
+ **kwargs
65
+ )
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.32.0"
4
+ }
modeling_qwen.py ADDED
@@ -0,0 +1,1347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ print('OdysseyAgent')
2
+
3
+ import importlib
4
+ import math
5
+ from typing import TYPE_CHECKING, Optional, Tuple, Union, Callable, List, Any, Generator
6
+ import os, json
7
+ import numpy as np
8
+ import torch
9
+ import torch.nn.functional as F
10
+ import torch.utils.checkpoint
11
+ from torch.cuda.amp import autocast
12
+
13
+ from torch.nn import CrossEntropyLoss
14
+ from transformers import PreTrainedTokenizer, GenerationConfig, StoppingCriteriaList
15
+ from transformers.generation.logits_process import LogitsProcessorList
16
+
17
+ if TYPE_CHECKING:
18
+ from transformers.generation.streamers import BaseStreamer
19
+ from transformers.generation.utils import GenerateOutput
20
+ from transformers.modeling_outputs import (
21
+ BaseModelOutputWithPast,
22
+ CausalLMOutputWithPast,
23
+ )
24
+ from transformers.modeling_utils import PreTrainedModel
25
+ from transformers.utils import logging
26
+
27
+ try:
28
+ from einops import rearrange
29
+ except ImportError:
30
+ rearrange = None
31
+ from torch import nn
32
+
33
+ SUPPORT_CUDA = torch.cuda.is_available()
34
+ SUPPORT_BF16 = SUPPORT_CUDA and torch.cuda.is_bf16_supported()
35
+ SUPPORT_FP16 = SUPPORT_CUDA and torch.cuda.get_device_capability(0)[0] >= 7
36
+
37
+ from torch.nn.init import trunc_normal_
38
+ import sys
39
+ sys.path.append('../OdysseyAgent')
40
+
41
+ from configuration_qwen import QWenConfig
42
+ from qwen_generation_utils import (
43
+ HistoryType,
44
+ make_context,
45
+ decode_tokens,
46
+ get_stop_words_ids,
47
+ StopWordsLogitsProcessor,
48
+ )
49
+ from visual import VisionTransformer
50
+
51
+ IMAGE_HISTORY = '../data/his_index.json'
52
+
53
+ USE_RESAMPLER = True
54
+
55
+ print(IMAGE_HISTORY)
56
+ logger = logging.get_logger(__name__)
57
+
58
+ _CHECKPOINT_FOR_DOC = "qwen"
59
+ _CONFIG_FOR_DOC = "QWenConfig"
60
+
61
+ QWen_PRETRAINED_MODEL_ARCHIVE_LIST = ["qwen-7b"]
62
+
63
+ _ERROR_BAD_CHAT_FORMAT = """\
64
+ We detect you are probably using the pretrained model (rather than chat model) for chatting, since the chat_format in generation_config is not "chatml".
65
+ If you are directly using the model downloaded from Huggingface, please make sure you are using our "Qwen/Qwen-7B-Chat" Huggingface model (rather than "Qwen/Qwen-7B") when you call model.chat().
66
+ 我们检测到您可能在使用预训练模型(而非chat模型)进行多轮chat,因为您当前在generation_config指定的chat_format,并未设置为我们在对话中所支持的"chatml"格式。
67
+ 如果您在直接使用我们从Huggingface提供的模型,请确保您在调用model.chat()时,使用的是"Qwen/Qwen-7B-Chat"模型(而非"Qwen/Qwen-7B"预训练模型)。
68
+ """
69
+
70
+ _SENTINEL = object()
71
+ _ERROR_STREAM_IN_CHAT = """\
72
+ Pass argument `stream` to model.chat() is buggy, deprecated, and marked for removal. Please use model.chat_stream(...) instead of model.chat(..., stream=True).
73
+ 向model.chat()传入参数stream的用法可能存在Bug,该用法已被废弃,将在未来被移除。请使用model.chat_stream(...)代替model.chat(..., stream=True)。
74
+ """
75
+
76
+ apply_rotary_emb_func = None
77
+ rms_norm = None
78
+
79
+
80
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
81
+ def _make_causal_mask(
82
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
83
+ ):
84
+ """
85
+ Make causal mask used for bi-directional self-attention.
86
+ """
87
+ bsz, tgt_len = input_ids_shape
88
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
89
+ mask_cond = torch.arange(mask.size(-1), device=device)
90
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
91
+ mask = mask.to(dtype)
92
+
93
+ if past_key_values_length > 0:
94
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
95
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
96
+
97
+
98
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
99
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
100
+ """
101
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
102
+ """
103
+ bsz, src_len = mask.size()
104
+ tgt_len = tgt_len if tgt_len is not None else src_len
105
+
106
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
107
+
108
+ inverted_mask = 1.0 - expanded_mask
109
+
110
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
111
+
112
+ def get_abs_pos(abs_pos, tgt_size):
113
+ # abs_pos: L, C
114
+ # tgt_size: M
115
+ # return: M, C
116
+ src_size = int(math.sqrt(abs_pos.size(0)))
117
+ tgt_size = int(math.sqrt(tgt_size))
118
+ dtype = abs_pos.dtype
119
+
120
+ if src_size != tgt_size:
121
+ return F.interpolate(
122
+ abs_pos.float().reshape(1, src_size, src_size, -1).permute(0, 3, 1, 2),
123
+ size=(tgt_size, tgt_size),
124
+ mode="bicubic",
125
+ align_corners=False,
126
+ ).permute(0, 2, 3, 1).flatten(0, 2).to(dtype=dtype)
127
+ else:
128
+ return abs_pos
129
+
130
+
131
+ def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False):
132
+ """
133
+ grid_size: int of the grid height and width
134
+ return:
135
+ pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
136
+ """
137
+ grid_h = np.arange(grid_size, dtype=np.float32)
138
+ grid_w = np.arange(grid_size, dtype=np.float32)
139
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
140
+ grid = np.stack(grid, axis=0)
141
+
142
+ grid = grid.reshape([2, 1, grid_size, grid_size])
143
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
144
+ if cls_token:
145
+ pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
146
+ return pos_embed
147
+
148
+
149
+ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
150
+ assert embed_dim % 2 == 0
151
+
152
+ # use half of dimensions to encode grid_h
153
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
154
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
155
+
156
+ emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
157
+ return emb
158
+
159
+
160
+ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
161
+ """
162
+ embed_dim: output dimension for each position
163
+ pos: a list of positions to be encoded: size (M,)
164
+ out: (M, D)
165
+ """
166
+ assert embed_dim % 2 == 0
167
+ omega = np.arange(embed_dim // 2, dtype=np.float32)
168
+ omega /= embed_dim / 2.
169
+ omega = 1. / 10000**omega # (D/2,)
170
+
171
+ pos = pos.reshape(-1) # (M,)
172
+ out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
173
+
174
+ emb_sin = np.sin(out) # (M, D/2)
175
+ emb_cos = np.cos(out) # (M, D/2)
176
+
177
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
178
+ return emb
179
+
180
+
181
+
182
+ class HisResampler(nn.Module):
183
+ def __init__(
184
+ self,
185
+ embed_dim=4096,
186
+ num_heads=32,
187
+ grid_size=16,
188
+ kv_dim=None,
189
+ norm_layer=nn.LayerNorm
190
+ ):
191
+ super().__init__()
192
+ self.num_queries = grid_size ** 2
193
+ self.embed_dim = embed_dim
194
+ self.num_heads = num_heads
195
+
196
+ self.pos_embed = nn.Parameter(
197
+ torch.from_numpy(get_2d_sincos_pos_embed(embed_dim, grid_size)).float()
198
+ ).requires_grad_(False)
199
+
200
+ self.query = nn.Parameter(torch.zeros(self.num_queries, embed_dim))
201
+ trunc_normal_(self.query, std=.02)
202
+
203
+ if kv_dim is not None and kv_dim != embed_dim:
204
+ self.kv_proj = nn.Linear(kv_dim, embed_dim, bias=False)
205
+ else:
206
+ self.kv_proj = nn.Identity()
207
+
208
+ self.attn = nn.MultiheadAttention(embed_dim, num_heads)
209
+ self.ln_q = norm_layer(embed_dim)
210
+ self.ln_kv = norm_layer(embed_dim)
211
+
212
+ self.ln_post = norm_layer(embed_dim)
213
+ self.proj = nn.Parameter((embed_dim** -0.5) * torch.randn(embed_dim, embed_dim))
214
+
215
+ self.apply(self._init_weights)
216
+
217
+ def _init_weights(self, m):
218
+ if isinstance(m, nn.Linear):
219
+ trunc_normal_(m.weight, std=.02)
220
+ if isinstance(m, nn.Linear) and m.bias is not None:
221
+ nn.init.constant_(m.bias, 0)
222
+ elif isinstance(m, nn.LayerNorm):
223
+ nn.init.constant_(m.bias, 0)
224
+ nn.init.constant_(m.weight, 1.0)
225
+
226
+ def forward(self, x, attn_mask=None):
227
+
228
+ x = self.kv_proj(x)
229
+ x = self.ln_kv(x).permute(1, 0, 2)
230
+
231
+ N = x.shape[1]
232
+ q = self.ln_q(self.query)
233
+ out = self.attn(
234
+ self._repeat(q, N),
235
+ x,
236
+ x,
237
+ attn_mask=attn_mask)[0]
238
+ out = out.permute(1, 0, 2)
239
+ out = self.ln_post(out)
240
+ out = out @ self.proj
241
+ return out
242
+
243
+ def _repeat(self, query, N: int):
244
+ return query.unsqueeze(1).repeat(1, N, 1)
245
+
246
+
247
+
248
+ class QWenAttention(nn.Module):
249
+ def __init__(self, config):
250
+ super().__init__()
251
+
252
+ self.register_buffer("masked_bias", torch.tensor(-1e4), persistent=False)
253
+ self.seq_length = config.seq_length
254
+
255
+ self.hidden_size = config.hidden_size
256
+ self.split_size = config.hidden_size
257
+ self.num_heads = config.num_attention_heads
258
+ self.head_dim = self.hidden_size // self.num_heads
259
+
260
+ self.scale_attn_weights = True
261
+
262
+ self.projection_size = config.kv_channels * config.num_attention_heads
263
+
264
+ assert self.projection_size % config.num_attention_heads == 0
265
+ self.hidden_size_per_attention_head = (
266
+ self.projection_size // config.num_attention_heads
267
+ )
268
+
269
+ self.c_attn = nn.Linear(config.hidden_size, 3 * self.projection_size)
270
+
271
+ self.c_proj = nn.Linear(
272
+ config.hidden_size, self.projection_size, bias=not config.no_bias
273
+ )
274
+
275
+ self.is_fp32 = not (config.bf16 or config.fp16)
276
+ self.bf16 = config.bf16
277
+
278
+ self.use_dynamic_ntk = config.use_dynamic_ntk
279
+ self.use_logn_attn = config.use_logn_attn
280
+
281
+ logn_list = [
282
+ math.log(i, self.seq_length) if i > self.seq_length else 1
283
+ for i in range(1, 32768)
284
+ ]
285
+ self.logn_tensor = torch.tensor(logn_list)[None, :, None, None]
286
+
287
+ self.attn_dropout = nn.Dropout(config.attn_dropout_prob)
288
+
289
+ def _attn(self, query, key, value, registered_causal_mask, attention_mask=None, head_mask=None):
290
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
291
+
292
+ if self.scale_attn_weights:
293
+ attn_weights = attn_weights / torch.full(
294
+ [],
295
+ value.size(-1) ** 0.5,
296
+ dtype=attn_weights.dtype,
297
+ device=attn_weights.device,
298
+ )
299
+
300
+ query_length, key_length = query.size(-2), key.size(-2)
301
+ # causal_mask = self.bias[
302
+ # :, :, key_length - query_length : key_length, :key_length
303
+ # ]
304
+ # mask_value = torch.finfo(attn_weights.dtype).min
305
+ # mask_value = torch.full([], mask_value, dtype=attn_weights.dtype).to(
306
+ # attn_weights.device
307
+ # )
308
+ # attn_weights = torch.where(
309
+ # causal_mask, attn_weights.to(attn_weights.dtype), mask_value
310
+ # )
311
+ attn_weights = attn_weights + attention_mask
312
+
313
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
314
+
315
+ attn_weights = attn_weights.type(value.dtype)
316
+ attn_weights = self.attn_dropout(attn_weights)
317
+
318
+ if head_mask is not None:
319
+ attn_weights = attn_weights * head_mask
320
+
321
+ attn_output = torch.matmul(attn_weights, value)
322
+ attn_output = attn_output.transpose(1, 2)
323
+
324
+ return attn_output, attn_weights
325
+
326
+ def _upcast_and_reordered_attn(
327
+ self, query, key, value, registered_causal_mask, attention_mask=None, head_mask=None
328
+ ):
329
+ bsz, num_heads, q_seq_len, dk = query.size()
330
+ _, _, k_seq_len, _ = key.size()
331
+
332
+ attn_weights = torch.empty(
333
+ bsz * num_heads,
334
+ q_seq_len,
335
+ k_seq_len,
336
+ dtype=torch.float32,
337
+ device=query.device,
338
+ )
339
+
340
+ scale_factor = 1.0
341
+ if self.scale_attn_weights:
342
+ scale_factor /= float(value.size(-1)) ** 0.5
343
+
344
+ with autocast(enabled=False):
345
+ q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(
346
+ -1, dk, k_seq_len
347
+ )
348
+ attn_weights = torch.baddbmm(
349
+ attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor
350
+ )
351
+ attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
352
+
353
+ query_length, key_length = query.size(-2), key.size(-2)
354
+ causal_mask = registered_causal_mask[
355
+ :, :, key_length - query_length : key_length, :key_length
356
+ ]
357
+ mask_value = torch.finfo(attn_weights.dtype).min
358
+ mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(
359
+ attn_weights.device
360
+ )
361
+ attn_weights = torch.where(causal_mask, attn_weights, mask_value)
362
+
363
+ if attention_mask is not None:
364
+ attn_weights = attn_weights + attention_mask
365
+
366
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
367
+
368
+ if attn_weights.dtype != torch.float32:
369
+ raise RuntimeError(
370
+ "Error with upcasting, attn_weights does not have dtype torch.float32"
371
+ )
372
+ attn_weights = attn_weights.type(value.dtype)
373
+ attn_weights = self.attn_dropout(attn_weights)
374
+
375
+ if head_mask is not None:
376
+ attn_weights = attn_weights * head_mask
377
+
378
+ attn_output = torch.matmul(attn_weights, value)
379
+
380
+ return attn_output, attn_weights
381
+
382
+ def _split_heads(self, tensor, num_heads, attn_head_size):
383
+ new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
384
+ tensor = tensor.view(new_shape)
385
+ return tensor
386
+
387
+ def _merge_heads(self, tensor, num_heads, attn_head_size):
388
+ tensor = tensor.contiguous()
389
+ new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
390
+ return tensor.view(new_shape)
391
+
392
+ def forward(
393
+ self,
394
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
395
+ rotary_pos_emb: Optional[List[torch.Tensor]] = None,
396
+ registered_causal_mask: Optional[torch.Tensor] = None,
397
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
398
+ attention_mask: Optional[torch.FloatTensor] = None,
399
+ head_mask: Optional[torch.FloatTensor] = None,
400
+ encoder_hidden_states: Optional[torch.Tensor] = None,
401
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
402
+ output_attentions: Optional[bool] = False,
403
+ use_cache: Optional[bool] = False,
404
+ ):
405
+
406
+ mixed_x_layer = self.c_attn(hidden_states)
407
+
408
+ query, key, value = mixed_x_layer.split(self.split_size, dim=2)
409
+
410
+ query = self._split_heads(query, self.num_heads, self.head_dim)
411
+ key = self._split_heads(key, self.num_heads, self.head_dim)
412
+ value = self._split_heads(value, self.num_heads, self.head_dim)
413
+
414
+ if rotary_pos_emb is not None:
415
+ cur_len = query.shape[1]
416
+ rotary_pos_emb = [i[:, -cur_len:, :, :] for i in rotary_pos_emb]
417
+ rotary_pos_emb = (rotary_pos_emb,) * 2
418
+ q_pos_emb, k_pos_emb = rotary_pos_emb
419
+ # Slice the pos emb for current inference
420
+ query = apply_rotary_pos_emb(query, q_pos_emb)
421
+ key = apply_rotary_pos_emb(key, k_pos_emb)
422
+
423
+ if layer_past is not None:
424
+ past_key, past_value = layer_past[0], layer_past[1]
425
+ key = torch.cat((past_key, key), dim=1)
426
+ value = torch.cat((past_value, value), dim=1)
427
+
428
+ if use_cache:
429
+ present = (key, value)
430
+ else:
431
+ present = None
432
+
433
+ if self.use_logn_attn and not self.training:
434
+ if self.logn_tensor.device != query.device or self.logn_tensor.dtype != query.dtype:
435
+ self.logn_tensor = self.logn_tensor.to(query.device).type_as(query)
436
+ seq_start = key.size(1) - query.size(1)
437
+ seq_end = key.size(1)
438
+ logn_tensor = self.logn_tensor[:, seq_start:seq_end, :, :]
439
+ query = query * logn_tensor.expand_as(query)
440
+
441
+ query = query.permute(0, 2, 1, 3)
442
+ key = key.permute(0, 2, 1, 3)
443
+ value = value.permute(0, 2, 1, 3)
444
+ attn_output, attn_weight = self._attn(
445
+ query, key, value, registered_causal_mask, attention_mask, head_mask
446
+ )
447
+ context_layer = self._merge_heads(
448
+ attn_output, self.num_heads, self.head_dim
449
+ )
450
+
451
+ attn_output = self.c_proj(context_layer)
452
+
453
+ outputs = (attn_output, present)
454
+ if output_attentions:
455
+ outputs += (attn_weight,)
456
+
457
+ return outputs
458
+
459
+
460
+ class QWenMLP(nn.Module):
461
+ def __init__(self, config):
462
+ super().__init__()
463
+ self.w1 = nn.Linear(
464
+ config.hidden_size, config.intermediate_size // 2, bias=not config.no_bias
465
+ )
466
+ self.w2 = nn.Linear(
467
+ config.hidden_size, config.intermediate_size // 2, bias=not config.no_bias
468
+ )
469
+ ff_dim_in = config.intermediate_size // 2
470
+ self.c_proj = nn.Linear(ff_dim_in, config.hidden_size, bias=not config.no_bias)
471
+
472
+ def forward(self, hidden_states):
473
+ a1 = self.w1(hidden_states)
474
+ a2 = self.w2(hidden_states)
475
+ intermediate_parallel = a1 * F.silu(a2)
476
+ output = self.c_proj(intermediate_parallel)
477
+ return output
478
+
479
+ class QWenBlock(nn.Module):
480
+ def __init__(self, config):
481
+ super().__init__()
482
+ hidden_size = config.hidden_size
483
+ self.bf16 = config.bf16
484
+
485
+ self.ln_1 = RMSNorm(
486
+ hidden_size,
487
+ eps=config.layer_norm_epsilon,
488
+ )
489
+ self.attn = QWenAttention(config)
490
+ self.ln_2 = RMSNorm(
491
+ hidden_size,
492
+ eps=config.layer_norm_epsilon,
493
+ )
494
+
495
+ self.mlp = QWenMLP(config)
496
+
497
+ def forward(
498
+ self,
499
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
500
+ rotary_pos_emb: Optional[List[torch.Tensor]] = None,
501
+ registered_causal_mask: Optional[torch.Tensor] = None,
502
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
503
+ attention_mask: Optional[torch.FloatTensor] = None,
504
+ head_mask: Optional[torch.FloatTensor] = None,
505
+ encoder_hidden_states: Optional[torch.Tensor] = None,
506
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
507
+ use_cache: Optional[bool] = False,
508
+ output_attentions: Optional[bool] = False,
509
+ ):
510
+ layernorm_output = self.ln_1(hidden_states)
511
+
512
+ attn_outputs = self.attn(
513
+ layernorm_output,
514
+ rotary_pos_emb,
515
+ registered_causal_mask=registered_causal_mask,
516
+ layer_past=layer_past,
517
+ attention_mask=attention_mask,
518
+ head_mask=head_mask,
519
+ use_cache=use_cache,
520
+ output_attentions=output_attentions,
521
+ )
522
+ attn_output = attn_outputs[0]
523
+
524
+ outputs = attn_outputs[1:]
525
+
526
+ residual = hidden_states
527
+ layernorm_input = attn_output + residual
528
+
529
+ layernorm_output = self.ln_2(layernorm_input)
530
+
531
+ residual = layernorm_input
532
+ mlp_output = self.mlp(layernorm_output)
533
+ hidden_states = residual + mlp_output
534
+
535
+ if use_cache:
536
+ outputs = (hidden_states,) + outputs
537
+ else:
538
+ outputs = (hidden_states,) + outputs[1:]
539
+
540
+ return outputs
541
+
542
+
543
+ class QWenPreTrainedModel(PreTrainedModel):
544
+ config_class = QWenConfig
545
+ base_model_prefix = "transformer"
546
+ is_parallelizable = False
547
+ supports_gradient_checkpointing = True
548
+ _no_split_modules = ["QWenBlock"]
549
+
550
+ def __init__(self, *inputs, **kwargs):
551
+ super().__init__(*inputs, **kwargs)
552
+
553
+ def _init_weights(self, module):
554
+ """Initialize the weights."""
555
+ if isinstance(module, nn.Linear):
556
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
557
+ if module.bias is not None:
558
+ module.bias.data.zero_()
559
+ elif isinstance(module, nn.Embedding):
560
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
561
+ if module.padding_idx is not None:
562
+ module.weight.data[module.padding_idx].zero_()
563
+ elif isinstance(module, RMSNorm):
564
+ module.weight.data.fill_(1.0)
565
+
566
+ for name, p in module.named_parameters():
567
+ if name == "c_proj.weight":
568
+ p.data.normal_(
569
+ mean=0.0,
570
+ std=(
571
+ self.config.initializer_range
572
+ / math.sqrt(2 * self.config.num_hidden_layers)
573
+ ),
574
+ )
575
+
576
+ def _set_gradient_checkpointing(self, module, value=False):
577
+ if isinstance(module, QWenModel):
578
+ module.gradient_checkpointing = value
579
+
580
+
581
+ class QWenModel(QWenPreTrainedModel):
582
+ _keys_to_ignore_on_load_missing = ["attn.masked_bias"]
583
+
584
+ def __init__(self, config):
585
+ super().__init__(config)
586
+ self.his_len = config.his_len
587
+ self.vocab_size = config.vocab_size
588
+ self.num_hidden_layers = config.num_hidden_layers
589
+ self.embed_dim = config.hidden_size
590
+
591
+ self.gradient_checkpointing = False
592
+ self.use_dynamic_ntk = config.use_dynamic_ntk
593
+ self.seq_length = config.seq_length
594
+
595
+ self.wte = nn.Embedding(self.vocab_size, self.embed_dim)
596
+
597
+ self.drop = nn.Dropout(config.emb_dropout_prob)
598
+
599
+ if config.rotary_pct == 1.0:
600
+ self.rotary_ndims = None
601
+ else:
602
+ assert config.rotary_pct < 1
603
+ self.rotary_ndims = int(
604
+ config.kv_channels * config.rotary_pct
605
+ )
606
+ dim = (
607
+ self.rotary_ndims
608
+ if self.rotary_ndims is not None
609
+ else config.kv_channels
610
+ )
611
+ self.rotary_emb = RotaryEmbedding(dim, base=config.rotary_emb_base)
612
+
613
+ self.use_flash_attn = config.use_flash_attn
614
+ self.is_fp32 = not (config.bf16 or config.fp16)
615
+ self.registered_causal_mask = None
616
+
617
+ self.h = nn.ModuleList(
618
+ [
619
+ QWenBlock(
620
+ config
621
+ )
622
+ for i in range(config.num_hidden_layers)
623
+ ]
624
+ )
625
+ self.ln_f = RMSNorm(
626
+ self.embed_dim,
627
+ eps=config.layer_norm_epsilon,
628
+ )
629
+
630
+ self.visual = VisionTransformer(**config.visual)
631
+
632
+ self.post_init()
633
+
634
+ if USE_RESAMPLER:
635
+ print('init RESAMPLER')
636
+ self.his_resampler = HisResampler()
637
+
638
+ self.imgtoken_dict = {}
639
+ if os.path.isdir(IMAGE_HISTORY):
640
+ for subdata in os.listdir(IMAGE_HISTORY):
641
+ sub_img_dict = json.load(open(os.path.join(IMAGE_HISTORY, subdata)))
642
+ self.imgtoken_dict.update(sub_img_dict)
643
+ else:
644
+ self.imgtoken_dict = json.load(open(IMAGE_HISTORY))
645
+
646
+ print('imgtoken_dict cache len:', len(self.imgtoken_dict))
647
+
648
+ def set_input_embeddings(self, new_embeddings):
649
+ self.wte = new_embeddings
650
+
651
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
652
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
653
+ # create causal mask
654
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
655
+ combined_attention_mask = None
656
+ if input_shape[-1] > 1:
657
+ combined_attention_mask = _make_causal_mask(
658
+ input_shape,
659
+ inputs_embeds.dtype,
660
+ device=inputs_embeds.device,
661
+ past_key_values_length=past_key_values_length,
662
+ )
663
+
664
+ if attention_mask is not None:
665
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
666
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
667
+ inputs_embeds.device
668
+ )
669
+ combined_attention_mask = (
670
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
671
+ )
672
+
673
+ return combined_attention_mask
674
+
675
+
676
+ def forward(
677
+ self,
678
+ input_ids: Optional[torch.LongTensor] = None,
679
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
680
+ attention_mask: Optional[torch.FloatTensor] = None,
681
+ token_type_ids: Optional[torch.LongTensor] = None,
682
+ position_ids: Optional[torch.LongTensor] = None,
683
+ head_mask: Optional[torch.FloatTensor] = None,
684
+ inputs_embeds: Optional[torch.FloatTensor] = None,
685
+ encoder_hidden_states: Optional[torch.Tensor] = None,
686
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
687
+ use_cache: Optional[bool] = None,
688
+ output_attentions: Optional[bool] = None,
689
+ output_hidden_states: Optional[bool] = None,
690
+ return_dict: Optional[bool] = None,
691
+ ):
692
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
693
+
694
+ if past_key_values is None and torch.any(input_ids == self.config.visual['image_start_id']):
695
+ bos_pos = torch.where(input_ids == self.config.visual['image_start_id'])
696
+ eos_pos = torch.where(input_ids == self.config.visual['image_start_id'] + 1)
697
+ assert (bos_pos[0] == eos_pos[0]).all()
698
+ img_pos = torch.stack((bos_pos[0], bos_pos[1], eos_pos[1]), dim=1)
699
+ now_images = []
700
+ his_images = []
701
+ C_list = []
702
+ images = []
703
+ his_idx = []
704
+ his_image_temp = []
705
+ for idx, (i, a, b) in enumerate(img_pos):
706
+ image = input_ids[i][a + 1 : b - 1].tolist()
707
+ image = image[ : image.index(self.config.visual['image_start_id'] + 2)]
708
+ image_path = bytes(image).decode('utf-8')
709
+
710
+ if image_path.startswith('image-history: '):
711
+ his_idx.append(idx)
712
+ image_path = image_path.replace('image-history: ', '')
713
+ his_list = self.imgtoken_dict[image_path][-self.his_len:] # t0 - tn-1
714
+ assert len(his_list) > 0, his_list
715
+
716
+ his_images.extend(his_list)
717
+ his_image_temp.append(his_list)
718
+
719
+ else:
720
+ now_images.append(image_path)
721
+
722
+ now_images = self.visual.encode(now_images)
723
+
724
+ if len(his_images) > 0:
725
+ his_images = self.visual.encode(his_images)
726
+ his_tkn = None
727
+
728
+ start_pos = 0
729
+ for his_scr in his_image_temp:
730
+ his_len = len(his_scr)
731
+ his_img_feature = his_images[start_pos: start_pos + his_len] # [b, l, d]
732
+ if USE_RESAMPLER:
733
+ his_img_feature = his_img_feature.reshape(1, -1, his_img_feature.size(-1))
734
+ his_vis_tkn = self.his_resampler(his_img_feature) # [l, d]
735
+ else:
736
+ raise ValueError("You cannot run without History Redsampler!")
737
+ his_tkn = his_vis_tkn if his_tkn is None else torch.concat((his_tkn, his_vis_tkn), dim=0)
738
+ start_pos += his_len
739
+ assert start_pos == len(his_images)
740
+ his_images = his_tkn
741
+
742
+ now_p, his_p = 0, 0
743
+ for j in range(len(img_pos)):
744
+ if j not in his_idx:
745
+ images.append(now_images[now_p])
746
+ now_p += 1
747
+ else:
748
+ images.append(his_images[his_p])
749
+ his_p += 1
750
+ images = torch.stack(images, dim=0)
751
+ assert len(images) == len(img_pos) == len(now_images) + len(his_images)
752
+
753
+ fake_images = None
754
+ elif self.training:
755
+ fake_images=torch.zeros(1,3,224,224).to(
756
+ dtype=self.visual.conv1.weight.dtype, device=self.visual.conv1.weight.device)
757
+ images = self.visual(fake_images)
758
+ else:
759
+ fake_images = None
760
+ images = None
761
+
762
+ output_attentions = (
763
+ output_attentions
764
+ if output_attentions is not None
765
+ else self.config.output_attentions
766
+ )
767
+ output_hidden_states = (
768
+ output_hidden_states
769
+ if output_hidden_states is not None
770
+ else self.config.output_hidden_states
771
+ )
772
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
773
+ return_dict = (
774
+ return_dict if return_dict is not None else self.config.use_return_dict
775
+ )
776
+
777
+ if input_ids is not None and inputs_embeds is not None:
778
+ raise ValueError(
779
+ "You cannot specify both input_ids and inputs_embeds at the same time"
780
+ )
781
+ elif input_ids is not None:
782
+ input_shape = input_ids.size()
783
+ input_ids = input_ids.view(-1, input_shape[-1])
784
+ batch_size = input_ids.shape[0]
785
+ elif inputs_embeds is not None:
786
+ input_shape = inputs_embeds.size()[:-1]
787
+ batch_size = inputs_embeds.shape[0]
788
+ else:
789
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
790
+
791
+
792
+ if token_type_ids is not None:
793
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
794
+ if position_ids is not None:
795
+ position_ids = position_ids.view(-1, input_shape[-1])
796
+
797
+ if past_key_values is None:
798
+ past_length = 0
799
+ past_key_values = tuple([None] * len(self.h))
800
+ else:
801
+ past_length = past_key_values[0][0].size(-2)
802
+
803
+ if position_ids is None:
804
+ position_ids = torch.arange(
805
+ past_length,
806
+ input_shape[-1] + past_length,
807
+ dtype=torch.long,
808
+ device=device,
809
+ )
810
+ position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
811
+
812
+ encoder_attention_mask = None
813
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
814
+
815
+ if inputs_embeds is None:
816
+ inputs_embeds = self.wte(input_ids)
817
+
818
+ if batch_size <= 0:
819
+ raise ValueError("batch_size has to be defined and > 0")
820
+ attention_mask = self._prepare_decoder_attention_mask(
821
+ attention_mask, input_shape, inputs_embeds, past_length
822
+ )
823
+
824
+ hidden_states = inputs_embeds
825
+
826
+ kv_seq_len = hidden_states.size()[1]
827
+ if past_key_values[0] is not None:
828
+ # past key values[0][0] shape: bs * seq_len * head_num * dim
829
+ kv_seq_len += past_key_values[0][0].shape[1]
830
+ if (
831
+ self.use_dynamic_ntk
832
+ and kv_seq_len == hidden_states.size()[1]
833
+ and not self.training
834
+ ):
835
+ context_value = math.log(kv_seq_len / self.seq_length, 2) + 1
836
+ ntk_alpha = 2 ** math.ceil(context_value) - 1
837
+ ntk_alpha = max(ntk_alpha, 1)
838
+ else:
839
+ ntk_alpha = self.rotary_emb._ntk_alpha_cached
840
+
841
+ rotary_pos_emb = self.rotary_emb(kv_seq_len, ntk_alpha=ntk_alpha)
842
+ for idx in range(len(rotary_pos_emb)):
843
+ rotary_pos_emb[idx] = rotary_pos_emb[idx].to(hidden_states.device)
844
+ hidden_states = self.drop(hidden_states).clone()
845
+
846
+ if fake_images is not None:
847
+ hidden_states = hidden_states + images.mean()*0
848
+ elif images is not None:
849
+ for idx, (i, a, b) in enumerate(img_pos):
850
+ hidden_states[i][a + 1 : b] = images[idx]
851
+ output_shape = input_shape + (hidden_states.size(-1),)
852
+
853
+ if self.gradient_checkpointing and self.training:
854
+ if use_cache:
855
+ logger.warning_once(
856
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
857
+ )
858
+ use_cache = False
859
+
860
+ presents = () if use_cache else None
861
+ all_self_attentions = () if output_attentions else None
862
+ all_hidden_states = () if output_hidden_states else None
863
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
864
+
865
+ if output_hidden_states:
866
+ all_hidden_states = all_hidden_states + (hidden_states,)
867
+
868
+ if self.gradient_checkpointing and self.training:
869
+
870
+ def create_custom_forward(module):
871
+ def custom_forward(*inputs):
872
+ # None for past_key_value
873
+ return module(*inputs, use_cache, output_attentions)
874
+
875
+ return custom_forward
876
+
877
+ outputs = torch.utils.checkpoint.checkpoint(
878
+ create_custom_forward(block),
879
+ hidden_states,
880
+ rotary_pos_emb,
881
+ self.registered_causal_mask,
882
+ None,
883
+ attention_mask,
884
+ head_mask[i],
885
+ encoder_hidden_states,
886
+ encoder_attention_mask,
887
+ )
888
+ else:
889
+ outputs = block(
890
+ hidden_states,
891
+ layer_past=layer_past,
892
+ rotary_pos_emb=rotary_pos_emb,
893
+ registered_causal_mask=self.registered_causal_mask,
894
+ attention_mask=attention_mask,
895
+ head_mask=head_mask[i],
896
+ encoder_hidden_states=encoder_hidden_states,
897
+ encoder_attention_mask=encoder_attention_mask,
898
+ use_cache=use_cache,
899
+ output_attentions=output_attentions,
900
+ )
901
+
902
+ hidden_states = outputs[0]
903
+ if use_cache is True:
904
+ presents = presents + (outputs[1],)
905
+
906
+ if output_attentions:
907
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
908
+
909
+ hidden_states = self.ln_f(hidden_states)
910
+ hidden_states = hidden_states.view(output_shape)
911
+ # Add last hidden state
912
+ if output_hidden_states:
913
+ all_hidden_states = all_hidden_states + (hidden_states,)
914
+
915
+ if not return_dict:
916
+ return tuple(
917
+ v for v in [hidden_states, presents, all_hidden_states] if v is not None
918
+ )
919
+
920
+ return BaseModelOutputWithPast(
921
+ last_hidden_state=hidden_states,
922
+ past_key_values=presents,
923
+ hidden_states=all_hidden_states,
924
+ attentions=all_self_attentions,
925
+ )
926
+
927
+
928
+ class QWenLMHeadModel(QWenPreTrainedModel):
929
+ _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.rotary_emb\.inv_freq"]
930
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.masked_bias"]
931
+
932
+ def __init__(self, config):
933
+ super().__init__(config)
934
+ assert (
935
+ config.bf16 + config.fp16 + config.fp32 <= 1
936
+ ), "Only one of \"bf16\", \"fp16\", \"fp32\" can be true"
937
+
938
+ autoset_precision = config.bf16 + config.fp16 + config.fp32 == 0
939
+
940
+ if autoset_precision:
941
+ if SUPPORT_BF16:
942
+ logger.warn(
943
+ "The model is automatically converting to bf16 for faster inference. "
944
+ "If you want to disable the automatic precision, please manually add bf16/fp16/fp32=True to \"AutoModelForCausalLM.from_pretrained\"."
945
+ )
946
+ config.bf16 = True
947
+ elif SUPPORT_FP16:
948
+ logger.warn(
949
+ "The model is automatically converting to fp16 for faster inference. "
950
+ "If you want to disable the automatic precision, please manually add bf16/fp16/fp32=True to \"AutoModelForCausalLM.from_pretrained\"."
951
+ )
952
+ config.fp16 = True
953
+ else:
954
+ config.fp32 = True
955
+
956
+ if config.bf16 and SUPPORT_CUDA and not SUPPORT_BF16:
957
+ logger.warn("Your device does NOT seem to support bf16, you can switch to fp16 or fp32 by by passing fp16/fp32=True in \"AutoModelForCausalLM.from_pretrained\".")
958
+ if config.fp16 and SUPPORT_CUDA and not SUPPORT_FP16:
959
+ logger.warn("Your device does NOT support faster inference with fp16, please switch to fp32 which is likely to be faster")
960
+ if config.fp32:
961
+ if SUPPORT_BF16:
962
+ logger.warn("Your device support faster inference by passing bf16=True in \"AutoModelForCausalLM.from_pretrained\".")
963
+ elif SUPPORT_FP16:
964
+ logger.warn("Your device support faster inference by passing fp16=True in \"AutoModelForCausalLM.from_pretrained\".")
965
+
966
+ self.transformer = QWenModel(config)
967
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
968
+
969
+ if config.bf16:
970
+ self.transformer.bfloat16()
971
+ self.lm_head.bfloat16()
972
+ if config.fp16:
973
+ self.transformer.half()
974
+ self.lm_head.half()
975
+ self.post_init()
976
+
977
+ def get_output_embeddings(self):
978
+ return self.lm_head
979
+
980
+ def set_output_embeddings(self, new_embeddings):
981
+ self.lm_head = new_embeddings
982
+
983
+ def prepare_inputs_for_generation(
984
+ self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs
985
+ ):
986
+ token_type_ids = kwargs.get("token_type_ids", None)
987
+ if past_key_values:
988
+ input_ids = input_ids[:, -1].unsqueeze(-1)
989
+ if token_type_ids is not None:
990
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
991
+
992
+ attention_mask = kwargs.get("attention_mask", None)
993
+ position_ids = kwargs.get("position_ids", None)
994
+
995
+ if attention_mask is not None and position_ids is None:
996
+ position_ids = attention_mask.long().cumsum(-1) - 1
997
+ position_ids.masked_fill_(attention_mask == 0, 1)
998
+ if past_key_values:
999
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1000
+ else:
1001
+ position_ids = None
1002
+
1003
+ if inputs_embeds is not None and past_key_values is None:
1004
+ model_inputs = {"inputs_embeds": inputs_embeds}
1005
+ else:
1006
+ model_inputs = {"input_ids": input_ids}
1007
+
1008
+ model_inputs.update(
1009
+ {
1010
+ "past_key_values": past_key_values,
1011
+ "use_cache": kwargs.get("use_cache"),
1012
+ "position_ids": position_ids,
1013
+ "attention_mask": attention_mask,
1014
+ "token_type_ids": token_type_ids,
1015
+ }
1016
+ )
1017
+ return model_inputs
1018
+
1019
+ def forward(
1020
+ self,
1021
+ input_ids: Optional[torch.LongTensor] = None,
1022
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1023
+ attention_mask: Optional[torch.FloatTensor] = None,
1024
+ token_type_ids: Optional[torch.LongTensor] = None,
1025
+ position_ids: Optional[torch.LongTensor] = None,
1026
+ head_mask: Optional[torch.FloatTensor] = None,
1027
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1028
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1029
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
1030
+ labels: Optional[torch.LongTensor] = None,
1031
+ use_cache: Optional[bool] = None,
1032
+ output_attentions: Optional[bool] = None,
1033
+ output_hidden_states: Optional[bool] = None,
1034
+ return_dict: Optional[bool] = None,
1035
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1036
+
1037
+ return_dict = (
1038
+ return_dict if return_dict is not None else self.config.use_return_dict
1039
+ )
1040
+
1041
+ transformer_outputs = self.transformer(
1042
+ input_ids,
1043
+ past_key_values=past_key_values,
1044
+ attention_mask=attention_mask,
1045
+ token_type_ids=token_type_ids,
1046
+ position_ids=position_ids,
1047
+ head_mask=head_mask,
1048
+ inputs_embeds=inputs_embeds,
1049
+ encoder_hidden_states=encoder_hidden_states,
1050
+ encoder_attention_mask=encoder_attention_mask,
1051
+ use_cache=use_cache,
1052
+ output_attentions=output_attentions,
1053
+ output_hidden_states=output_hidden_states,
1054
+ return_dict=return_dict,
1055
+ )
1056
+ hidden_states = transformer_outputs[0]
1057
+
1058
+ lm_logits = self.lm_head(hidden_states)
1059
+
1060
+ loss = None
1061
+ if labels is not None:
1062
+ labels = labels.to(lm_logits.device)
1063
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1064
+ shift_labels = labels[..., 1:].contiguous()
1065
+ loss_fct = CrossEntropyLoss()
1066
+ loss = loss_fct(
1067
+ shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)
1068
+ )
1069
+
1070
+ if not return_dict:
1071
+ output = (lm_logits,) + transformer_outputs[1:]
1072
+ return ((loss,) + output) if loss is not None else output
1073
+
1074
+ return CausalLMOutputWithPast(
1075
+ loss=loss,
1076
+ logits=lm_logits,
1077
+ past_key_values=transformer_outputs.past_key_values,
1078
+ hidden_states=transformer_outputs.hidden_states,
1079
+ attentions=transformer_outputs.attentions,
1080
+ )
1081
+
1082
+ @staticmethod
1083
+ def _reorder_cache(
1084
+ past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
1085
+ ) -> Tuple[Tuple[torch.Tensor]]:
1086
+
1087
+ return tuple(
1088
+ tuple(
1089
+ past_state.index_select(0, beam_idx.to(past_state.device))
1090
+ for past_state in layer_past
1091
+ )
1092
+ for layer_past in past_key_values
1093
+ )
1094
+
1095
+ def chat(
1096
+ self,
1097
+ tokenizer: PreTrainedTokenizer,
1098
+ query: str,
1099
+ history: Optional[HistoryType],
1100
+ system: str = "You are a helpful assistant.",
1101
+ append_history: bool = True,
1102
+ stream: Optional[bool] = _SENTINEL,
1103
+ stop_words_ids: Optional[List[List[int]]] = None,
1104
+ generation_config: Optional[GenerationConfig] = None,
1105
+ **kwargs,
1106
+ ) -> Tuple[str, HistoryType]:
1107
+ generation_config = generation_config if generation_config is not None else self.generation_config
1108
+
1109
+ assert stream is _SENTINEL, _ERROR_STREAM_IN_CHAT
1110
+ assert generation_config.chat_format == 'chatml', _ERROR_BAD_CHAT_FORMAT
1111
+ if history is None:
1112
+ history = []
1113
+ if stop_words_ids is None:
1114
+ stop_words_ids = []
1115
+
1116
+ max_window_size = kwargs.get('max_window_size', None)
1117
+ if max_window_size is None:
1118
+ max_window_size = generation_config.max_window_size
1119
+ raw_text, context_tokens = make_context(
1120
+ tokenizer,
1121
+ query,
1122
+ history=history,
1123
+ system=system,
1124
+ max_window_size=max_window_size,
1125
+ chat_format=generation_config.chat_format,
1126
+ )
1127
+
1128
+ stop_words_ids.extend(get_stop_words_ids(
1129
+ generation_config.chat_format, tokenizer
1130
+ ))
1131
+ input_ids = torch.tensor([context_tokens]).to(self.device)
1132
+ outputs = self.generate(
1133
+ input_ids,
1134
+ stop_words_ids=stop_words_ids,
1135
+ return_dict_in_generate=False,
1136
+ generation_config=generation_config,
1137
+ **kwargs,
1138
+ )
1139
+
1140
+ response = decode_tokens(
1141
+ outputs[0],
1142
+ tokenizer,
1143
+ raw_text_len=len(raw_text),
1144
+ context_length=len(context_tokens),
1145
+ chat_format=generation_config.chat_format,
1146
+ verbose=False,
1147
+ errors='replace'
1148
+ )
1149
+
1150
+ if append_history:
1151
+ history.append((query, response))
1152
+
1153
+ return response, history
1154
+
1155
+ def chat_stream(
1156
+ self,
1157
+ tokenizer: PreTrainedTokenizer,
1158
+ query: str,
1159
+ history: Optional[HistoryType],
1160
+ system: str = "You are a helpful assistant.",
1161
+ stop_words_ids: Optional[List[List[int]]] = None,
1162
+ logits_processor: Optional[LogitsProcessorList] = None,
1163
+ generation_config: Optional[GenerationConfig] = None,
1164
+ **kwargs,
1165
+ ) -> Generator[str, Any, None]:
1166
+ generation_config = generation_config if generation_config is not None else self.generation_config
1167
+ assert generation_config.chat_format == 'chatml', _ERROR_BAD_CHAT_FORMAT
1168
+ if history is None:
1169
+ history = []
1170
+ if stop_words_ids is None:
1171
+ stop_words_ids = []
1172
+
1173
+ max_window_size = kwargs.get('max_window_size', None)
1174
+ if max_window_size is None:
1175
+ max_window_size = generation_config.max_window_size
1176
+ raw_text, context_tokens = make_context(
1177
+ tokenizer,
1178
+ query,
1179
+ history=history,
1180
+ system=system,
1181
+ max_window_size=max_window_size,
1182
+ chat_format=generation_config.chat_format,
1183
+ )
1184
+
1185
+ stop_words_ids.extend(get_stop_words_ids(
1186
+ generation_config.chat_format, tokenizer
1187
+ ))
1188
+ if stop_words_ids is not None:
1189
+ stop_words_logits_processor = StopWordsLogitsProcessor(
1190
+ stop_words_ids=stop_words_ids,
1191
+ eos_token_id=generation_config.eos_token_id,
1192
+ )
1193
+ if logits_processor is None:
1194
+ logits_processor = LogitsProcessorList([stop_words_logits_processor])
1195
+ else:
1196
+ logits_processor.append(stop_words_logits_processor)
1197
+ input_ids = torch.tensor([context_tokens]).to(self.device)
1198
+
1199
+ from transformers_stream_generator.main import NewGenerationMixin, StreamGenerationConfig
1200
+ self.__class__.generate_stream = NewGenerationMixin.generate
1201
+ self.__class__.sample_stream = NewGenerationMixin.sample_stream
1202
+ stream_config = StreamGenerationConfig(**generation_config.to_dict(), do_stream=True)
1203
+
1204
+ def stream_generator():
1205
+ outputs = []
1206
+ for token in self.generate_stream(
1207
+ input_ids,
1208
+ return_dict_in_generate=False,
1209
+ generation_config=stream_config,
1210
+ logits_processor=logits_processor,
1211
+ seed=-1,
1212
+ **kwargs):
1213
+ outputs.append(token.item())
1214
+ yield tokenizer.decode(outputs, skip_special_tokens=True, errors='ignore', keep_image_special=True)
1215
+
1216
+ return stream_generator()
1217
+
1218
+ def generate(
1219
+ self,
1220
+ inputs: Optional[torch.Tensor] = None,
1221
+ generation_config: Optional[GenerationConfig] = None,
1222
+ logits_processor: Optional[LogitsProcessorList] = None,
1223
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
1224
+ prefix_allowed_tokens_fn: Optional[
1225
+ Callable[[int, torch.Tensor], List[int]]
1226
+ ] = None,
1227
+ synced_gpus: Optional[bool] = None,
1228
+ assistant_model: Optional["PreTrainedModel"] = None,
1229
+ streamer: Optional["BaseStreamer"] = None,
1230
+ **kwargs,
1231
+ ) -> Union[GenerateOutput, torch.LongTensor]:
1232
+ generation_config = generation_config if generation_config is not None else self.generation_config
1233
+
1234
+ # Process stop_words_ids.
1235
+ stop_words_ids = kwargs.pop("stop_words_ids", None)
1236
+ if stop_words_ids is None and generation_config is not None:
1237
+ stop_words_ids = getattr(generation_config, "stop_words_ids", None)
1238
+ if stop_words_ids is None:
1239
+ stop_words_ids = getattr(generation_config, "stop_words_ids", None)
1240
+
1241
+ if stop_words_ids is not None:
1242
+ stop_words_logits_processor = StopWordsLogitsProcessor(
1243
+ stop_words_ids=stop_words_ids,
1244
+ eos_token_id=generation_config.eos_token_id,
1245
+ )
1246
+ if logits_processor is None:
1247
+ logits_processor = LogitsProcessorList([stop_words_logits_processor])
1248
+ else:
1249
+ logits_processor.append(stop_words_logits_processor)
1250
+
1251
+ return super().generate(
1252
+ inputs,
1253
+ generation_config=generation_config,
1254
+ logits_processor=logits_processor,
1255
+ stopping_criteria=stopping_criteria,
1256
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1257
+ synced_gpus=synced_gpus,
1258
+ assistant_model=assistant_model,
1259
+ streamer=streamer,
1260
+ **kwargs,
1261
+ )
1262
+
1263
+
1264
+ class RotaryEmbedding(torch.nn.Module):
1265
+ def __init__(self, dim, base=10000):
1266
+ super().__init__()
1267
+ self.dim = dim
1268
+ self.base = base
1269
+ self.inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
1270
+ if importlib.util.find_spec("einops") is None:
1271
+ raise RuntimeError("einops is required for Rotary Embedding")
1272
+
1273
+ self._rotary_pos_emb_cache = None
1274
+ self._seq_len_cached = 0
1275
+ self._ntk_alpha_cached = 1.0
1276
+
1277
+ def update_rotary_pos_emb_cache(self, max_seq_len, offset=0, ntk_alpha=1.0):
1278
+ seqlen = max_seq_len + offset
1279
+ if seqlen > self._seq_len_cached or ntk_alpha != self._ntk_alpha_cached:
1280
+ base = self.base * ntk_alpha ** (self.dim / (self.dim - 2))
1281
+ self.inv_freq = 1.0 / (
1282
+ base
1283
+ ** (
1284
+ torch.arange(0, self.dim, 2, device=self.inv_freq.device).float()
1285
+ / self.dim
1286
+ )
1287
+ )
1288
+ self._seq_len_cached = max(2 * seqlen, 16)
1289
+ self._ntk_alpha_cached = ntk_alpha
1290
+ seq = torch.arange(self._seq_len_cached, device=self.inv_freq.device)
1291
+ freqs = torch.outer(seq.type_as(self.inv_freq), self.inv_freq)
1292
+
1293
+ emb = torch.cat((freqs, freqs), dim=-1)
1294
+ from einops import rearrange
1295
+
1296
+ emb = rearrange(emb, "n d -> 1 n 1 d")
1297
+
1298
+ cos, sin = emb.cos(), emb.sin()
1299
+ self._rotary_pos_emb_cache = [cos, sin]
1300
+
1301
+ def forward(self, max_seq_len, offset=0, ntk_alpha=1.0):
1302
+ self.update_rotary_pos_emb_cache(max_seq_len, offset, ntk_alpha)
1303
+ cos, sin = self._rotary_pos_emb_cache
1304
+ return [cos[:, offset : offset + max_seq_len], sin[:, offset : offset + max_seq_len]]
1305
+
1306
+
1307
+ def _rotate_half(x):
1308
+ from einops import rearrange
1309
+
1310
+ x = rearrange(x, "... (j d) -> ... j d", j=2)
1311
+ x1, x2 = x.unbind(dim=-2)
1312
+ return torch.cat((-x2, x1), dim=-1)
1313
+
1314
+
1315
+ def apply_rotary_pos_emb(t, freqs):
1316
+ cos, sin = freqs
1317
+ if apply_rotary_emb_func is not None and t.is_cuda:
1318
+ t_ = t.float()
1319
+ cos = cos.squeeze(0).squeeze(1)[:, : cos.shape[-1] // 2]
1320
+ sin = sin.squeeze(0).squeeze(1)[:, : sin.shape[-1] // 2]
1321
+ output = apply_rotary_emb_func(t_, cos, sin).type_as(t)
1322
+ return output
1323
+ else:
1324
+ rot_dim = freqs[0].shape[-1]
1325
+ cos, sin = freqs
1326
+ t_, t_pass_ = t[..., :rot_dim], t[..., rot_dim:]
1327
+ t_ = t_.float()
1328
+ t_pass_ = t_pass_.float()
1329
+ t_ = (t_ * cos) + (_rotate_half(t_) * sin)
1330
+ return torch.cat((t_, t_pass_), dim=-1).type_as(t)
1331
+
1332
+
1333
+ class RMSNorm(torch.nn.Module):
1334
+ def __init__(self, dim: int, eps: float = 1e-6):
1335
+ super().__init__()
1336
+ self.eps = eps
1337
+ self.weight = nn.Parameter(torch.ones(dim))
1338
+
1339
+ def _norm(self, x):
1340
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
1341
+
1342
+ def forward(self, x):
1343
+ if rms_norm is not None and x.is_cuda:
1344
+ return rms_norm(x, self.weight, self.eps)
1345
+ else:
1346
+ output = self._norm(x.float()).type_as(x)
1347
+ return output * self.weight
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e78548361c1a8f10b8abcc410b6fd9c273e152d03ef0c2312dbdd58fdb8f1392
3
+ size 19486169385
qwen.tiktoken ADDED
The diff for this file is too large to render. See raw diff
 
special_tokens_map.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "pad_token": "<|endoftext|>"
3
+ }
tokenization_qwen.py ADDED
@@ -0,0 +1,598 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.colors as mcolors
24
+ from matplotlib.font_manager import FontProperties
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ VOCAB_FILES_NAMES = {"vocab_file": "qwen.tiktoken", "ttf": "SimSun.ttf"}
30
+ FONT_PATH = try_to_load_from_cache("Qwen/Qwen-VL-Chat", "SimSun.ttf")
31
+ if FONT_PATH is None:
32
+ if not os.path.exists("SimSun.ttf"):
33
+ ttf = requests.get("https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/SimSun.ttf")
34
+ open("SimSun.ttf", "wb").write(ttf.content)
35
+ FONT_PATH = "SimSun.ttf"
36
+
37
+ 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+"""
38
+ ENDOFTEXT = "<|endoftext|>"
39
+ IMSTART = "<|im_start|>"
40
+ IMEND = "<|im_end|>"
41
+ # as the default behavior is changed to allow special tokens in
42
+ # regular texts, the surface forms of special tokens need to be
43
+ # as different as possible to minimize the impact
44
+ EXTRAS = tuple((f"<|extra_{i}|>" for i in range(205)))
45
+ SPECIAL_TOKENS = (
46
+ ENDOFTEXT,
47
+ IMSTART,
48
+ IMEND,
49
+ ) + EXTRAS
50
+ IMG_TOKEN_SPAN = 256
51
+
52
+
53
+ def _load_tiktoken_bpe(tiktoken_bpe_file: str) -> Dict[bytes, int]:
54
+ with open(tiktoken_bpe_file, "rb") as f:
55
+ contents = f.read()
56
+ return {
57
+ base64.b64decode(token): int(rank)
58
+ for token, rank in (line.split() for line in contents.splitlines() if line)
59
+ }
60
+
61
+ def _list_find(
62
+ input_list: List[Any],
63
+ candidates: Tuple[Any],
64
+ start: int = 0,
65
+ ):
66
+ for i in range(start, len(input_list)):
67
+ if input_list[i] in candidates:
68
+ return i
69
+ return -1
70
+
71
+ def _replace_closed_tag(
72
+ input_tokens: List[Any],
73
+ start_tags: Union[Any, Tuple[Any]],
74
+ end_tags: Union[Any, Tuple[Any]],
75
+ inclusive_replace_func: Callable,
76
+ exclusive_replace_func: Callable = lambda x: x,
77
+ ):
78
+ if isinstance(start_tags, (str, int)):
79
+ start_tags = (start_tags,)
80
+ if isinstance(end_tags, (str, int)):
81
+ end_tags = (end_tags,)
82
+ assert len(start_tags) == len(end_tags)
83
+
84
+ output_tokens = []
85
+ end = 0
86
+ while True:
87
+ start = _list_find(input_tokens, start_tags, end)
88
+ if start == -1:
89
+ break
90
+ output_tokens.extend(exclusive_replace_func(input_tokens[end : start]))
91
+ tag_idx = start_tags.index(input_tokens[start])
92
+ end = _list_find(input_tokens, (end_tags[tag_idx],), start)
93
+ if end == -1:
94
+ raise ValueError("Unclosed image token")
95
+ output_tokens.extend(inclusive_replace_func(input_tokens[start : end + 1]))
96
+ end += 1
97
+ output_tokens.extend(exclusive_replace_func(input_tokens[end : ]))
98
+ return output_tokens
99
+
100
+ class QWenTokenizer(PreTrainedTokenizer):
101
+ """QWen tokenizer."""
102
+
103
+ vocab_files_names = VOCAB_FILES_NAMES
104
+
105
+ def __init__(
106
+ self,
107
+ vocab_file,
108
+ errors="replace",
109
+ image_start_tag='<img>',
110
+ image_end_tag='</img>',
111
+ image_pad_tag='<imgpad>',
112
+ ref_start_tag='<ref>',
113
+ ref_end_tag='</ref>',
114
+ box_start_tag='<box>',
115
+ box_end_tag='</box>',
116
+ quad_start_tag='<quad>',
117
+ quad_end_tag='</quad>',
118
+ **kwargs,
119
+ ):
120
+ super().__init__(**kwargs)
121
+ self.image_start_tag = image_start_tag
122
+ self.image_end_tag = image_end_tag
123
+ self.image_pad_tag = image_pad_tag
124
+ self.ref_start_tag = ref_start_tag
125
+ self.ref_end_tag = ref_end_tag
126
+ self.box_start_tag = box_start_tag
127
+ self.box_end_tag = box_end_tag
128
+ self.quad_start_tag = quad_start_tag
129
+ self.quad_end_tag = quad_end_tag
130
+ self.IMAGE_ST = (
131
+ ref_start_tag, ref_end_tag,
132
+ box_start_tag, box_end_tag,
133
+ quad_start_tag, quad_end_tag,
134
+ image_start_tag, image_end_tag,
135
+ image_pad_tag
136
+ )
137
+
138
+ self.errors = errors # how to handle errors in decoding
139
+
140
+ self.mergeable_ranks = _load_tiktoken_bpe(vocab_file) # type: dict[bytes, int]
141
+ self.special_tokens = {
142
+ token: index
143
+ for index, token in enumerate(
144
+ SPECIAL_TOKENS + self.IMAGE_ST, start=len(self.mergeable_ranks)
145
+ )
146
+ }
147
+ self.img_start_id = self.special_tokens[self.image_start_tag]
148
+ self.img_end_id = self.special_tokens[self.image_end_tag]
149
+ self.img_pad_id = self.special_tokens[self.image_pad_tag]
150
+ self.ref_start_id = self.special_tokens[self.ref_start_tag]
151
+ self.ref_end_id = self.special_tokens[self.ref_end_tag]
152
+ self.box_start_id = self.special_tokens[self.box_start_tag]
153
+ self.box_end_id = self.special_tokens[self.box_end_tag]
154
+ self.quad_start_id = self.special_tokens[self.quad_start_tag]
155
+ self.quad_end_id = self.special_tokens[self.quad_end_tag]
156
+ self.image_special_tokens = set([
157
+ self.ref_start_id, self.ref_end_id, self.box_start_id, self.box_end_id,
158
+ self.quad_start_id, self.quad_end_id,
159
+ ])
160
+
161
+ enc = tiktoken.Encoding(
162
+ "Qwen",
163
+ pat_str=PAT_STR,
164
+ mergeable_ranks=self.mergeable_ranks,
165
+ special_tokens=self.special_tokens,
166
+ )
167
+ assert (
168
+ len(self.mergeable_ranks) + len(self.special_tokens) == enc.n_vocab
169
+ ), f"{len(self.mergeable_ranks) + len(self.special_tokens)} != {enc.n_vocab} in encoding"
170
+
171
+ self.decoder = {
172
+ v: k for k, v in self.mergeable_ranks.items()
173
+ } # type: dict[int, bytes|str]
174
+ self.decoder.update({v: k for k, v in self.special_tokens.items()})
175
+
176
+ self.tokenizer = enc # type: tiktoken.Encoding
177
+
178
+ self.eod_id = self.tokenizer.eot_token
179
+ self.im_start_id = self.special_tokens[IMSTART]
180
+ self.im_end_id = self.special_tokens[IMEND]
181
+
182
+ def __getstate__(self):
183
+ # for pickle lovers
184
+ state = self.__dict__.copy()
185
+ del state['tokenizer']
186
+ return state
187
+
188
+ def __setstate__(self, state):
189
+ # tokenizer is not python native; don't pass it; rebuild it
190
+ self.__dict__.update(state)
191
+ enc = tiktoken.Encoding(
192
+ "Qwen",
193
+ pat_str=PAT_STR,
194
+ mergeable_ranks=self.mergeable_ranks,
195
+ special_tokens=self.special_tokens,
196
+ )
197
+ self.tokenizer = enc
198
+
199
+
200
+ def __len__(self) -> int:
201
+ return self.tokenizer.n_vocab
202
+
203
+ def get_vocab(self) -> Dict[bytes, int]:
204
+ return self.mergeable_ranks
205
+
206
+ def convert_tokens_to_ids(
207
+ self, tokens: Union[bytes, str, List[Union[bytes, str]]]
208
+ ) -> List[int]:
209
+ ids = []
210
+ if isinstance(tokens, (str, bytes)):
211
+ if tokens in self.special_tokens:
212
+ return self.special_tokens[tokens]
213
+ else:
214
+ return self.mergeable_ranks.get(tokens)
215
+ for token in tokens:
216
+ if token in self.special_tokens:
217
+ ids.append(self.special_tokens[token])
218
+ else:
219
+ ids.append(self.mergeable_ranks.get(token))
220
+ return ids
221
+
222
+ def _add_tokens(self, new_tokens: Union[List[str], List[AddedToken]], special_tokens: bool = False) -> int:
223
+ if not special_tokens and new_tokens:
224
+ raise ValueError('Adding regular tokens is not supported')
225
+ for token in new_tokens:
226
+ surface_form = token.content if isinstance(token, AddedToken) else token
227
+ if surface_form not in SPECIAL_TOKENS + self.IMAGE_ST:
228
+ raise ValueError('Adding unknown special tokens is not supported')
229
+ return 0
230
+
231
+ def save_vocabulary(self, save_directory: str, **kwargs) -> Tuple[str]:
232
+ """
233
+ Save only the vocabulary of the tokenizer (vocabulary).
234
+
235
+ Returns:
236
+ `Tuple(str)`: Paths to the files saved.
237
+ """
238
+ file_path = os.path.join(save_directory, "qwen.tiktoken")
239
+ with open(file_path, "w", encoding="utf8") as w:
240
+ for k, v in self.mergeable_ranks.items():
241
+ line = base64.b64encode(k).decode("utf8") + " " + str(v) + "\n"
242
+ w.write(line)
243
+ return (file_path,)
244
+
245
+ def tokenize(
246
+ self,
247
+ text: str,
248
+ allowed_special: Union[Set, str] = "all",
249
+ disallowed_special: Union[Collection, str] = (),
250
+ **kwargs,
251
+ ) -> List[Union[bytes, str]]:
252
+ """
253
+ Converts a string in a sequence of tokens.
254
+
255
+ Args:
256
+ text (`str`):
257
+ The sequence to be encoded.
258
+ allowed_special (`Literal["all"]` or `set`):
259
+ The surface forms of the tokens to be encoded as special tokens in regular texts.
260
+ Default to "all".
261
+ disallowed_special (`Literal["all"]` or `Collection`):
262
+ The surface forms of the tokens that should not be in regular texts and trigger errors.
263
+ Default to an empty tuple.
264
+
265
+ kwargs (additional keyword arguments, *optional*):
266
+ Will be passed to the underlying model specific encode method.
267
+
268
+ Returns:
269
+ `List[bytes|str]`: The list of tokens.
270
+ """
271
+ tokens = []
272
+ text = unicodedata.normalize("NFC", text)
273
+
274
+ # this implementation takes a detour: text -> token id -> token surface forms
275
+ for t in self.tokenizer.encode(
276
+ text, allowed_special=allowed_special, disallowed_special=disallowed_special
277
+ ):
278
+ tokens.append(self.decoder[t])
279
+
280
+ def _encode_imgurl(img_tokens):
281
+ assert img_tokens[0] == self.image_start_tag and img_tokens[-1] == self.image_end_tag
282
+ img_tokens = img_tokens[1:-1]
283
+ img_url = b''.join(img_tokens)
284
+ out_img_tokens = list(map(self.decoder.get, img_url))
285
+ if len(out_img_tokens) > IMG_TOKEN_SPAN:
286
+ raise ValueError("The content in {}..{} is too long".format(
287
+ self.image_start_tag, self.image_end_tag))
288
+ out_img_tokens.extend([self.image_pad_tag] * (IMG_TOKEN_SPAN - len(out_img_tokens)))
289
+ out_img_tokens = [self.image_start_tag] + out_img_tokens + [self.image_end_tag]
290
+ return out_img_tokens
291
+
292
+ return _replace_closed_tag(tokens, self.image_start_tag, self.image_end_tag, _encode_imgurl)
293
+
294
+ def convert_tokens_to_string(self, tokens: List[Union[bytes, str]]) -> str:
295
+ """
296
+ Converts a sequence of tokens in a single string.
297
+ """
298
+ text = ""
299
+ temp = b""
300
+ for t in tokens:
301
+ if isinstance(t, str):
302
+ if temp:
303
+ text += temp.decode("utf-8", errors=self.errors)
304
+ temp = b""
305
+ text += t
306
+ elif isinstance(t, bytes):
307
+ temp += t
308
+ else:
309
+ raise TypeError("token should only be of type types or str")
310
+ if temp:
311
+ text += temp.decode("utf-8", errors=self.errors)
312
+ return text
313
+
314
+ @property
315
+ def vocab_size(self):
316
+ return self.tokenizer.n_vocab
317
+
318
+ def _convert_id_to_token(self, index: int) -> Union[bytes, str]:
319
+ """Converts an id to a token, special tokens included"""
320
+ if index in self.decoder:
321
+ return self.decoder[index]
322
+ raise ValueError("unknown ids")
323
+
324
+ def _convert_token_to_id(self, token: Union[bytes, str]) -> int:
325
+ """Converts a token to an id using the vocab, special tokens included"""
326
+ if token in self.special_tokens:
327
+ return self.special_tokens[token]
328
+ if token in self.mergeable_ranks:
329
+ return self.mergeable_ranks[token]
330
+ raise ValueError("unknown token")
331
+
332
+ def _tokenize(self, text: str, **kwargs):
333
+ """
334
+ Converts a string in a sequence of tokens (string), using the tokenizer. Split in words for word-based
335
+ vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces).
336
+
337
+ Do NOT take care of added tokens.
338
+ """
339
+ raise NotImplementedError
340
+
341
+ def _decode(
342
+ self,
343
+ token_ids: Union[int, List[int]],
344
+ skip_special_tokens: bool = False,
345
+ errors: str = None,
346
+ **kwargs,
347
+ ) -> str:
348
+ if isinstance(token_ids, int):
349
+ token_ids = [token_ids]
350
+
351
+ def _decode_imgurl(img_token_ids):
352
+ assert img_token_ids[0] == self.img_start_id and img_token_ids[-1] == self.img_end_id
353
+ img_token_ids = img_token_ids[1:-1]
354
+ img_token_ids = img_token_ids[ : img_token_ids.index(self.img_pad_id)]
355
+ img_url = bytes(img_token_ids).decode('utf-8')
356
+ return [self.img_start_id] + self.tokenizer.encode(img_url) + [self.img_end_id]
357
+
358
+ token_ids = _replace_closed_tag(token_ids, self.img_start_id, self.img_end_id, _decode_imgurl)
359
+
360
+ if skip_special_tokens:
361
+ if kwargs.get('keep_image_special', False):
362
+ token_ids = [i for i in token_ids if i < self.eod_id
363
+ or i in self.image_special_tokens]
364
+ else:
365
+ token_ids = [i for i in token_ids if i < self.eod_id]
366
+ return self.tokenizer.decode(token_ids, errors=errors or self.errors)
367
+
368
+ def to_list_format(self, text: str):
369
+ text = unicodedata.normalize("NFC", text)
370
+ token_ids = self.tokenizer.encode(
371
+ text, allowed_special=set(self.IMAGE_ST + (ENDOFTEXT,)))
372
+
373
+ def _encode_vl_info(tokens):
374
+ if len(tokens) == 0:
375
+ return []
376
+ if tokens[0] == self.img_start_id and tokens[-1] == self.img_end_id:
377
+ key = 'image'
378
+ elif tokens[0] == self.ref_start_id and tokens[-1] == self.ref_end_id:
379
+ key = 'ref'
380
+ elif tokens[0] == self.box_start_id and tokens[-1] == self.box_end_id:
381
+ key = 'box'
382
+ elif tokens[0] == self.quad_start_id and tokens[-1] == self.quad_end_id:
383
+ key = 'quad'
384
+ else:
385
+ _tobytes = lambda x: x.encode('utf-8') if isinstance(x, str) else x
386
+ return [{'text': b''.join(map(_tobytes, map(self.decoder.get, tokens))).decode('utf-8')}]
387
+ _tobytes = lambda x: x.encode('utf-8') if isinstance(x, str) else x
388
+ val = b''.join(map(_tobytes, map(self.decoder.get, tokens[1:-1]))).decode('utf-8')
389
+ return [{key: val}]
390
+
391
+ return _replace_closed_tag(
392
+ token_ids,
393
+ (self.img_start_id, self.ref_start_id, self.box_start_id, self.quad_start_id),
394
+ (self.img_end_id, self.ref_end_id, self.box_end_id, self.quad_end_id),
395
+ _encode_vl_info,
396
+ _encode_vl_info,
397
+ )
398
+
399
+ def from_list_format(self, list_format: List[Dict]):
400
+ text = ''
401
+ num_images = 0
402
+ for ele in list_format:
403
+ if 'image' in ele:
404
+ num_images += 1
405
+ text += f'Picture {num_images}: '
406
+ text += self.image_start_tag + ele['image'] + self.image_end_tag
407
+ text += '\n'
408
+ elif 'text' in ele:
409
+ text += ele['text']
410
+ elif 'box' in ele:
411
+ if 'ref' in ele:
412
+ text += self.ref_start_tag + ele['ref'] + self.ref_end_tag
413
+ for box in ele['box']:
414
+ text += self.box_start_tag + '(%d,%d),(%d,%d)' % (box[0], box[1], box[2], box[3]) + self.box_end_tag
415
+ else:
416
+ raise ValueError("Unsupport element: " + str(ele))
417
+ return text
418
+
419
+ def _fetch_latest_picture(self, response, history):
420
+ if history is None:
421
+ history = []
422
+ _history = history + [(response, None)]
423
+ for q, r in _history[::-1]:
424
+ for ele in self.to_list_format(q)[::-1]:
425
+ if 'image' in ele:
426
+ return ele['image']
427
+ return None
428
+
429
+ def _fetch_all_box_with_ref(self, text):
430
+ list_format = self.to_list_format(text)
431
+ output = []
432
+ for i, ele in enumerate(list_format):
433
+ if 'box' in ele:
434
+ bbox = tuple(map(int, ele['box'].replace('(', '').replace(')', '').split(',')))
435
+ assert len(bbox) == 4
436
+ output.append({'box': bbox})
437
+ if i > 0 and 'ref' in list_format[i-1]:
438
+ output[-1]['ref'] = list_format[i-1]['ref'].strip()
439
+ return output
440
+
441
+ def draw_bbox_on_latest_picture(
442
+ self,
443
+ response,
444
+ history=None,
445
+ ) -> Optional[Image.Image]:
446
+ image = self._fetch_latest_picture(response, history)
447
+ if image is None:
448
+ return None
449
+ if image.startswith("http://") or image.startswith("https://"):
450
+ image = Image.open(requests.get(image, stream=True).raw).convert("RGB")
451
+ h, w = image.height, image.width
452
+ else:
453
+ image = np.asarray(Image.open(image).convert("RGB"))
454
+ h, w = image.shape[0], image.shape[1]
455
+ visualizer = Visualizer(image)
456
+
457
+ boxes = self._fetch_all_box_with_ref(response)
458
+ if not boxes:
459
+ return None
460
+ color = random.choice([_ for _ in mcolors.TABLEAU_COLORS.keys()]) # init color
461
+ for box in boxes:
462
+ if 'ref' in box: # random new color for new refexps
463
+ color = random.choice([_ for _ in mcolors.TABLEAU_COLORS.keys()])
464
+ x1, y1, x2, y2 = box['box']
465
+ x1, y1, x2, y2 = (int(x1 / 1000 * w), int(y1 / 1000 * h), int(x2 / 1000 * w), int(y2 / 1000 * h))
466
+ visualizer.draw_box((x1, y1, x2, y2), alpha=1, edge_color=color)
467
+ if 'ref' in box:
468
+ visualizer.draw_text(box['ref'], (x1, y1), color=color, horizontal_alignment="left")
469
+ return visualizer.output
470
+
471
+
472
+ import colorsys
473
+ import logging
474
+ import math
475
+ import numpy as np
476
+ import matplotlib as mpl
477
+ import matplotlib.colors as mplc
478
+ import matplotlib.figure as mplfigure
479
+ import torch
480
+ from matplotlib.backends.backend_agg import FigureCanvasAgg
481
+ from PIL import Image
482
+ import random
483
+
484
+ logger = logging.getLogger(__name__)
485
+
486
+
487
+ class VisImage:
488
+ def __init__(self, img, scale=1.0):
489
+ self.img = img
490
+ self.scale = scale
491
+ self.width, self.height = img.shape[1], img.shape[0]
492
+ self._setup_figure(img)
493
+
494
+ def _setup_figure(self, img):
495
+ fig = mplfigure.Figure(frameon=False)
496
+ self.dpi = fig.get_dpi()
497
+ # add a small 1e-2 to avoid precision lost due to matplotlib's truncation
498
+ # (https://github.com/matplotlib/matplotlib/issues/15363)
499
+ fig.set_size_inches(
500
+ (self.width * self.scale + 1e-2) / self.dpi,
501
+ (self.height * self.scale + 1e-2) / self.dpi,
502
+ )
503
+ self.canvas = FigureCanvasAgg(fig)
504
+ # self.canvas = mpl.backends.backend_cairo.FigureCanvasCairo(fig)
505
+ ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
506
+ ax.axis("off")
507
+ self.fig = fig
508
+ self.ax = ax
509
+ self.reset_image(img)
510
+
511
+ def reset_image(self, img):
512
+ img = img.astype("uint8")
513
+ self.ax.imshow(img, extent=(0, self.width, self.height, 0), interpolation="nearest")
514
+
515
+ def save(self, filepath):
516
+ self.fig.savefig(filepath)
517
+
518
+ def get_image(self):
519
+ canvas = self.canvas
520
+ s, (width, height) = canvas.print_to_buffer()
521
+
522
+ buffer = np.frombuffer(s, dtype="uint8")
523
+
524
+ img_rgba = buffer.reshape(height, width, 4)
525
+ rgb, alpha = np.split(img_rgba, [3], axis=2)
526
+ return rgb.astype("uint8")
527
+
528
+
529
+ class Visualizer:
530
+ def __init__(self, img_rgb, metadata=None, scale=1.0):
531
+ self.img = np.asarray(img_rgb).clip(0, 255).astype(np.uint8)
532
+ self.font_path = FONT_PATH
533
+ self.output = VisImage(self.img, scale=scale)
534
+ self.cpu_device = torch.device("cpu")
535
+
536
+ # too small texts are useless, therefore clamp to 14
537
+ self._default_font_size = max(
538
+ np.sqrt(self.output.height * self.output.width) // 30, 15 // scale
539
+ )
540
+
541
+ def draw_text(
542
+ self,
543
+ text,
544
+ position,
545
+ *,
546
+ font_size=None,
547
+ color="g",
548
+ horizontal_alignment="center",
549
+ rotation=0,
550
+ ):
551
+ if not font_size:
552
+ font_size = self._default_font_size
553
+
554
+ # since the text background is dark, we don't want the text to be dark
555
+ color = np.maximum(list(mplc.to_rgb(color)), 0.2)
556
+ color[np.argmax(color)] = max(0.8, np.max(color))
557
+
558
+ x, y = position
559
+ self.output.ax.text(
560
+ x,
561
+ y,
562
+ text,
563
+ size=font_size * self.output.scale,
564
+ fontproperties=FontProperties(fname=self.font_path),
565
+ bbox={"facecolor": "black", "alpha": 0.8, "pad": 0.7, "edgecolor": "none"},
566
+ verticalalignment="top",
567
+ horizontalalignment=horizontal_alignment,
568
+ color=color,
569
+ zorder=10,
570
+ rotation=rotation,
571
+ )
572
+ return self.output
573
+
574
+ def draw_box(self, box_coord, alpha=0.5, edge_color="g", line_style="-"):
575
+
576
+ x0, y0, x1, y1 = box_coord
577
+ width = x1 - x0
578
+ height = y1 - y0
579
+
580
+ linewidth = max(self._default_font_size / 4, 1)
581
+
582
+ self.output.ax.add_patch(
583
+ mpl.patches.Rectangle(
584
+ (x0, y0),
585
+ width,
586
+ height,
587
+ fill=False,
588
+ edgecolor=edge_color,
589
+ linewidth=linewidth * self.output.scale,
590
+ alpha=alpha,
591
+ linestyle=line_style,
592
+ )
593
+ )
594
+ return self.output
595
+
596
+ def get_output(self):
597
+
598
+ return self.output
tokenizer_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoTokenizer": [
4
+ "tokenization_qwen.QWenTokenizer",
5
+ null
6
+ ]
7
+ },
8
+ "clean_up_tokenization_spaces": true,
9
+ "model_max_length": 912,
10
+ "padding_side": "right",
11
+ "tokenizer_class": "QWenTokenizer"
12
+ }