Tuyabei commited on
Commit
52d6255
1 Parent(s): c63e50e
config.json ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/mnt/petrelfs/tianjie/projects/Qwen-VL/vision_model/",
3
+ "architectures": [
4
+ "QWenForClassification"
5
+ ],
6
+ "attn_dropout_prob": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_qwen.QWenConfig",
9
+ "AutoModelForCausalLM": "modeling_qwen.QWenForClassification"
10
+ },
11
+ "bf16": true,
12
+ "class_name": [
13
+ "\u5199\u5b9e\u98ce\u683c",
14
+ "\u56fe\u6807\u98ce\u683c",
15
+ "\u5361\u901a\u98ce\u683c",
16
+ "\u827a\u672f\u98ce\u683c",
17
+ "\u9ed1\u767d\u7b80\u7b14\u98ce\u683c",
18
+ "\u7eaf\u6587\u5b57\u98ce\u683c",
19
+ "3D\u98ce\u683c",
20
+ "\u6c34\u5f69\u98ce\u683c",
21
+ "\u7d20\u63cf\u98ce\u683c",
22
+ "\u50cf\u7d20\u98ce\u683c",
23
+ "\u63d2\u753b\u98ce\u683c",
24
+ "\u79d1\u6280\u98ce\u683c",
25
+ "\u4e2d\u56fd\u98ce\u98ce\u683c"
26
+ ],
27
+ "emb_dropout_prob": 0.0,
28
+ "fp16": false,
29
+ "fp32": false,
30
+ "gamma": 0.9,
31
+ "hidden_size": 4096,
32
+ "id2label": {
33
+ "0": "LABEL_0",
34
+ "1": "LABEL_1",
35
+ "2": "LABEL_2",
36
+ "3": "LABEL_3",
37
+ "4": "LABEL_4",
38
+ "5": "LABEL_5",
39
+ "6": "LABEL_6",
40
+ "7": "LABEL_7",
41
+ "8": "LABEL_8",
42
+ "9": "LABEL_9",
43
+ "10": "LABEL_10",
44
+ "11": "LABEL_11",
45
+ "12": "LABEL_12"
46
+ },
47
+ "initializer_range": 0.02,
48
+ "intermediate_size": 22016,
49
+ "kv_channels": 128,
50
+ "label2id": {
51
+ "LABEL_0": 0,
52
+ "LABEL_1": 1,
53
+ "LABEL_10": 10,
54
+ "LABEL_11": 11,
55
+ "LABEL_12": 12,
56
+ "LABEL_2": 2,
57
+ "LABEL_3": 3,
58
+ "LABEL_4": 4,
59
+ "LABEL_5": 5,
60
+ "LABEL_6": 6,
61
+ "LABEL_7": 7,
62
+ "LABEL_8": 8,
63
+ "LABEL_9": 9
64
+ },
65
+ "layer_norm_epsilon": 1e-06,
66
+ "max_position_embeddings": 8192,
67
+ "model_type": "qwen",
68
+ "no_bias": true,
69
+ "num_attention_heads": 32,
70
+ "num_hidden_layers": 32,
71
+ "onnx_safe": null,
72
+ "rotary_emb_base": 10000,
73
+ "rotary_pct": 1.0,
74
+ "scale_attn_weights": true,
75
+ "seq_length": 2048,
76
+ "tie_word_embeddings": false,
77
+ "tokenizer_type": "QWenTokenizer",
78
+ "torch_dtype": "bfloat16",
79
+ "transformers_version": "4.34.0",
80
+ "use_cache": false,
81
+ "use_dynamic_ntk": true,
82
+ "use_flash_attn": false,
83
+ "use_logn_attn": true,
84
+ "visual": {
85
+ "heads": 16,
86
+ "image_size": 448,
87
+ "image_start_id": 151857,
88
+ "layers": 48,
89
+ "mlp_ratio": 4.9231,
90
+ "output_dim": 4096,
91
+ "patch_size": 14,
92
+ "width": 1664
93
+ },
94
+ "vocab_size": 151936
95
+ }
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,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "chat_format": "chatml",
3
+ "do_sample": true,
4
+ "eos_token_id": 151643,
5
+ "max_new_tokens": 512,
6
+ "max_window_size": 6144,
7
+ "pad_token_id": 151643,
8
+ "top_k": 0,
9
+ "top_p": 0.3,
10
+ "transformers_version": "4.34.0"
11
+ }
modeling_qwen.py ADDED
@@ -0,0 +1,1517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from transformers.generation.utils import *
6
+ import importlib
7
+ import math
8
+ from typing import TYPE_CHECKING, Optional, Tuple, Union, Callable, List, Any, Generator
9
+
10
+ import torch
11
+ import torch.nn.functional as F
12
+ import torch.utils.checkpoint
13
+ from torch.cuda.amp import autocast
14
+
15
+ from torch.nn import CrossEntropyLoss
16
+ from transformers import PreTrainedTokenizer, GenerationConfig, StoppingCriteriaList
17
+ from transformers.generation.logits_process import LogitsProcessorList
18
+
19
+ if TYPE_CHECKING:
20
+ from transformers.generation.streamers import BaseStreamer
21
+ from transformers.generation.utils import GenerateOutput
22
+ from transformers.modeling_outputs import (
23
+ ModelOutput,
24
+ )
25
+ from transformers.modeling_utils import PreTrainedModel
26
+ from transformers.utils import logging
27
+
28
+ try:
29
+ from einops import rearrange
30
+ except ImportError:
31
+ rearrange = None
32
+ from torch import nn
33
+
34
+ SUPPORT_CUDA = torch.cuda.is_available()
35
+ SUPPORT_BF16 = SUPPORT_CUDA and torch.cuda.is_bf16_supported()
36
+ SUPPORT_FP16 = SUPPORT_CUDA and torch.cuda.get_device_capability(0)[0] >= 7
37
+
38
+ from .configuration_qwen import QWenConfig
39
+ from .qwen_generation_utils import (
40
+ HistoryType,
41
+ make_context,
42
+ decode_tokens,
43
+ get_stop_words_ids,
44
+ StopWordsLogitsProcessor,
45
+ )
46
+ from .visual import VisionTransformer
47
+
48
+
49
+ logger = logging.get_logger(__name__)
50
+
51
+ _CHECKPOINT_FOR_DOC = "qwen"
52
+ _CONFIG_FOR_DOC = "QWenConfig"
53
+
54
+ QWen_PRETRAINED_MODEL_ARCHIVE_LIST = ["qwen-7b"]
55
+
56
+ _ERROR_BAD_CHAT_FORMAT = """\
57
+ 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".
58
+ 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().
59
+ 我们检测到您可能在使用预训练模型(而非chat模型)进行多轮chat,因为您当前在generation_config指定的chat_format,并未设置为我们在对话中所支持的"chatml"格式。
60
+ 如果您在直接使用我们从Huggingface提供的模型,请确保您在调用model.chat()时,使用的是"Qwen/Qwen-7B-Chat"模型(而非"Qwen/Qwen-7B"预训练模型)。
61
+ """
62
+
63
+ _SENTINEL = object()
64
+ _ERROR_STREAM_IN_CHAT = """\
65
+ Pass argument `stream` to model.chat() is buggy, deprecated, and marked for removal. Please use model.chat_stream(...) instead of model.chat(..., stream=True).
66
+ 向model.chat()传入参数stream的用法可能存在Bug,该用法已被废弃,将在未来被移除。请使用model.chat_stream(...)代替model.chat(..., stream=True)。
67
+ """
68
+
69
+ apply_rotary_emb_func = None
70
+ rms_norm = None
71
+
72
+ @dataclass
73
+ class CLSModelOutputWithPast(ModelOutput):
74
+ last_hidden_state: torch.FloatTensor = None
75
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
76
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
77
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
78
+ images_embed: Optional[Tuple[torch.FloatTensor]] = None
79
+
80
+ @dataclass
81
+ class CausalLMOutputWithPast(ModelOutput):
82
+ loss: Optional[torch.FloatTensor] = None
83
+ logits: torch.FloatTensor = None
84
+ cls_logits: torch.FloatTensor = None
85
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
86
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
87
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
88
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
89
+ def _make_causal_mask(
90
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
91
+ ):
92
+ """
93
+ Make causal mask used for bi-directional self-attention.
94
+ """
95
+ bsz, tgt_len = input_ids_shape
96
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
97
+ mask_cond = torch.arange(mask.size(-1), device=device)
98
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
99
+ mask = mask.to(dtype)
100
+
101
+ if past_key_values_length > 0:
102
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
103
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
104
+
105
+
106
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
107
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
108
+ """
109
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
110
+ """
111
+ bsz, src_len = mask.size()
112
+ tgt_len = tgt_len if tgt_len is not None else src_len
113
+
114
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
115
+
116
+ inverted_mask = 1.0 - expanded_mask
117
+
118
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
119
+
120
+
121
+ class QWenAttention(nn.Module):
122
+ def __init__(self, config):
123
+ super().__init__()
124
+
125
+ self.register_buffer("masked_bias", torch.tensor(-1e4), persistent=False)
126
+ self.seq_length = config.seq_length
127
+
128
+ self.hidden_size = config.hidden_size
129
+ self.split_size = config.hidden_size
130
+ self.num_heads = config.num_attention_heads
131
+ self.head_dim = self.hidden_size // self.num_heads
132
+
133
+ self.scale_attn_weights = True
134
+
135
+ self.projection_size = config.kv_channels * config.num_attention_heads
136
+
137
+ assert self.projection_size % config.num_attention_heads == 0
138
+ self.hidden_size_per_attention_head = (
139
+ self.projection_size // config.num_attention_heads
140
+ )
141
+
142
+ self.c_attn = nn.Linear(config.hidden_size, 3 * self.projection_size)
143
+
144
+ self.c_proj = nn.Linear(
145
+ config.hidden_size, self.projection_size, bias=not config.no_bias
146
+ )
147
+
148
+ self.is_fp32 = not (config.bf16 or config.fp16)
149
+ self.bf16 = config.bf16
150
+
151
+ self.use_dynamic_ntk = config.use_dynamic_ntk
152
+ self.use_logn_attn = config.use_logn_attn
153
+
154
+ logn_list = [
155
+ math.log(i, self.seq_length) if i > self.seq_length else 1
156
+ for i in range(1, 32768)
157
+ ]
158
+ self.logn_tensor = torch.tensor(logn_list)[None, :, None, None]
159
+
160
+ self.attn_dropout = nn.Dropout(config.attn_dropout_prob)
161
+
162
+ def _attn(self, query, key, value, registered_causal_mask, attention_mask=None, head_mask=None):
163
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
164
+
165
+ if self.scale_attn_weights:
166
+ attn_weights = attn_weights / torch.full(
167
+ [],
168
+ value.size(-1) ** 0.5,
169
+ dtype=attn_weights.dtype,
170
+ device=attn_weights.device,
171
+ )
172
+
173
+ query_length, key_length = query.size(-2), key.size(-2)
174
+ # causal_mask = self.bias[
175
+ # :, :, key_length - query_length : key_length, :key_length
176
+ # ]
177
+ # mask_value = torch.finfo(attn_weights.dtype).min
178
+ # mask_value = torch.full([], mask_value, dtype=attn_weights.dtype).to(
179
+ # attn_weights.device
180
+ # )
181
+ # attn_weights = torch.where(
182
+ # causal_mask, attn_weights.to(attn_weights.dtype), mask_value
183
+ # )
184
+ attn_weights = attn_weights + attention_mask
185
+
186
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
187
+
188
+ attn_weights = attn_weights.type(value.dtype)
189
+ attn_weights = self.attn_dropout(attn_weights)
190
+
191
+ if head_mask is not None:
192
+ attn_weights = attn_weights * head_mask
193
+
194
+ attn_output = torch.matmul(attn_weights, value)
195
+ attn_output = attn_output.transpose(1, 2)
196
+
197
+ return attn_output, attn_weights
198
+
199
+ def _upcast_and_reordered_attn(
200
+ self, query, key, value, registered_causal_mask, attention_mask=None, head_mask=None
201
+ ):
202
+ bsz, num_heads, q_seq_len, dk = query.size()
203
+ _, _, k_seq_len, _ = key.size()
204
+
205
+ attn_weights = torch.empty(
206
+ bsz * num_heads,
207
+ q_seq_len,
208
+ k_seq_len,
209
+ dtype=torch.float32,
210
+ device=query.device,
211
+ )
212
+
213
+ scale_factor = 1.0
214
+ if self.scale_attn_weights:
215
+ scale_factor /= float(value.size(-1)) ** 0.5
216
+
217
+ with autocast(enabled=False):
218
+ q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(
219
+ -1, dk, k_seq_len
220
+ )
221
+ attn_weights = torch.baddbmm(
222
+ attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor
223
+ )
224
+ attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
225
+
226
+ query_length, key_length = query.size(-2), key.size(-2)
227
+ causal_mask = registered_causal_mask[
228
+ :, :, key_length - query_length : key_length, :key_length
229
+ ]
230
+ mask_value = torch.finfo(attn_weights.dtype).min
231
+ mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(
232
+ attn_weights.device
233
+ )
234
+ attn_weights = torch.where(causal_mask, attn_weights, mask_value)
235
+
236
+ if attention_mask is not None:
237
+ attn_weights = attn_weights + attention_mask
238
+
239
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
240
+
241
+ if attn_weights.dtype != torch.float32:
242
+ raise RuntimeError(
243
+ "Error with upcasting, attn_weights does not have dtype torch.float32"
244
+ )
245
+ attn_weights = attn_weights.type(value.dtype)
246
+ attn_weights = self.attn_dropout(attn_weights)
247
+
248
+ if head_mask is not None:
249
+ attn_weights = attn_weights * head_mask
250
+
251
+ attn_output = torch.matmul(attn_weights, value)
252
+
253
+ return attn_output, attn_weights
254
+
255
+ def _split_heads(self, tensor, num_heads, attn_head_size):
256
+ new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
257
+ tensor = tensor.view(new_shape)
258
+ return tensor
259
+
260
+ def _merge_heads(self, tensor, num_heads, attn_head_size):
261
+ tensor = tensor.contiguous()
262
+ new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
263
+ return tensor.view(new_shape)
264
+
265
+ def forward(
266
+ self,
267
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
268
+ rotary_pos_emb: Optional[List[torch.Tensor]] = None,
269
+ registered_causal_mask: Optional[torch.Tensor] = None,
270
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
271
+ attention_mask: Optional[torch.FloatTensor] = None,
272
+ head_mask: Optional[torch.FloatTensor] = None,
273
+ encoder_hidden_states: Optional[torch.Tensor] = None,
274
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
275
+ output_attentions: Optional[bool] = False,
276
+ use_cache: Optional[bool] = False,
277
+ ):
278
+
279
+ mixed_x_layer = self.c_attn(hidden_states)
280
+
281
+ query, key, value = mixed_x_layer.split(self.split_size, dim=2)
282
+
283
+ query = self._split_heads(query, self.num_heads, self.head_dim)
284
+ key = self._split_heads(key, self.num_heads, self.head_dim)
285
+ value = self._split_heads(value, self.num_heads, self.head_dim)
286
+
287
+ if rotary_pos_emb is not None:
288
+ cur_len = query.shape[1]
289
+ rotary_pos_emb = [i[:, -cur_len:, :, :] for i in rotary_pos_emb]
290
+ rotary_pos_emb = (rotary_pos_emb,) * 2
291
+ q_pos_emb, k_pos_emb = rotary_pos_emb
292
+ # Slice the pos emb for current inference
293
+ query = apply_rotary_pos_emb(query, q_pos_emb)
294
+ key = apply_rotary_pos_emb(key, k_pos_emb)
295
+
296
+ if layer_past is not None:
297
+ past_key, past_value = layer_past[0], layer_past[1]
298
+ key = torch.cat((past_key, key), dim=1)
299
+ value = torch.cat((past_value, value), dim=1)
300
+
301
+ if use_cache:
302
+ present = (key, value)
303
+ else:
304
+ present = None
305
+
306
+ if self.use_logn_attn and not self.training:
307
+ if self.logn_tensor.device != query.device or self.logn_tensor.dtype != query.dtype:
308
+ self.logn_tensor = self.logn_tensor.to(query.device).type_as(query)
309
+ seq_start = key.size(1) - query.size(1)
310
+ seq_end = key.size(1)
311
+ logn_tensor = self.logn_tensor[:, seq_start:seq_end, :, :]
312
+ query = query * logn_tensor.expand_as(query)
313
+
314
+ query = query.permute(0, 2, 1, 3)
315
+ key = key.permute(0, 2, 1, 3)
316
+ value = value.permute(0, 2, 1, 3)
317
+ attn_output, attn_weight = self._attn(
318
+ query, key, value, registered_causal_mask, attention_mask, head_mask
319
+ )
320
+ context_layer = self._merge_heads(
321
+ attn_output, self.num_heads, self.head_dim
322
+ )
323
+
324
+ attn_output = self.c_proj(context_layer)
325
+
326
+ outputs = (attn_output, present)
327
+ if output_attentions:
328
+ outputs += (attn_weight,)
329
+
330
+ return outputs
331
+
332
+
333
+ class QWenMLP(nn.Module):
334
+ def __init__(self, config):
335
+ super().__init__()
336
+ self.w1 = nn.Linear(
337
+ config.hidden_size, config.intermediate_size // 2, bias=not config.no_bias
338
+ )
339
+ self.w2 = nn.Linear(
340
+ config.hidden_size, config.intermediate_size // 2, bias=not config.no_bias
341
+ )
342
+ ff_dim_in = config.intermediate_size // 2
343
+ self.c_proj = nn.Linear(ff_dim_in, config.hidden_size, bias=not config.no_bias)
344
+
345
+ def forward(self, hidden_states):
346
+ a1 = self.w1(hidden_states)
347
+ a2 = self.w2(hidden_states)
348
+ intermediate_parallel = a1 * F.silu(a2)
349
+ output = self.c_proj(intermediate_parallel)
350
+ return output
351
+
352
+ class QWenBlock(nn.Module):
353
+ def __init__(self, config):
354
+ super().__init__()
355
+ hidden_size = config.hidden_size
356
+ self.bf16 = config.bf16
357
+
358
+ self.ln_1 = RMSNorm(
359
+ hidden_size,
360
+ eps=config.layer_norm_epsilon,
361
+ )
362
+ self.attn = QWenAttention(config)
363
+ self.ln_2 = RMSNorm(
364
+ hidden_size,
365
+ eps=config.layer_norm_epsilon,
366
+ )
367
+
368
+ self.mlp = QWenMLP(config)
369
+
370
+ def forward(
371
+ self,
372
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
373
+ rotary_pos_emb: Optional[List[torch.Tensor]] = None,
374
+ registered_causal_mask: Optional[torch.Tensor] = None,
375
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
376
+ attention_mask: Optional[torch.FloatTensor] = None,
377
+ head_mask: Optional[torch.FloatTensor] = None,
378
+ encoder_hidden_states: Optional[torch.Tensor] = None,
379
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
380
+ use_cache: Optional[bool] = False,
381
+ output_attentions: Optional[bool] = False,
382
+ ):
383
+ layernorm_output = self.ln_1(hidden_states)
384
+
385
+ attn_outputs = self.attn(
386
+ layernorm_output,
387
+ rotary_pos_emb,
388
+ registered_causal_mask=registered_causal_mask,
389
+ layer_past=layer_past,
390
+ attention_mask=attention_mask,
391
+ head_mask=head_mask,
392
+ use_cache=use_cache,
393
+ output_attentions=output_attentions,
394
+ )
395
+ attn_output = attn_outputs[0]
396
+
397
+ outputs = attn_outputs[1:]
398
+
399
+ residual = hidden_states
400
+ layernorm_input = attn_output + residual
401
+
402
+ layernorm_output = self.ln_2(layernorm_input)
403
+
404
+ residual = layernorm_input
405
+ mlp_output = self.mlp(layernorm_output)
406
+ hidden_states = residual + mlp_output
407
+
408
+ if use_cache:
409
+ outputs = (hidden_states,) + outputs
410
+ else:
411
+ outputs = (hidden_states,) + outputs[1:]
412
+
413
+ return outputs
414
+
415
+
416
+ class QWenPreTrainedModel(PreTrainedModel):
417
+ config_class = QWenConfig
418
+ base_model_prefix = "transformer"
419
+ is_parallelizable = False
420
+ supports_gradient_checkpointing = True
421
+ _no_split_modules = ["QWenBlock"]
422
+
423
+ def __init__(self, *inputs, **kwargs):
424
+ super().__init__(*inputs, **kwargs)
425
+
426
+ def _init_weights(self, module):
427
+ """Initialize the weights."""
428
+ if isinstance(module, nn.Linear):
429
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
430
+ if module.bias is not None:
431
+ module.bias.data.zero_()
432
+ elif isinstance(module, nn.Embedding):
433
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
434
+ if module.padding_idx is not None:
435
+ module.weight.data[module.padding_idx].zero_()
436
+ elif isinstance(module, RMSNorm):
437
+ module.weight.data.fill_(1.0)
438
+
439
+ for name, p in module.named_parameters():
440
+ if name == "c_proj.weight":
441
+ p.data.normal_(
442
+ mean=0.0,
443
+ std=(
444
+ self.config.initializer_range
445
+ / math.sqrt(2 * self.config.num_hidden_layers)
446
+ ),
447
+ )
448
+
449
+ def _set_gradient_checkpointing(self, module, value=False):
450
+ if isinstance(module, QWenModel):
451
+ module.gradient_checkpointing = value
452
+
453
+
454
+ class QWenModel(QWenPreTrainedModel):
455
+ _keys_to_ignore_on_load_missing = ["attn.masked_bias"]
456
+
457
+ def __init__(self, config):
458
+ super().__init__(config)
459
+ self.vocab_size = config.vocab_size
460
+ self.num_hidden_layers = config.num_hidden_layers
461
+ self.embed_dim = config.hidden_size
462
+
463
+ self.gradient_checkpointing = False
464
+ self.use_dynamic_ntk = config.use_dynamic_ntk
465
+ self.seq_length = config.seq_length
466
+
467
+ self.wte = nn.Embedding(self.vocab_size, self.embed_dim)
468
+
469
+ self.drop = nn.Dropout(config.emb_dropout_prob)
470
+
471
+ if config.rotary_pct == 1.0:
472
+ self.rotary_ndims = None
473
+ else:
474
+ assert config.rotary_pct < 1
475
+ self.rotary_ndims = int(
476
+ config.kv_channels * config.rotary_pct
477
+ )
478
+ dim = (
479
+ self.rotary_ndims
480
+ if self.rotary_ndims is not None
481
+ else config.kv_channels
482
+ )
483
+ self.rotary_emb = RotaryEmbedding(dim, base=config.rotary_emb_base)
484
+
485
+ self.use_flash_attn = config.use_flash_attn
486
+ self.is_fp32 = not (config.bf16 or config.fp16)
487
+ self.registered_causal_mask = None
488
+ # if (
489
+ # self.use_flash_attn
490
+ # and flash_attn_unpadded_func is not None
491
+ # and not self.is_fp32
492
+ # ):
493
+ # self.registered_causal_mask = None
494
+ # else:
495
+ # max_positions = config.max_position_embeddings
496
+ # self.register_buffer(
497
+ # "registered_causal_mask",
498
+ # torch.tril(
499
+ # torch.ones((max_positions, max_positions), dtype=torch.bool)
500
+ # ).view(1, 1, max_positions, max_positions),
501
+ # persistent=False,
502
+ # )
503
+
504
+ self.h = nn.ModuleList(
505
+ [
506
+ QWenBlock(
507
+ config
508
+ )
509
+ for i in range(config.num_hidden_layers)
510
+ ]
511
+ )
512
+ self.ln_f = RMSNorm(
513
+ self.embed_dim,
514
+ eps=config.layer_norm_epsilon,
515
+ )
516
+
517
+ self.visual = VisionTransformer(**config.visual)
518
+
519
+ self.post_init()
520
+
521
+ def get_input_embeddings(self):
522
+ return self.wte
523
+
524
+ def set_input_embeddings(self, new_embeddings):
525
+ self.wte = new_embeddings
526
+
527
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
528
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
529
+ # create causal mask
530
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
531
+ combined_attention_mask = None
532
+ if input_shape[-1] > 1:
533
+ combined_attention_mask = _make_causal_mask(
534
+ input_shape,
535
+ inputs_embeds.dtype,
536
+ device=inputs_embeds.device,
537
+ past_key_values_length=past_key_values_length,
538
+ )
539
+
540
+ if attention_mask is not None:
541
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
542
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
543
+ inputs_embeds.device
544
+ )
545
+ combined_attention_mask = (
546
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
547
+ )
548
+
549
+ return combined_attention_mask
550
+
551
+
552
+ def forward(
553
+ self,
554
+ input_ids: Optional[torch.LongTensor] = None,
555
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
556
+ attention_mask: Optional[torch.FloatTensor] = None,
557
+ token_type_ids: Optional[torch.LongTensor] = None,
558
+ position_ids: Optional[torch.LongTensor] = None,
559
+ head_mask: Optional[torch.FloatTensor] = None,
560
+ inputs_embeds: Optional[torch.FloatTensor] = None,
561
+ encoder_hidden_states: Optional[torch.Tensor] = None,
562
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
563
+ use_cache: Optional[bool] = None,
564
+ output_attentions: Optional[bool] = None,
565
+ output_hidden_states: Optional[bool] = None,
566
+ return_dict: Optional[bool] = None,
567
+ ):
568
+ if past_key_values is None and torch.any(input_ids == self.config.visual['image_start_id']):
569
+ bos_pos = torch.where(input_ids == self.config.visual['image_start_id'])
570
+ eos_pos = torch.where(input_ids == self.config.visual['image_start_id'] + 1)
571
+ assert (bos_pos[0] == eos_pos[0]).all()
572
+ img_pos = torch.stack((bos_pos[0], bos_pos[1], eos_pos[1]), dim=1)
573
+ images = []
574
+ for i, a, b in img_pos:
575
+ image = input_ids[i][a + 1 : b - 1].tolist()
576
+ image = image[ : image.index(self.config.visual['image_start_id'] + 2)]
577
+ images.append(bytes(image).decode('utf-8'))
578
+
579
+ images = self.visual.encode(images)
580
+ assert images.shape[0] == len(images)
581
+ fake_images = None
582
+ elif self.training:
583
+ fake_images=torch.zeros(1,3,224,224).to(
584
+ dtype=self.visual.conv1.weight.dtype, device=self.visual.conv1.weight.device)
585
+ images = self.visual(fake_images)
586
+ else:
587
+ fake_images = None
588
+ images = None
589
+
590
+ output_attentions = (
591
+ output_attentions
592
+ if output_attentions is not None
593
+ else self.config.output_attentions
594
+ )
595
+ output_hidden_states = (
596
+ output_hidden_states
597
+ if output_hidden_states is not None
598
+ else self.config.output_hidden_states
599
+ )
600
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
601
+ return_dict = (
602
+ return_dict if return_dict is not None else self.config.use_return_dict
603
+ )
604
+
605
+ if input_ids is not None and inputs_embeds is not None:
606
+ raise ValueError(
607
+ "You cannot specify both input_ids and inputs_embeds at the same time"
608
+ )
609
+ elif input_ids is not None:
610
+ input_shape = input_ids.size()
611
+ input_ids = input_ids.view(-1, input_shape[-1])
612
+ batch_size = input_ids.shape[0]
613
+ elif inputs_embeds is not None:
614
+ input_shape = inputs_embeds.size()[:-1]
615
+ batch_size = inputs_embeds.shape[0]
616
+ else:
617
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
618
+
619
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
620
+
621
+ if token_type_ids is not None:
622
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
623
+ if position_ids is not None:
624
+ position_ids = position_ids.view(-1, input_shape[-1])
625
+
626
+ if past_key_values is None:
627
+ past_length = 0
628
+ past_key_values = tuple([None] * len(self.h))
629
+ else:
630
+ past_length = past_key_values[0][0].size(-2)
631
+
632
+ if position_ids is None:
633
+ position_ids = torch.arange(
634
+ past_length,
635
+ input_shape[-1] + past_length,
636
+ dtype=torch.long,
637
+ device=device,
638
+ )
639
+ position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
640
+
641
+ encoder_attention_mask = None
642
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
643
+
644
+ if inputs_embeds is None:
645
+ inputs_embeds = self.wte(input_ids)
646
+
647
+ if batch_size <= 0:
648
+ raise ValueError("batch_size has to be defined and > 0")
649
+ attention_mask = self._prepare_decoder_attention_mask(
650
+ attention_mask, input_shape, inputs_embeds, past_length
651
+ )
652
+
653
+ hidden_states = inputs_embeds
654
+
655
+ kv_seq_len = hidden_states.size()[1]
656
+ if past_key_values[0] is not None:
657
+ # past key values[0][0] shape: bs * seq_len * head_num * dim
658
+ kv_seq_len += past_key_values[0][0].shape[1]
659
+ if (
660
+ self.use_dynamic_ntk
661
+ and kv_seq_len == hidden_states.size()[1]
662
+ and not self.training
663
+ ):
664
+ context_value = math.log(kv_seq_len / self.seq_length, 2) + 1
665
+ ntk_alpha = 2 ** math.ceil(context_value) - 1
666
+ ntk_alpha = max(ntk_alpha, 1)
667
+ else:
668
+ ntk_alpha = self.rotary_emb._ntk_alpha_cached
669
+
670
+ rotary_pos_emb = self.rotary_emb(kv_seq_len, ntk_alpha=ntk_alpha)
671
+ for idx in range(len(rotary_pos_emb)):
672
+ rotary_pos_emb[idx] = rotary_pos_emb[idx].to(hidden_states.device)
673
+
674
+ hidden_states = self.drop(hidden_states).clone()
675
+ if fake_images is not None:
676
+ hidden_states = hidden_states + images.mean()*0
677
+ elif images is not None:
678
+ for idx, (i, a, b) in enumerate(img_pos):
679
+ hidden_states[i][a + 1 : b] = images[idx]
680
+ output_shape = input_shape + (hidden_states.size(-1),)
681
+
682
+ if self.gradient_checkpointing and self.training:
683
+ if use_cache:
684
+ logger.warning_once(
685
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
686
+ )
687
+ use_cache = False
688
+
689
+ presents = () if use_cache else None
690
+ all_self_attentions = () if output_attentions else None
691
+ all_hidden_states = () if output_hidden_states else None
692
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
693
+
694
+ if output_hidden_states:
695
+ all_hidden_states = all_hidden_states + (hidden_states,)
696
+
697
+ if self.gradient_checkpointing and self.training:
698
+
699
+ def create_custom_forward(module):
700
+ def custom_forward(*inputs):
701
+ # None for past_key_value
702
+ return module(*inputs, use_cache, output_attentions)
703
+
704
+ return custom_forward
705
+
706
+ outputs = torch.utils.checkpoint.checkpoint(
707
+ create_custom_forward(block),
708
+ hidden_states,
709
+ rotary_pos_emb,
710
+ self.registered_causal_mask,
711
+ None,
712
+ attention_mask,
713
+ head_mask[i],
714
+ encoder_hidden_states,
715
+ encoder_attention_mask,
716
+ )
717
+ else:
718
+ outputs = block(
719
+ hidden_states,
720
+ layer_past=layer_past,
721
+ rotary_pos_emb=rotary_pos_emb,
722
+ registered_causal_mask=self.registered_causal_mask,
723
+ attention_mask=attention_mask,
724
+ head_mask=head_mask[i],
725
+ encoder_hidden_states=encoder_hidden_states,
726
+ encoder_attention_mask=encoder_attention_mask,
727
+ use_cache=use_cache,
728
+ output_attentions=output_attentions,
729
+ )
730
+
731
+ hidden_states = outputs[0]
732
+ if use_cache is True:
733
+ presents = presents + (outputs[1],)
734
+
735
+ if output_attentions:
736
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
737
+
738
+ hidden_states = self.ln_f(hidden_states)
739
+ hidden_states = hidden_states.view(output_shape)
740
+ # Add last hidden state
741
+ if output_hidden_states:
742
+ all_hidden_states = all_hidden_states + (hidden_states,)
743
+ if not return_dict:
744
+ return tuple(
745
+ v for v in [hidden_states, presents, all_hidden_states, images] if v is not None
746
+ )
747
+
748
+ return CLSModelOutputWithPast(
749
+ last_hidden_state=hidden_states,
750
+ past_key_values=presents,
751
+ hidden_states=all_hidden_states,
752
+ attentions=all_self_attentions,
753
+ images_embed=images,
754
+ )
755
+
756
+
757
+ class QWenForClassification(QWenPreTrainedModel):
758
+ _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.rotary_emb\.inv_freq"]
759
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.masked_bias"]
760
+
761
+ def __init__(self, config):
762
+ super().__init__(config)
763
+ assert (
764
+ config.bf16 + config.fp16 + config.fp32 <= 1
765
+ ), "Only one of \"bf16\", \"fp16\", \"fp32\" can be true"
766
+
767
+ autoset_precision = config.bf16 + config.fp16 + config.fp32 == 0
768
+
769
+ if autoset_precision:
770
+ if SUPPORT_BF16:
771
+ logger.warn(
772
+ "The model is automatically converting to bf16 for faster inference. "
773
+ "If you want to disable the automatic precision, please manually add bf16/fp16/fp32=True to \"AutoModelForCausalLM.from_pretrained\"."
774
+ )
775
+ config.bf16 = True
776
+ elif SUPPORT_FP16:
777
+ logger.warn(
778
+ "The model is automatically converting to fp16 for faster inference. "
779
+ "If you want to disable the automatic precision, please manually add bf16/fp16/fp32=True to \"AutoModelForCausalLM.from_pretrained\"."
780
+ )
781
+ config.fp16 = True
782
+ else:
783
+ config.fp32 = True
784
+
785
+ if config.bf16 and SUPPORT_CUDA and not SUPPORT_BF16:
786
+ 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\".")
787
+ if config.fp16 and SUPPORT_CUDA and not SUPPORT_FP16:
788
+ logger.warn("Your device does NOT support faster inference with fp16, please switch to fp32 which is likely to be faster")
789
+ if config.fp32:
790
+ if SUPPORT_BF16:
791
+ logger.warn("Your device support faster inference by passing bf16=True in \"AutoModelForCausalLM.from_pretrained\".")
792
+ elif SUPPORT_FP16:
793
+ logger.warn("Your device support faster inference by passing fp16=True in \"AutoModelForCausalLM.from_pretrained\".")
794
+ self.gamma = config.gamma
795
+ self.class_names = config.class_name
796
+ self.transformer = QWenModel(config)
797
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
798
+ self.cls_head = nn.Linear(config.hidden_size, config.num_labels)
799
+ if config.bf16:
800
+ self.transformer.bfloat16()
801
+ self.lm_head.bfloat16()
802
+ self.cls_head.bfloat16()
803
+ if config.fp16:
804
+ self.transformer.half()
805
+ self.lm_head.half()
806
+ self.cls_head.half()
807
+ self.post_init()
808
+
809
+ def get_output_embeddings(self):
810
+ return self.lm_head
811
+
812
+ def set_output_embeddings(self, new_embeddings):
813
+ self.lm_head = new_embeddings
814
+
815
+ def prepare_inputs_for_generation(
816
+ self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs
817
+ ):
818
+ token_type_ids = kwargs.get("token_type_ids", None)
819
+ if past_key_values:
820
+ input_ids = input_ids[:, -1].unsqueeze(-1)
821
+ if token_type_ids is not None:
822
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
823
+
824
+ attention_mask = kwargs.get("attention_mask", None)
825
+ position_ids = kwargs.get("position_ids", None)
826
+
827
+ if attention_mask is not None and position_ids is None:
828
+ position_ids = attention_mask.long().cumsum(-1) - 1
829
+ position_ids.masked_fill_(attention_mask == 0, 1)
830
+ if past_key_values:
831
+ position_ids = position_ids[:, -1].unsqueeze(-1)
832
+ else:
833
+ position_ids = None
834
+
835
+ if inputs_embeds is not None and past_key_values is None:
836
+ model_inputs = {"inputs_embeds": inputs_embeds}
837
+ else:
838
+ model_inputs = {"input_ids": input_ids}
839
+
840
+ model_inputs.update(
841
+ {
842
+ "past_key_values": past_key_values,
843
+ "use_cache": kwargs.get("use_cache"),
844
+ "position_ids": position_ids,
845
+ "attention_mask": attention_mask,
846
+ "token_type_ids": token_type_ids,
847
+ }
848
+ )
849
+ return model_inputs
850
+
851
+ def forward(
852
+ self,
853
+ input_ids: Optional[torch.LongTensor] = None,
854
+ cls_labels: Optional[torch.LongTensor] = None,
855
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
856
+ attention_mask: Optional[torch.FloatTensor] = None,
857
+ token_type_ids: Optional[torch.LongTensor] = None,
858
+ position_ids: Optional[torch.LongTensor] = None,
859
+ head_mask: Optional[torch.FloatTensor] = None,
860
+ inputs_embeds: Optional[torch.FloatTensor] = None,
861
+ encoder_hidden_states: Optional[torch.Tensor] = None,
862
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
863
+ labels: Optional[torch.LongTensor] = None,
864
+ use_cache: Optional[bool] = None,
865
+ output_attentions: Optional[bool] = None,
866
+ output_hidden_states: Optional[bool] = None,
867
+ return_dict: Optional[bool] = None,
868
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
869
+
870
+ return_dict = (
871
+ return_dict if return_dict is not None else self.config.use_return_dict
872
+ )
873
+
874
+ transformer_outputs = self.transformer(
875
+ input_ids,
876
+ past_key_values=past_key_values,
877
+ attention_mask=attention_mask,
878
+ token_type_ids=token_type_ids,
879
+ position_ids=position_ids,
880
+ head_mask=head_mask,
881
+ inputs_embeds=inputs_embeds,
882
+ encoder_hidden_states=encoder_hidden_states,
883
+ encoder_attention_mask=encoder_attention_mask,
884
+ use_cache=use_cache,
885
+ output_attentions=output_attentions,
886
+ output_hidden_states=output_hidden_states,
887
+ return_dict=return_dict,
888
+ )
889
+ hidden_states = transformer_outputs[0]
890
+ cls_hidden_states = transformer_outputs.images_embed
891
+ lm_logits = self.lm_head(hidden_states)
892
+
893
+ if cls_hidden_states is not None:
894
+ cls_logits = self.cls_head(cls_hidden_states[:, 0, :])
895
+ else :
896
+ cls_logits = None
897
+ loss = None
898
+ if labels is not None:
899
+ labels = labels.to(lm_logits.device)
900
+ shift_logits = lm_logits[..., :-1, :].contiguous()
901
+ shift_labels = labels[..., 1:].contiguous()
902
+ loss_fct = CrossEntropyLoss()
903
+ lm_loss = loss_fct(
904
+ shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)
905
+ )
906
+ cls_loss = loss_fct(
907
+ cls_logits.view(-1, cls_logits.size(-1)), cls_labels.view(-1)
908
+ )
909
+ loss = self.gamma*lm_loss + (1-self.gamma)*cls_loss
910
+ print("llm_loss:\t{}\tcls_loss:\t{}".format(lm_loss.item(), cls_loss.item()))
911
+ if not return_dict:
912
+ output = (lm_logits,) + transformer_outputs[1:]
913
+ return ((loss,) + output) if loss is not None else output
914
+
915
+ return CausalLMOutputWithPast(
916
+ loss=loss,
917
+ logits=lm_logits,
918
+ cls_logits=cls_logits,
919
+ past_key_values=transformer_outputs.past_key_values,
920
+ hidden_states=transformer_outputs.hidden_states,
921
+ attentions=transformer_outputs.attentions,
922
+ )
923
+
924
+ @staticmethod
925
+ def _reorder_cache(
926
+ past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
927
+ ) -> Tuple[Tuple[torch.Tensor]]:
928
+
929
+ return tuple(
930
+ tuple(
931
+ past_state.index_select(0, beam_idx.to(past_state.device))
932
+ for past_state in layer_past
933
+ )
934
+ for layer_past in past_key_values
935
+ )
936
+
937
+ def chat(
938
+ self,
939
+ tokenizer: PreTrainedTokenizer,
940
+ query: str,
941
+ history: Optional[HistoryType],
942
+ system: str = "You are a helpful assistant.",
943
+ append_history: bool = True,
944
+ stream: Optional[bool] = _SENTINEL,
945
+ stop_words_ids: Optional[List[List[int]]] = None,
946
+ generation_config: Optional[GenerationConfig] = None,
947
+ **kwargs,
948
+ ) -> Tuple[str, HistoryType]:
949
+ generation_config = generation_config if generation_config is not None else self.generation_config
950
+
951
+ assert stream is _SENTINEL, _ERROR_STREAM_IN_CHAT
952
+ assert generation_config.chat_format == 'chatml', _ERROR_BAD_CHAT_FORMAT
953
+ if history is None:
954
+ history = []
955
+ if stop_words_ids is None:
956
+ stop_words_ids = []
957
+
958
+ max_window_size = kwargs.get('max_window_size', None)
959
+ if max_window_size is None:
960
+ max_window_size = generation_config.max_window_size
961
+ raw_text, context_tokens = make_context(
962
+ tokenizer,
963
+ query,
964
+ history=history,
965
+ system=system,
966
+ max_window_size=max_window_size,
967
+ chat_format=generation_config.chat_format,
968
+ )
969
+
970
+ stop_words_ids.extend(get_stop_words_ids(
971
+ generation_config.chat_format, tokenizer
972
+ ))
973
+ input_ids = torch.tensor([context_tokens]).to(self.device)
974
+ outputs, predicted_class_ids = self.generate(
975
+ input_ids,
976
+ stop_words_ids=stop_words_ids,
977
+ return_dict_in_generate=False,
978
+ generation_config=generation_config,
979
+ **kwargs,
980
+ )
981
+
982
+ response = decode_tokens(
983
+ outputs[0],
984
+ tokenizer,
985
+ raw_text_len=len(raw_text),
986
+ context_length=len(context_tokens),
987
+ chat_format=generation_config.chat_format,
988
+ verbose=False,
989
+ errors='replace'
990
+ )
991
+
992
+ predicted_class_names = self.class_names[predicted_class_ids[0]]
993
+
994
+ return response, predicted_class_names
995
+
996
+ def chat_stream(
997
+ self,
998
+ tokenizer: PreTrainedTokenizer,
999
+ query: str,
1000
+ history: Optional[HistoryType],
1001
+ system: str = "You are a helpful assistant.",
1002
+ stop_words_ids: Optional[List[List[int]]] = None,
1003
+ logits_processor: Optional[LogitsProcessorList] = None,
1004
+ generation_config: Optional[GenerationConfig] = None,
1005
+ **kwargs,
1006
+ ) -> Generator[str, Any, None]:
1007
+ generation_config = generation_config if generation_config is not None else self.generation_config
1008
+ assert generation_config.chat_format == 'chatml', _ERROR_BAD_CHAT_FORMAT
1009
+ if history is None:
1010
+ history = []
1011
+ if stop_words_ids is None:
1012
+ stop_words_ids = []
1013
+
1014
+ max_window_size = kwargs.get('max_window_size', None)
1015
+ if max_window_size is None:
1016
+ max_window_size = generation_config.max_window_size
1017
+ raw_text, context_tokens = make_context(
1018
+ tokenizer,
1019
+ query,
1020
+ history=history,
1021
+ system=system,
1022
+ max_window_size=max_window_size,
1023
+ chat_format=generation_config.chat_format,
1024
+ )
1025
+
1026
+ stop_words_ids.extend(get_stop_words_ids(
1027
+ generation_config.chat_format, tokenizer
1028
+ ))
1029
+ if stop_words_ids is not None:
1030
+ stop_words_logits_processor = StopWordsLogitsProcessor(
1031
+ stop_words_ids=stop_words_ids,
1032
+ eos_token_id=generation_config.eos_token_id,
1033
+ )
1034
+ if logits_processor is None:
1035
+ logits_processor = LogitsProcessorList([stop_words_logits_processor])
1036
+ else:
1037
+ logits_processor.append(stop_words_logits_processor)
1038
+ input_ids = torch.tensor([context_tokens]).to(self.device)
1039
+
1040
+ from transformers_stream_generator.main import NewGenerationMixin, StreamGenerationConfig
1041
+ self.__class__.generate_stream = NewGenerationMixin.generate
1042
+ self.__class__.sample_stream = NewGenerationMixin.sample_stream
1043
+ stream_config = StreamGenerationConfig(**generation_config.to_dict(), do_stream=True)
1044
+
1045
+ def stream_generator():
1046
+ outputs = []
1047
+ for token in self.generate_stream(
1048
+ input_ids,
1049
+ return_dict_in_generate=False,
1050
+ generation_config=stream_config,
1051
+ logits_processor=logits_processor,
1052
+ seed=-1,
1053
+ **kwargs):
1054
+ outputs.append(token.item())
1055
+ yield tokenizer.decode(outputs, skip_special_tokens=True, errors='ignore', keep_image_special=True)
1056
+
1057
+ return stream_generator()
1058
+
1059
+ def generate(
1060
+ self,
1061
+ inputs: Optional[torch.Tensor] = None,
1062
+ generation_config: Optional[GenerationConfig] = None,
1063
+ logits_processor: Optional[LogitsProcessorList] = None,
1064
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
1065
+ prefix_allowed_tokens_fn: Optional[
1066
+ Callable[[int, torch.Tensor], List[int]]
1067
+ ] = None,
1068
+ synced_gpus: Optional[bool] = None,
1069
+ assistant_model: Optional["PreTrainedModel"] = None,
1070
+ streamer: Optional["BaseStreamer"] = None,
1071
+ negative_prompt_ids: Optional[torch.Tensor] = None,
1072
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
1073
+ **kwargs,
1074
+ ) -> Union[GenerateOutput, torch.LongTensor]:
1075
+ generation_config = generation_config if generation_config is not None else self.generation_config
1076
+
1077
+ # Process stop_words_ids.
1078
+ stop_words_ids = kwargs.pop("stop_words_ids", None)
1079
+ if stop_words_ids is None and generation_config is not None:
1080
+ stop_words_ids = getattr(generation_config, "stop_words_ids", None)
1081
+ if stop_words_ids is None:
1082
+ stop_words_ids = getattr(generation_config, "stop_words_ids", None)
1083
+
1084
+ if stop_words_ids is not None:
1085
+ stop_words_logits_processor = StopWordsLogitsProcessor(
1086
+ stop_words_ids=stop_words_ids,
1087
+ eos_token_id=generation_config.eos_token_id,
1088
+ )
1089
+ if logits_processor is None:
1090
+ logits_processor = LogitsProcessorList([stop_words_logits_processor])
1091
+ else:
1092
+ logits_processor.append(stop_words_logits_processor)
1093
+ if synced_gpus is None:
1094
+ if is_deepspeed_zero3_enabled() and dist.get_world_size() > 1:
1095
+ synced_gpus = True
1096
+ else:
1097
+ synced_gpus = False
1098
+
1099
+ # 1. Handle `generation_config` and kwargs that might update it, and validate the `.generate()` call
1100
+ self._validate_model_class()
1101
+
1102
+ # priority: `generation_config` argument > `model.generation_config` (the default generation config)
1103
+ if generation_config is None:
1104
+ # legacy: users may modify the model configuration to control generation -- update the generation config
1105
+ # model attribute accordingly, if it was created from the model config
1106
+ if self.generation_config._from_model_config:
1107
+ new_generation_config = GenerationConfig.from_model_config(self.config)
1108
+ if new_generation_config != self.generation_config:
1109
+ warnings.warn(
1110
+ "You have modified the pretrained model configuration to control generation. This is a"
1111
+ " deprecated strategy to control generation and will be removed soon, in a future version."
1112
+ " Please use a generation configuration file (see"
1113
+ " https://huggingface.co/docs/transformers/main_classes/text_generation )"
1114
+ )
1115
+ self.generation_config = new_generation_config
1116
+ generation_config = self.generation_config
1117
+
1118
+ generation_config = copy.deepcopy(generation_config)
1119
+ model_kwargs = generation_config.update(**kwargs) # All unused kwargs must be model kwargs
1120
+ generation_config.validate()
1121
+ self._validate_model_kwargs(model_kwargs.copy())
1122
+
1123
+ # 2. Set generation parameters if not already defined
1124
+ logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
1125
+ stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
1126
+
1127
+ if generation_config.pad_token_id is None and generation_config.eos_token_id is not None:
1128
+ if model_kwargs.get("attention_mask", None) is None:
1129
+ logger.warning(
1130
+ "The attention mask and the pad token id were not set. As a consequence, you may observe "
1131
+ "unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results."
1132
+ )
1133
+ eos_token_id = generation_config.eos_token_id
1134
+ if isinstance(eos_token_id, list):
1135
+ eos_token_id = eos_token_id[0]
1136
+ logger.warning(f"Setting `pad_token_id` to `eos_token_id`:{eos_token_id} for open-end generation.")
1137
+ generation_config.pad_token_id = eos_token_id
1138
+
1139
+ # 3. Define model inputs
1140
+ # inputs_tensor has to be defined
1141
+ # model_input_name is defined if model-specific keyword input is passed
1142
+ # otherwise model_input_name is None
1143
+ # all model-specific keyword inputs are removed from `model_kwargs`
1144
+ inputs_tensor, model_input_name, model_kwargs = self._prepare_model_inputs(
1145
+ inputs, generation_config.bos_token_id, model_kwargs
1146
+ )
1147
+ batch_size = inputs_tensor.shape[0]
1148
+
1149
+ # 4. Define other model kwargs
1150
+ model_kwargs["output_attentions"] = generation_config.output_attentions
1151
+ model_kwargs["output_hidden_states"] = generation_config.output_hidden_states
1152
+ # decoder-only models with inputs_embeds forwarding must use caching (otherwise we can't detect whether we are
1153
+ # generating the first new token or not, and we only want to use the embeddings for the first new token)
1154
+ if not self.config.is_encoder_decoder and model_input_name == "inputs_embeds":
1155
+ model_kwargs["use_cache"] = True
1156
+ else:
1157
+ model_kwargs["use_cache"] = generation_config.use_cache
1158
+
1159
+ accepts_attention_mask = "attention_mask" in set(inspect.signature(self.forward).parameters.keys())
1160
+ requires_attention_mask = "encoder_outputs" not in model_kwargs
1161
+
1162
+ if model_kwargs.get("attention_mask", None) is None and requires_attention_mask and accepts_attention_mask:
1163
+ model_kwargs["attention_mask"] = self._prepare_attention_mask_for_generation(
1164
+ inputs_tensor, generation_config.pad_token_id, generation_config.eos_token_id
1165
+ )
1166
+ # decoder-only models should use left-padding for generation
1167
+ if not self.config.is_encoder_decoder:
1168
+ # If `input_ids` was given, check if the last id in any sequence is `pad_token_id`
1169
+ # Note: If using, `inputs_embeds` this check does not work, because we want to be more hands-off.
1170
+ if (
1171
+ generation_config.pad_token_id is not None
1172
+ and len(inputs_tensor.shape) == 2
1173
+ and torch.sum(inputs_tensor[:, -1] == generation_config.pad_token_id) > 0
1174
+ ):
1175
+ logger.warning(
1176
+ "A decoder-only architecture is being used, but right-padding was detected! For correct "
1177
+ "generation results, please set `padding_side='left'` when initializing the tokenizer."
1178
+ )
1179
+
1180
+ if self.config.is_encoder_decoder and "encoder_outputs" not in model_kwargs:
1181
+ # if model is encoder decoder encoder_outputs are created
1182
+ # and added to `model_kwargs`
1183
+ model_kwargs = self._prepare_encoder_decoder_kwargs_for_generation(
1184
+ inputs_tensor, model_kwargs, model_input_name
1185
+ )
1186
+
1187
+ # 5. Prepare `input_ids` which will be used for auto-regressive generation
1188
+ if self.config.is_encoder_decoder:
1189
+ input_ids, model_kwargs = self._prepare_decoder_input_ids_for_generation(
1190
+ batch_size=batch_size,
1191
+ model_input_name=model_input_name,
1192
+ model_kwargs=model_kwargs,
1193
+ decoder_start_token_id=generation_config.decoder_start_token_id,
1194
+ bos_token_id=generation_config.bos_token_id,
1195
+ device=inputs_tensor.device,
1196
+ )
1197
+ else:
1198
+ input_ids = inputs_tensor if model_input_name == "input_ids" else model_kwargs.pop("input_ids")
1199
+
1200
+ if streamer is not None:
1201
+ streamer.put(input_ids.cpu())
1202
+
1203
+ # 6. Prepare `max_length` depending on other stopping criteria.
1204
+ input_ids_length = input_ids.shape[-1]
1205
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
1206
+ if generation_config.max_new_tokens is not None:
1207
+ if not has_default_max_length:
1208
+ logger.warning(
1209
+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
1210
+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
1211
+ "Please refer to the documentation for more information. "
1212
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
1213
+ )
1214
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_length
1215
+ self._validate_generated_length(generation_config, input_ids_length, has_default_max_length)
1216
+
1217
+ # 7. determine generation mode
1218
+ generation_mode = self._get_generation_mode(generation_config, assistant_model)
1219
+
1220
+ if streamer is not None and (generation_config.num_beams > 1):
1221
+ raise ValueError(
1222
+ "`streamer` cannot be used with beam search (yet!). Make sure that `num_beams` is set to 1."
1223
+ )
1224
+
1225
+ if self.device.type != input_ids.device.type:
1226
+ warnings.warn(
1227
+ "You are calling .generate() with the `input_ids` being on a device type different"
1228
+ f" than your model's device. `input_ids` is on {input_ids.device.type}, whereas the model"
1229
+ f" is on {self.device.type}. You may experience unexpected behaviors or slower generation."
1230
+ " Please make sure that you have put `input_ids` to the"
1231
+ f" correct device by calling for example input_ids = input_ids.to('{self.device.type}') before"
1232
+ " running `.generate()`.",
1233
+ UserWarning,
1234
+ )
1235
+
1236
+ # 8. prepare distribution pre_processing samplers
1237
+ logits_processor = self._get_logits_processor(
1238
+ generation_config=generation_config,
1239
+ input_ids_seq_length=input_ids_length,
1240
+ encoder_input_ids=inputs_tensor,
1241
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1242
+ logits_processor=logits_processor,
1243
+ model_kwargs=model_kwargs,
1244
+ negative_prompt_ids=negative_prompt_ids,
1245
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
1246
+ )
1247
+
1248
+ # 9. prepare stopping criteria
1249
+ stopping_criteria = self._get_stopping_criteria(
1250
+ generation_config=generation_config, stopping_criteria=stopping_criteria
1251
+ )
1252
+ # 11. prepare logits warper
1253
+ logits_warper = self._get_logits_warper(generation_config)
1254
+
1255
+ # 12. expand input_ids with `num_return_sequences` additional sequences per batch
1256
+ input_ids, model_kwargs = self._expand_inputs_for_generation(
1257
+ input_ids=input_ids,
1258
+ expand_size=generation_config.num_return_sequences,
1259
+ is_encoder_decoder=self.config.is_encoder_decoder,
1260
+ **model_kwargs,
1261
+ )
1262
+
1263
+ # 13. run sample
1264
+ return self.sample(
1265
+ input_ids,
1266
+ logits_processor=logits_processor,
1267
+ logits_warper=logits_warper,
1268
+ stopping_criteria=stopping_criteria,
1269
+ pad_token_id=generation_config.pad_token_id,
1270
+ eos_token_id=generation_config.eos_token_id,
1271
+ output_scores=generation_config.output_scores,
1272
+ return_dict_in_generate=generation_config.return_dict_in_generate,
1273
+ synced_gpus=synced_gpus,
1274
+ streamer=streamer,
1275
+ **model_kwargs,
1276
+ )
1277
+
1278
+ def sample(
1279
+ self,
1280
+ input_ids: torch.LongTensor,
1281
+ logits_processor: Optional[LogitsProcessorList] = None,
1282
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
1283
+ logits_warper: Optional[LogitsProcessorList] = None,
1284
+ max_length: Optional[int] = None,
1285
+ pad_token_id: Optional[int] = None,
1286
+ eos_token_id: Optional[Union[int, List[int]]] = None,
1287
+ output_attentions: Optional[bool] = None,
1288
+ output_hidden_states: Optional[bool] = None,
1289
+ output_scores: Optional[bool] = None,
1290
+ return_dict_in_generate: Optional[bool] = None,
1291
+ synced_gpus: bool = False,
1292
+ streamer: Optional["BaseStreamer"] = None,
1293
+ **model_kwargs,
1294
+ ):
1295
+ # init values
1296
+ logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
1297
+ stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
1298
+ if max_length is not None:
1299
+ warnings.warn(
1300
+ "`max_length` is deprecated in this function, use"
1301
+ " `stopping_criteria=StoppingCriteriaList(MaxLengthCriteria(max_length=max_length))` instead.",
1302
+ UserWarning,
1303
+ )
1304
+ stopping_criteria = validate_stopping_criteria(stopping_criteria, max_length)
1305
+ logits_warper = logits_warper if logits_warper is not None else LogitsProcessorList()
1306
+ pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
1307
+ eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
1308
+ if isinstance(eos_token_id, int):
1309
+ eos_token_id = [eos_token_id]
1310
+ eos_token_id_tensor = torch.tensor(eos_token_id).to(input_ids.device) if eos_token_id is not None else None
1311
+ output_scores = output_scores if output_scores is not None else self.generation_config.output_scores
1312
+ output_attentions = (
1313
+ output_attentions if output_attentions is not None else self.generation_config.output_attentions
1314
+ )
1315
+ output_hidden_states = (
1316
+ output_hidden_states if output_hidden_states is not None else self.generation_config.output_hidden_states
1317
+ )
1318
+ return_dict_in_generate = (
1319
+ return_dict_in_generate
1320
+ if return_dict_in_generate is not None
1321
+ else self.generation_config.return_dict_in_generate
1322
+ )
1323
+
1324
+ # init attention / hidden states / scores tuples
1325
+ scores = () if (return_dict_in_generate and output_scores) else None
1326
+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
1327
+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None
1328
+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
1329
+
1330
+ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
1331
+ if return_dict_in_generate and self.config.is_encoder_decoder:
1332
+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
1333
+ encoder_hidden_states = (
1334
+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
1335
+ )
1336
+
1337
+ # keep track of which sequences are already finished
1338
+ unfinished_sequences = torch.ones(input_ids.shape[0], dtype=torch.long, device=input_ids.device)
1339
+
1340
+ this_peer_finished = False # used by synced_gpus only
1341
+ cls_logits = None
1342
+ # auto-regressive generation
1343
+ while True:
1344
+ if synced_gpus:
1345
+ # Under synced_gpus the `forward` call must continue until all gpus complete their sequence.
1346
+ # The following logic allows an early break if all peers finished generating their sequence
1347
+ this_peer_finished_flag = torch.tensor(0.0 if this_peer_finished else 1.0).to(input_ids.device)
1348
+ # send 0.0 if we finished, 1.0 otherwise
1349
+ dist.all_reduce(this_peer_finished_flag, op=dist.ReduceOp.SUM)
1350
+ # did all peers finish? the reduced sum will be 0.0 then
1351
+ if this_peer_finished_flag.item() == 0.0:
1352
+ break
1353
+
1354
+ # prepare model inputs
1355
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
1356
+
1357
+ # forward pass to get next token
1358
+ outputs = self(
1359
+ **model_inputs,
1360
+ return_dict=True,
1361
+ output_attentions=output_attentions,
1362
+ output_hidden_states=output_hidden_states,
1363
+ )
1364
+
1365
+ if synced_gpus and this_peer_finished:
1366
+ continue # don't waste resources running the code we don't need
1367
+
1368
+ next_token_logits = outputs.logits[:, -1, :]
1369
+ if outputs.cls_logits is not None:
1370
+ cls_logits = outputs.cls_logits
1371
+ # pre-process distribution
1372
+ next_token_scores = logits_processor(input_ids, next_token_logits)
1373
+ next_token_scores = logits_warper(input_ids, next_token_scores)
1374
+
1375
+ # Store scores, attentions and hidden_states when required
1376
+ if return_dict_in_generate:
1377
+ if output_scores:
1378
+ scores += (next_token_scores,)
1379
+ if output_attentions:
1380
+ decoder_attentions += (
1381
+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
1382
+ )
1383
+ if self.config.is_encoder_decoder:
1384
+ cross_attentions += (outputs.cross_attentions,)
1385
+
1386
+ if output_hidden_states:
1387
+ decoder_hidden_states += (
1388
+ (outputs.decoder_hidden_states,)
1389
+ if self.config.is_encoder_decoder
1390
+ else (outputs.hidden_states,)
1391
+ )
1392
+
1393
+ # sample
1394
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
1395
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
1396
+
1397
+ # finished sentences should have their next token be a padding token
1398
+ if eos_token_id is not None:
1399
+ if pad_token_id is None:
1400
+ raise ValueError("If `eos_token_id` is defined, make sure that `pad_token_id` is defined.")
1401
+ next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)
1402
+
1403
+ # update generated ids, model inputs, and length for next step
1404
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
1405
+ if streamer is not None:
1406
+ streamer.put(next_tokens.cpu())
1407
+ model_kwargs = self._update_model_kwargs_for_generation(
1408
+ outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
1409
+ )
1410
+
1411
+ # if eos_token was found in one sentence, set sentence to finished
1412
+ if eos_token_id_tensor is not None:
1413
+ unfinished_sequences = unfinished_sequences.mul(
1414
+ next_tokens.tile(eos_token_id_tensor.shape[0], 1).ne(eos_token_id_tensor.unsqueeze(1)).prod(dim=0)
1415
+ )
1416
+
1417
+ # stop when each sentence is finished
1418
+ if unfinished_sequences.max() == 0:
1419
+ this_peer_finished = True
1420
+
1421
+ # stop if we exceed the maximum length
1422
+ if stopping_criteria(input_ids, scores):
1423
+ this_peer_finished = True
1424
+
1425
+ if this_peer_finished and not synced_gpus:
1426
+ break
1427
+
1428
+ if streamer is not None:
1429
+ streamer.end()
1430
+ predicted_class_ids = torch.argmax(cls_logits, dim=1)
1431
+
1432
+ return input_ids, predicted_class_ids
1433
+
1434
+
1435
+ class RotaryEmbedding(torch.nn.Module):
1436
+ def __init__(self, dim, base=10000):
1437
+ super().__init__()
1438
+ self.dim = dim
1439
+ self.base = base
1440
+ self.inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
1441
+ if importlib.util.find_spec("einops") is None:
1442
+ raise RuntimeError("einops is required for Rotary Embedding")
1443
+
1444
+ self._rotary_pos_emb_cache = None
1445
+ self._seq_len_cached = 0
1446
+ self._ntk_alpha_cached = 1.0
1447
+
1448
+ def update_rotary_pos_emb_cache(self, max_seq_len, offset=0, ntk_alpha=1.0):
1449
+ seqlen = max_seq_len + offset
1450
+ if seqlen > self._seq_len_cached or ntk_alpha != self._ntk_alpha_cached:
1451
+ base = self.base * ntk_alpha ** (self.dim / (self.dim - 2))
1452
+ self.inv_freq = 1.0 / (
1453
+ base
1454
+ ** (
1455
+ torch.arange(0, self.dim, 2, device=self.inv_freq.device).float()
1456
+ / self.dim
1457
+ )
1458
+ )
1459
+ self._seq_len_cached = max(2 * seqlen, 16)
1460
+ self._ntk_alpha_cached = ntk_alpha
1461
+ seq = torch.arange(self._seq_len_cached, device=self.inv_freq.device)
1462
+ freqs = torch.outer(seq.type_as(self.inv_freq), self.inv_freq)
1463
+
1464
+ emb = torch.cat((freqs, freqs), dim=-1)
1465
+ from einops import rearrange
1466
+
1467
+ emb = rearrange(emb, "n d -> 1 n 1 d")
1468
+
1469
+ cos, sin = emb.cos(), emb.sin()
1470
+ self._rotary_pos_emb_cache = [cos, sin]
1471
+
1472
+ def forward(self, max_seq_len, offset=0, ntk_alpha=1.0):
1473
+ self.update_rotary_pos_emb_cache(max_seq_len, offset, ntk_alpha)
1474
+ cos, sin = self._rotary_pos_emb_cache
1475
+ return [cos[:, offset : offset + max_seq_len], sin[:, offset : offset + max_seq_len]]
1476
+
1477
+ def _rotate_half(x):
1478
+ from einops import rearrange
1479
+
1480
+ x = rearrange(x, "... (j d) -> ... j d", j=2)
1481
+ x1, x2 = x.unbind(dim=-2)
1482
+ return torch.cat((-x2, x1), dim=-1)
1483
+
1484
+
1485
+ def apply_rotary_pos_emb(t, freqs):
1486
+ cos, sin = freqs
1487
+ if apply_rotary_emb_func is not None and t.is_cuda:
1488
+ t_ = t.float()
1489
+ cos = cos.squeeze(0).squeeze(1)[:, : cos.shape[-1] // 2]
1490
+ sin = sin.squeeze(0).squeeze(1)[:, : sin.shape[-1] // 2]
1491
+ output = apply_rotary_emb_func(t_, cos, sin).type_as(t)
1492
+ return output
1493
+ else:
1494
+ rot_dim = freqs[0].shape[-1]
1495
+ cos, sin = freqs
1496
+ t_, t_pass_ = t[..., :rot_dim], t[..., rot_dim:]
1497
+ t_ = t_.float()
1498
+ t_pass_ = t_pass_.float()
1499
+ t_ = (t_ * cos) + (_rotate_half(t_) * sin)
1500
+ return torch.cat((t_, t_pass_), dim=-1).type_as(t)
1501
+
1502
+
1503
+ class RMSNorm(torch.nn.Module):
1504
+ def __init__(self, dim: int, eps: float = 1e-6):
1505
+ super().__init__()
1506
+ self.eps = eps
1507
+ self.weight = nn.Parameter(torch.ones(dim))
1508
+
1509
+ def _norm(self, x):
1510
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
1511
+
1512
+ def forward(self, x):
1513
+ if rms_norm is not None and x.is_cuda:
1514
+ return rms_norm(x, self.weight, self.eps)
1515
+ else:
1516
+ output = self._norm(x.float()).type_as(x)
1517
+ return output * self.weight
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1430a5d1087f68a3caf675e16bad15d810afcf9e78d66d4f0bd2703e7b667b89
3
+ size 19314226418
qwen.tiktoken ADDED
The diff for this file is too large to render. See raw diff
 
qwen_generation_utils.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Generation support."""
7
+
8
+ from typing import Tuple, List, Union, Iterable
9
+
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn.functional as F
13
+ from transformers import PreTrainedTokenizer
14
+ from transformers import logging
15
+ from transformers.generation import LogitsProcessor
16
+
17
+ logger = logging.get_logger(__name__)
18
+
19
+ # Types.
20
+ HistoryType = List[Tuple[str, str]]
21
+ TokensType = List[int]
22
+ BatchTokensType = List[List[int]]
23
+
24
+
25
+ def pad_batch(batch: BatchTokensType, pad_id: int, seq_length: int) -> BatchTokensType:
26
+ for tokens in batch:
27
+ context_length = len(tokens)
28
+ if context_length < seq_length:
29
+ tokens.extend([pad_id] * (seq_length - context_length))
30
+ return batch
31
+
32
+
33
+ def get_ltor_masks_and_position_ids(
34
+ data,
35
+ eod_token,
36
+ reset_position_ids,
37
+ reset_attention_mask,
38
+ eod_mask_loss,
39
+ ):
40
+ """Build masks and position id for left to right model."""
41
+
42
+ # Extract batch size and sequence length.
43
+ micro_batch_size, seq_length = data.size()
44
+
45
+ # Attention mask (lower triangular).
46
+ if reset_attention_mask:
47
+ att_mask_batch = micro_batch_size
48
+ else:
49
+ att_mask_batch = 1
50
+ attention_mask = torch.tril(
51
+ torch.ones((att_mask_batch, seq_length, seq_length), device=data.device)
52
+ ).view(att_mask_batch, 1, seq_length, seq_length)
53
+
54
+ # Loss mask.
55
+ loss_mask = torch.ones(data.size(), dtype=torch.float, device=data.device)
56
+ if eod_mask_loss:
57
+ loss_mask[data == eod_token] = 0.0
58
+
59
+ # Position ids.
60
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=data.device)
61
+ position_ids = position_ids.unsqueeze(0).expand_as(data)
62
+ # We need to clone as the ids will be modifed based on batch index.
63
+ if reset_position_ids:
64
+ position_ids = position_ids.clone()
65
+
66
+ if reset_position_ids or reset_attention_mask:
67
+ # Loop through the batches:
68
+ for b in range(micro_batch_size):
69
+
70
+ # Find indecies where EOD token is.
71
+ eod_index = position_ids[b, data[b] == eod_token]
72
+ # Detach indecies from positions if going to modify positions.
73
+ if reset_position_ids:
74
+ eod_index = eod_index.clone()
75
+
76
+ # Loop through EOD indecies:
77
+ prev_index = 0
78
+ for j in range(eod_index.size()[0]):
79
+ i = eod_index[j]
80
+ # Mask attention loss.
81
+ if reset_attention_mask:
82
+ attention_mask[b, 0, (i + 1) :, : (i + 1)] = 0
83
+ # Reset positions.
84
+ if reset_position_ids:
85
+ position_ids[b, (i + 1) :] -= i + 1 - prev_index
86
+ prev_index = i + 1
87
+
88
+ # Convert attention mask to binary:
89
+ attention_mask = attention_mask < 0.5
90
+
91
+ return attention_mask, loss_mask, position_ids
92
+
93
+
94
+ def get_batch(context_tokens: torch.LongTensor, eod_id: int):
95
+ """Generate batch from context tokens."""
96
+ # Move to GPU.
97
+ tokens = context_tokens.contiguous().to(context_tokens.device)
98
+ # Get the attention mask and postition ids.
99
+ attention_mask, _, position_ids = get_ltor_masks_and_position_ids(
100
+ tokens,
101
+ eod_id,
102
+ reset_position_ids=False,
103
+ reset_attention_mask=False,
104
+ eod_mask_loss=False,
105
+ )
106
+ return tokens, attention_mask, position_ids
107
+
108
+
109
+ def get_stop_words_ids(chat_format, tokenizer):
110
+ if chat_format == "raw":
111
+ stop_words_ids = [tokenizer.encode("Human:"), [tokenizer.eod_id]]
112
+ elif chat_format == "chatml":
113
+ stop_words_ids = [[tokenizer.im_end_id], [tokenizer.im_start_id]]
114
+ else:
115
+ raise NotImplementedError(f"Unknown chat format {chat_format!r}")
116
+ return stop_words_ids
117
+
118
+
119
+ def make_context(
120
+ tokenizer: PreTrainedTokenizer,
121
+ query: str,
122
+ history: List[Tuple[str, str]] = None,
123
+ system: str = "",
124
+ max_window_size: int = 6144,
125
+ chat_format: str = "chatml",
126
+ ):
127
+ if history is None:
128
+ history = []
129
+
130
+ if chat_format == "chatml":
131
+ im_start, im_end = "<|im_start|>", "<|im_end|>"
132
+ im_start_tokens = [tokenizer.im_start_id]
133
+ im_end_tokens = [tokenizer.im_end_id]
134
+ nl_tokens = tokenizer.encode("\n")
135
+
136
+ def _tokenize_str(role, content):
137
+ return f"{role}\n{content}", tokenizer.encode(
138
+ role, allowed_special=set(tokenizer.IMAGE_ST)
139
+ ) + nl_tokens + tokenizer.encode(content, allowed_special=set(tokenizer.IMAGE_ST))
140
+
141
+ system_text, system_tokens_part = _tokenize_str("system", system)
142
+ system_tokens = im_start_tokens + system_tokens_part + im_end_tokens
143
+
144
+ raw_text = ""
145
+ context_tokens = []
146
+
147
+ for turn_query, turn_response in reversed(history):
148
+ query_text, query_tokens_part = _tokenize_str("user", turn_query)
149
+ query_tokens = im_start_tokens + query_tokens_part + im_end_tokens
150
+ if turn_response is not None:
151
+ response_text, response_tokens_part = _tokenize_str(
152
+ "assistant", turn_response
153
+ )
154
+ response_tokens = im_start_tokens + response_tokens_part + im_end_tokens
155
+
156
+ next_context_tokens = nl_tokens + query_tokens + nl_tokens + response_tokens
157
+ prev_chat = (
158
+ f"\n{im_start}{query_text}{im_end}\n{im_start}{response_text}{im_end}"
159
+ )
160
+ else:
161
+ next_context_tokens = nl_tokens + query_tokens + nl_tokens
162
+ prev_chat = f"\n{im_start}{query_text}{im_end}\n"
163
+
164
+ current_context_size = (
165
+ len(system_tokens) + len(next_context_tokens) + len(context_tokens)
166
+ )
167
+ if current_context_size < max_window_size:
168
+ context_tokens = next_context_tokens + context_tokens
169
+ raw_text = prev_chat + raw_text
170
+ else:
171
+ break
172
+
173
+ context_tokens = system_tokens + context_tokens
174
+ raw_text = f"{im_start}{system_text}{im_end}" + raw_text
175
+ context_tokens += (
176
+ nl_tokens
177
+ + im_start_tokens
178
+ + _tokenize_str("user", query)[1]
179
+ + im_end_tokens
180
+ + nl_tokens
181
+ + im_start_tokens
182
+ + tokenizer.encode("assistant")
183
+ + nl_tokens
184
+ )
185
+ raw_text += f"\n{im_start}user\n{query}{im_end}\n{im_start}assistant\n"
186
+
187
+ elif chat_format == "raw":
188
+ raw_text = query
189
+ context_tokens = tokenizer.encode(raw_text)
190
+ else:
191
+ raise NotImplementedError(f"Unknown chat format {chat_format!r}")
192
+
193
+ return raw_text, context_tokens
194
+
195
+
196
+ def _decode_default(
197
+ tokens: List[int],
198
+ *,
199
+ stop_words: List[str],
200
+ eod_words: List[str],
201
+ tokenizer: PreTrainedTokenizer,
202
+ raw_text_len: int,
203
+ verbose: bool = False,
204
+ return_end_reason: bool = False,
205
+ errors: str='replace',
206
+ ):
207
+ trim_decode_tokens = tokenizer.decode(tokens, errors=errors)[raw_text_len:]
208
+ if verbose:
209
+ print("\nRaw Generate: ", trim_decode_tokens)
210
+
211
+ end_reason = f"Gen length {len(tokens)}"
212
+ for stop_word in stop_words:
213
+ trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip()
214
+ for eod_word in eod_words:
215
+ if eod_word in trim_decode_tokens:
216
+ end_reason = f"Gen {eod_word!r}"
217
+ trim_decode_tokens = trim_decode_tokens.split(eod_word)[0]
218
+ trim_decode_tokens = trim_decode_tokens.strip()
219
+ if verbose:
220
+ print("\nEnd Reason:", end_reason)
221
+ print("\nGenerate: ", trim_decode_tokens)
222
+
223
+ if return_end_reason:
224
+ return trim_decode_tokens, end_reason
225
+ else:
226
+ return trim_decode_tokens
227
+
228
+
229
+ def _decode_chatml(
230
+ tokens: List[int],
231
+ *,
232
+ stop_words: List[str],
233
+ eod_token_ids: List[int],
234
+ tokenizer: PreTrainedTokenizer,
235
+ raw_text_len: int,
236
+ context_length: int,
237
+ verbose: bool = False,
238
+ return_end_reason: bool = False,
239
+ errors: str='replace'
240
+ ):
241
+ end_reason = f"Gen length {len(tokens)}"
242
+ eod_token_idx = context_length
243
+ for eod_token_idx in range(context_length, len(tokens)):
244
+ if tokens[eod_token_idx] in eod_token_ids:
245
+ end_reason = f"Gen {tokenizer.decode([tokens[eod_token_idx]])!r}"
246
+ break
247
+
248
+ trim_decode_tokens = tokenizer.decode(tokens[:eod_token_idx], errors=errors)[raw_text_len:]
249
+ if verbose:
250
+ print("\nRaw Generate w/o EOD:", tokenizer.decode(tokens, errors=errors)[raw_text_len:])
251
+ print("\nRaw Generate:", trim_decode_tokens)
252
+ print("\nEnd Reason:", end_reason)
253
+ for stop_word in stop_words:
254
+ trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip()
255
+ trim_decode_tokens = trim_decode_tokens.strip()
256
+ if verbose:
257
+ print("\nGenerate:", trim_decode_tokens)
258
+
259
+ if return_end_reason:
260
+ return trim_decode_tokens, end_reason
261
+ else:
262
+ return trim_decode_tokens
263
+
264
+
265
+ def decode_tokens(
266
+ tokens: Union[torch.LongTensor, TokensType],
267
+ tokenizer: PreTrainedTokenizer,
268
+ raw_text_len: int,
269
+ context_length: int,
270
+ chat_format: str,
271
+ verbose: bool = False,
272
+ return_end_reason: bool = False,
273
+ errors: str="replace",
274
+ ) -> str:
275
+ if torch.is_tensor(tokens):
276
+ tokens = tokens.cpu().numpy().tolist()
277
+
278
+ if chat_format == "chatml":
279
+ return _decode_chatml(
280
+ tokens,
281
+ stop_words=[],
282
+ eod_token_ids=[tokenizer.im_start_id, tokenizer.im_end_id],
283
+ tokenizer=tokenizer,
284
+ raw_text_len=raw_text_len,
285
+ context_length=context_length,
286
+ verbose=verbose,
287
+ return_end_reason=return_end_reason,
288
+ errors=errors,
289
+ )
290
+ elif chat_format == "raw":
291
+ return _decode_default(
292
+ tokens,
293
+ stop_words=["<|endoftext|>"],
294
+ eod_words=["<|endoftext|>"],
295
+ tokenizer=tokenizer,
296
+ raw_text_len=raw_text_len,
297
+ verbose=verbose,
298
+ return_end_reason=return_end_reason,
299
+ errors=errors,
300
+ )
301
+ else:
302
+ raise NotImplementedError(f"Unknown chat format {chat_format!r}")
303
+
304
+
305
+ class StopWordsLogitsProcessor(LogitsProcessor):
306
+ """
307
+ :class:`transformers.LogitsProcessor` that enforces that when specified sequences appear, stop geration.
308
+
309
+ Args:
310
+ stop_words_ids (:obj:`List[List[int]]`):
311
+ List of list of token ids of stop ids. In order to get the tokens of the words
312
+ that should not appear in the generated text, use :obj:`tokenizer(bad_word,
313
+ add_prefix_space=True).input_ids`.
314
+ eos_token_id (:obj:`int`):
315
+ The id of the `end-of-sequence` token.
316
+ """
317
+
318
+ def __init__(self, stop_words_ids: Iterable[Iterable[int]], eos_token_id: int):
319
+
320
+ if not isinstance(stop_words_ids, List) or len(stop_words_ids) == 0:
321
+ raise ValueError(
322
+ f"`stop_words_ids` has to be a non-emtpy list, but is {stop_words_ids}."
323
+ )
324
+ if any(not isinstance(bad_word_ids, list) for bad_word_ids in stop_words_ids):
325
+ raise ValueError(
326
+ f"`stop_words_ids` has to be a list of lists, but is {stop_words_ids}."
327
+ )
328
+ if any(
329
+ any(
330
+ (not isinstance(token_id, (int, np.integer)) or token_id < 0)
331
+ for token_id in stop_word_ids
332
+ )
333
+ for stop_word_ids in stop_words_ids
334
+ ):
335
+ raise ValueError(
336
+ f"Each list in `stop_words_ids` has to be a list of positive integers, but is {stop_words_ids}."
337
+ )
338
+
339
+ self.stop_words_ids = list(
340
+ filter(
341
+ lambda bad_token_seq: bad_token_seq != [eos_token_id], stop_words_ids
342
+ )
343
+ )
344
+ self.eos_token_id = eos_token_id
345
+ for stop_token_seq in self.stop_words_ids:
346
+ assert (
347
+ len(stop_token_seq) > 0
348
+ ), "Stop words token sequences {} cannot have an empty list".format(
349
+ stop_words_ids
350
+ )
351
+
352
+ def __call__(
353
+ self, input_ids: torch.LongTensor, scores: torch.FloatTensor
354
+ ) -> torch.FloatTensor:
355
+ stopped_samples = self._calc_stopped_samples(input_ids)
356
+ for i, should_stop in enumerate(stopped_samples):
357
+ if should_stop:
358
+ scores[i, self.eos_token_id] = float(2**15)
359
+ return scores
360
+
361
+ def _tokens_match(self, prev_tokens: torch.LongTensor, tokens: List[int]) -> bool:
362
+ if len(tokens) == 0:
363
+ # if bad word tokens is just one token always ban it
364
+ return True
365
+ elif len(tokens) > len(prev_tokens):
366
+ # if bad word tokens are longer then prev input_ids they can't be equal
367
+ return False
368
+ elif prev_tokens[-len(tokens) :].tolist() == tokens:
369
+ # if tokens match
370
+ return True
371
+ else:
372
+ return False
373
+
374
+ def _calc_stopped_samples(self, prev_input_ids: Iterable[int]) -> Iterable[int]:
375
+ stopped_samples = []
376
+ for prev_input_ids_slice in prev_input_ids:
377
+ match = False
378
+ for stop_token_seq in self.stop_words_ids:
379
+ if self._tokens_match(prev_input_ids_slice, stop_token_seq):
380
+ # if tokens do not match continue
381
+ match = True
382
+ break
383
+ stopped_samples.append(match)
384
+
385
+ return stopped_samples
386
+
387
+
388
+ def top_k_logits(logits, top_k=0, top_p=0.0, filter_value=-float("Inf")):
389
+ """This function has been mostly taken from hf.rst.imnversational
390
+ ai code at
391
+ https://medium.com/huggingface/how-to-build-a-state-of-the-art-
392
+ conversational-ai-with-transfer-learning-2d818ac26313"""
393
+
394
+ if top_k > 0:
395
+ # Remove all tokens with a probability less than the
396
+ # last token of the top-k
397
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
398
+ logits[indices_to_remove] = filter_value
399
+
400
+ if top_p > 0.0:
401
+ # Cconvert to 1D
402
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
403
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
404
+
405
+ # Remove tokens with cumulative probability above the threshold
406
+ sorted_indices_to_remove = cumulative_probs > top_p
407
+ # Shift the indices to the right to keep also the first token
408
+ # above the threshold
409
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
410
+ sorted_indices_to_remove[..., 0] = 0
411
+ for i in range(sorted_indices.size(0)):
412
+ indices_to_remove = sorted_indices[i][sorted_indices_to_remove[i]]
413
+ logits[i][indices_to_remove] = filter_value
414
+
415
+ return logits
416
+
417
+
418
+ def switch(val1, val2, boolean):
419
+ boolean = boolean.type_as(val1)
420
+ return (1 - boolean) * val1 + boolean * val2
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,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {},
3
+ "additional_special_tokens": [],
4
+ "auto_map": {
5
+ "AutoTokenizer": [
6
+ "tokenization_qwen.QWenTokenizer",
7
+ null
8
+ ]
9
+ },
10
+ "clean_up_tokenization_spaces": true,
11
+ "model_max_length": 512,
12
+ "padding_side": "right",
13
+ "tokenizer_class": "QWenTokenizer",
14
+ "tokenizer_file": null
15
+ }
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:89ab6a5d4c4bb8e9ea3547ffc12b94253af9285e13b0a907914cadbaec63363e
3
+ size 6200
visual.py ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 torch.allclose(query, 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: List[str]):
417
+ images = []
418
+ for image_path in image_paths:
419
+ if image_path.startswith("http://") or image_path.startswith("https://"):
420
+ image = Image.open(requests.get(image_path, stream=True).raw)
421
+ else:
422
+ image = Image.open(image_path)
423
+ image = image.convert("RGB")
424
+ images.append(self.image_transform(image))
425
+ images = torch.stack(images, dim=0)
426
+ return self(images)