PyTorch
English
monkey
custom_code
EDGEwww25 commited on
Commit
558a8e9
1 Parent(s): 9bf6b53

add model files (without .bin params)

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