echo840 commited on
Commit
fa345bd
1 Parent(s): d28c270

Add application file

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