asabet commited on
Commit
b5aa3ad
1 Parent(s): 2cd32e9

Upload CogVLMForCausalLM

Browse files
adapter_config.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "alpha_pattern": {},
3
+ "auto_mapping": null,
4
+ "base_model_name_or_path": "THUDM/cogvlm2-llama3-chat-19B",
5
+ "bias": "none",
6
+ "fan_in_fan_out": false,
7
+ "inference_mode": true,
8
+ "init_lora_weights": true,
9
+ "layer_replication": null,
10
+ "layers_pattern": null,
11
+ "layers_to_transform": null,
12
+ "loftq_config": {},
13
+ "lora_alpha": 32,
14
+ "lora_dropout": 0.1,
15
+ "megatron_config": null,
16
+ "megatron_core": "megatron.core",
17
+ "modules_to_save": null,
18
+ "peft_type": "LORA",
19
+ "r": 128,
20
+ "rank_pattern": {},
21
+ "revision": null,
22
+ "target_modules": [
23
+ "language_expert_query_key_value",
24
+ "vision_expert_query_key_value"
25
+ ],
26
+ "task_type": "CAUSAL_LM",
27
+ "use_dora": false,
28
+ "use_rslora": false
29
+ }
adapter_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1d600c90d07e8f167eeaac98de6e9d81de42de28dd2dad31c6349bc1063f81de
3
+ size 335564968
configuration_cogvlm.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Literal
2
+ from transformers import PretrainedConfig
3
+
4
+
5
+ class CogVLMConfig(PretrainedConfig):
6
+ _auto_class = "AutoConfig"
7
+
8
+ def __init__(
9
+ self,
10
+ vocab_size=128256,
11
+ hidden_size=4096,
12
+ intermediate_size=14336,
13
+ num_hidden_layers=32,
14
+ num_attention_heads=32,
15
+ num_multi_query_heads=8,
16
+ hidden_act='silu',
17
+ max_position_embeddings=8192,
18
+ initializer_range=0.02,
19
+ rms_norm_eps=1e-05,
20
+ template_version: Literal["base", "chat"] = "chat",
21
+ bos_token_id=128000,
22
+ eos_token_id=128001,
23
+ tie_word_embeddings=False,
24
+ use_cache=True,
25
+ **kwargs,
26
+ ):
27
+ self.hidden_size = hidden_size
28
+ self.intermediate_size = intermediate_size
29
+ self.num_attention_heads = num_attention_heads
30
+ self.num_multi_query_heads = num_multi_query_heads
31
+ self.max_position_embeddings = max_position_embeddings
32
+ self.rms_norm_eps = rms_norm_eps
33
+ self.initializer_range = initializer_range
34
+ self.vocab_size = vocab_size
35
+ self.num_hidden_layers = num_hidden_layers
36
+ self.hidden_act = hidden_act
37
+ self.template_version = template_version
38
+ self.use_cache = use_cache
39
+ super().__init__(
40
+ bos_token_id=bos_token_id,
41
+ eos_token_id=eos_token_id,
42
+ tie_word_embeddings=tie_word_embeddings,
43
+ **kwargs,
44
+ )
generation_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 128000,
4
+ "do_sample": true,
5
+ "eos_token_id": [
6
+ 128001,
7
+ 128009
8
+ ],
9
+ "max_length": 4096,
10
+ "pad_token_id": 128002,
11
+ "temperature": 0.6,
12
+ "top_p": 0.9,
13
+ "transformers_version": "4.40.2"
14
+ }
modeling_cogvlm.py ADDED
@@ -0,0 +1,848 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """largely copy from llama and adapt for cogvlm"""
2
+ import warnings
3
+ import packaging.version
4
+ from typing import TYPE_CHECKING, Optional, Tuple, List, Union, Literal, Dict, Any
5
+
6
+ import math
7
+ import torch
8
+ import transformers
9
+ from torch import nn
10
+ from torch.nn import CrossEntropyLoss
11
+ from torchvision import transforms
12
+ from einops import rearrange
13
+ from torch.utils.checkpoint import checkpoint
14
+
15
+ from transformers import PreTrainedModel, PreTrainedTokenizer
16
+ from transformers.utils.logging import get_logger
17
+ from transformers.activations import ACT2FN
18
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
19
+
20
+ from .configuration_cogvlm import CogVLMConfig
21
+ from .util import FastRotaryEmbedding
22
+ from .visual import EVA2CLIPModel
23
+
24
+ if TYPE_CHECKING:
25
+ from transformers.utils import ModelOutput
26
+
27
+ logger = get_logger(__name__)
28
+
29
+ LANGUAGE_TOKEN_TYPE = 0
30
+ VISION_TOKEN_TYPE = 1
31
+ TRANSFORMERS_ABOVE_441 = (
32
+ True
33
+ if packaging.version.parse(transformers.__version__)
34
+ >= packaging.version.parse("4.42.0")
35
+ else False
36
+ )
37
+
38
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
39
+ def _make_causal_mask(
40
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
41
+ ):
42
+ """
43
+ Make causal mask used for bi-directional self-attention.
44
+ """
45
+ bsz, tgt_len = input_ids_shape
46
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
47
+ mask_cond = torch.arange(mask.size(-1), device=device)
48
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
49
+ mask = mask.to(dtype)
50
+
51
+ if past_key_values_length > 0:
52
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
53
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
54
+
55
+
56
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
57
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
58
+ """
59
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
60
+ """
61
+ bsz, src_len = mask.size()
62
+ tgt_len = tgt_len if tgt_len is not None else src_len
63
+
64
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
65
+
66
+ inverted_mask = 1.0 - expanded_mask
67
+
68
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
69
+
70
+
71
+ class RMSNorm(nn.Module):
72
+ def __init__(self, hidden_size, eps=1e-5):
73
+ super().__init__()
74
+ self.weight = nn.Parameter(torch.ones(hidden_size))
75
+ self.variance_epsilon = eps
76
+
77
+ def forward(self, hidden_states):
78
+ input_dtype = hidden_states.dtype
79
+ hidden_states = hidden_states.to(torch.float32)
80
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
81
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
82
+ return (self.weight * hidden_states).to(input_dtype)
83
+
84
+
85
+ class MLP(nn.Module):
86
+ def __init__(self, config):
87
+ super().__init__()
88
+ self.hidden_size = config.hidden_size
89
+ self.intermediate_size = config.intermediate_size
90
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
91
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
92
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
93
+ self.act_fn = ACT2FN[config.hidden_act]
94
+
95
+ def forward(self, x):
96
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
97
+ return down_proj
98
+
99
+
100
+ def get_expert_mask(token_type_ids: "torch.LongTensor(B, L)") -> "[torch.BoolTensor(B, L), torch.BoolTensor(B, L)]":
101
+ vision_token_mask = torch.zeros_like(token_type_ids, dtype=torch.bool)
102
+ vision_token_mask[:, :-1] = (token_type_ids[:, :-1] == VISION_TOKEN_TYPE) & (token_type_ids[:, 1:] == VISION_TOKEN_TYPE)
103
+ language_token_mask = ~vision_token_mask
104
+ return vision_token_mask, language_token_mask
105
+
106
+
107
+ class VisionExpertMLP(nn.Module):
108
+ def __init__(self, config):
109
+ super().__init__()
110
+ self.language_mlp = MLP(config)
111
+ self.vision_mlp = MLP(config)
112
+
113
+ def forward(self, hidden_states: "torch.Tensor(B, L, D)", token_type_ids: "torch.LongTensor(B, L)"):
114
+ output = torch.empty(hidden_states.shape, dtype=hidden_states.dtype, device=hidden_states.device)
115
+ vision_token_mask, language_token_mask = get_expert_mask(token_type_ids)
116
+ output[vision_token_mask] = self.vision_mlp(hidden_states[vision_token_mask])
117
+ output[language_token_mask] = self.language_mlp(hidden_states[language_token_mask])
118
+ return output
119
+
120
+
121
+ def attention_fn(
122
+ query_layer: "torch.tensor(B, H, L, HD)",
123
+ key_layer: "torch.tensor(B, H, L, HD)",
124
+ value_layer: "torch.tensor(B, H, L, HD)",
125
+ attention_mask: "torch.tensor(B, H, L, HD)",
126
+ *,
127
+ scaling_attention_score: bool = True,
128
+ attention_dropout: nn.Module = None
129
+ ):
130
+ attention_mask_bool = (attention_mask == 0)
131
+ is_low_triangle = (attention_mask_bool == torch.ones_like(attention_mask_bool, dtype=torch.float).tril()).all()
132
+ is_full = (attention_mask_bool > 0).all()
133
+ if not (int(torch.__version__.split('.')[0]) >= 2):
134
+ warnings.warn("It's recommended to use torch2.0 or higher.")
135
+ if int(torch.__version__.split('.')[0]) >= 2 and scaling_attention_score and (is_full or is_low_triangle):
136
+ dropout_p = 0. if attention_dropout is None or not attention_dropout.training else attention_dropout.p
137
+ return torch.nn.functional.scaled_dot_product_attention(
138
+ query_layer, key_layer, value_layer,
139
+ attn_mask=None,
140
+ dropout_p=dropout_p,
141
+ is_causal=not is_full
142
+ )
143
+ else:
144
+ if scaling_attention_score:
145
+ query_layer = query_layer / math.sqrt(query_layer.shape[-1])
146
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
147
+ attention_scores = attention_scores + attention_mask
148
+ attention_scores = nn.functional.softmax(attention_scores, dim=-1, dtype=torch.float32).to(query_layer.dtype)
149
+ if attention_dropout is not None:
150
+ attention_scores = attention_dropout(attention_scores)
151
+ context_layer = torch.matmul(attention_scores, value_layer)
152
+ return context_layer
153
+
154
+
155
+ class VisionExpertAttention(nn.Module):
156
+ def __init__(self, config):
157
+ super().__init__()
158
+ self.config = config
159
+ self.hidden_size = config.hidden_size
160
+ self.num_attention_heads = config.num_attention_heads
161
+ self.num_multi_query_heads = config.num_multi_query_heads
162
+ self.hidden_size_per_attention_head = self.hidden_size // self.num_attention_heads
163
+ self.stride = [self.num_attention_heads, self.num_multi_query_heads, self.num_multi_query_heads]
164
+ self.qkv_size = self.hidden_size + self.hidden_size_per_attention_head * self.num_multi_query_heads * 2
165
+ self.head_dim = self.hidden_size // self.num_attention_heads
166
+ self.max_position_embeddings = config.max_position_embeddings
167
+ self.rotary_emb = FastRotaryEmbedding(dim=self.head_dim, pos_idx_in_fp32=False, base=500000)
168
+ self.vision_expert_query_key_value = nn.Linear(self.hidden_size, self.qkv_size, bias=True)
169
+ self.vision_expert_dense = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
170
+ self.language_expert_query_key_value = nn.Linear(self.hidden_size, self.qkv_size, bias=False)
171
+ self.language_expert_dense = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
172
+
173
+ def _transpose_for_scores(self, tensor):
174
+ """Transpose a 3D tensor [B, L, H*HD] into a 4D tensor with size [B H L HD]."""
175
+ new_tensor_shape = tensor.size()[:-1] + \
176
+ (-1, # flexible for multi-query
177
+ self.hidden_size_per_attention_head)
178
+ tensor = tensor.view(*new_tensor_shape)
179
+ return tensor.permute(0, 2, 1, 3)
180
+
181
+ def forward(
182
+ self,
183
+ hidden_states: torch.Tensor,
184
+ token_type_ids: torch.LongTensor,
185
+ position_ids: torch.LongTensor,
186
+ attention_mask: Optional[torch.Tensor] = None,
187
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
188
+ output_attentions: bool = False,
189
+ use_cache: bool = False,
190
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
191
+ bsz, q_len, _ = hidden_states.size()
192
+ vision_token_mask, language_token_mask = get_expert_mask(token_type_ids)
193
+
194
+ shape = list(hidden_states.shape)
195
+ shape[-1] = self.qkv_size
196
+ mixed_raw_layer = torch.empty(shape, dtype=hidden_states.dtype, device=hidden_states.device)
197
+ mixed_raw_layer[vision_token_mask] = self.vision_expert_query_key_value(hidden_states[vision_token_mask])
198
+ mixed_raw_layer[language_token_mask] = self.language_expert_query_key_value(hidden_states[language_token_mask])
199
+
200
+ # query_states, key_states, value_states = torch.split(mixed_raw_layer, self.hidden_size, dim=-1)
201
+ factor = mixed_raw_layer.size()[-1] // sum(self.stride)
202
+ query_states, key_states, value_states = torch.split(mixed_raw_layer, [factor * x for x in self.stride], dim=-1)
203
+
204
+ query_states = self._transpose_for_scores(query_states) # B, H, L, HD
205
+ key_states = self._transpose_for_scores(key_states) # B, H, L, HD
206
+ value_states = self._transpose_for_scores(value_states) # B, H, L, HD
207
+
208
+ kv_seq_len = key_states.shape[-2]
209
+ if past_key_value is not None:
210
+ kv_seq_len += past_key_value[0].shape[-2]
211
+
212
+ query_states, key_states = self.rotary_emb(query_states, key_states, position_ids=position_ids, max_seqlen=position_ids.max() + 1)
213
+
214
+ if past_key_value is not None:
215
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
216
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
217
+
218
+ past_key_value = (key_states, value_states) if use_cache else None
219
+
220
+ key_states = key_states.unsqueeze(2).expand(-1, -1, self.num_attention_heads // self.num_multi_query_heads, -1, -1).contiguous().view(
221
+ bsz, self.num_attention_heads, *key_states.shape[2:])
222
+ value_states = value_states.unsqueeze(2).expand(-1, -1, self.num_attention_heads // self.num_multi_query_heads, -1,
223
+ -1).contiguous().view(bsz, self.num_attention_heads, *value_states.shape[2:])
224
+
225
+ context_layer = attention_fn(
226
+ query_layer=query_states, key_layer=key_states, value_layer=value_states, attention_mask=attention_mask,
227
+ scaling_attention_score=True, attention_dropout=None)
228
+ if context_layer.size() != (bsz, self.num_attention_heads, q_len, self.head_dim):
229
+ raise ValueError(
230
+ f"`attn_output` should be of size {(bsz, self.num_attention_heads, q_len, self.head_dim)}, but is"
231
+ f" {context_layer.size()}"
232
+ )
233
+ context_layer = context_layer.transpose(1, 2).contiguous().reshape(bsz, q_len, self.hidden_size)
234
+
235
+ attn_output = torch.empty(context_layer.shape, dtype=hidden_states.dtype, device=hidden_states.device)
236
+ attn_output[vision_token_mask] = self.vision_expert_dense(context_layer[vision_token_mask])
237
+ attn_output[language_token_mask] = self.language_expert_dense(context_layer[language_token_mask])
238
+
239
+ if output_attentions:
240
+ warnings.warn("output_attentions is not implemented.")
241
+
242
+ return attn_output, None, past_key_value
243
+
244
+
245
+ class CogVLMDecoderLayer(nn.Module):
246
+ def __init__(self, config):
247
+ super().__init__()
248
+ self.hidden_size = config.hidden_size
249
+ self.self_attn = VisionExpertAttention(config=config)
250
+ self.mlp = VisionExpertMLP(config)
251
+ self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
252
+ self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
253
+
254
+ def forward(
255
+ self,
256
+ hidden_states: torch.Tensor,
257
+ token_type_ids: torch.LongTensor,
258
+ position_ids: torch.LongTensor,
259
+ attention_mask: Optional[torch.Tensor] = None,
260
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
261
+ output_attentions: Optional[bool] = False,
262
+ use_cache: Optional[bool] = False,
263
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
264
+ residual = hidden_states
265
+
266
+ hidden_states = self.input_layernorm(hidden_states)
267
+
268
+ # Self Attention
269
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
270
+ hidden_states=hidden_states,
271
+ token_type_ids=token_type_ids,
272
+ position_ids=position_ids,
273
+ attention_mask=attention_mask,
274
+ past_key_value=past_key_value,
275
+ output_attentions=output_attentions,
276
+ use_cache=use_cache,
277
+ )
278
+ hidden_states = residual + hidden_states
279
+
280
+ # Fully Connected
281
+ residual = hidden_states
282
+ hidden_states = self.post_attention_layernorm(hidden_states)
283
+ hidden_states = self.mlp(hidden_states, token_type_ids=token_type_ids)
284
+ hidden_states = residual + hidden_states
285
+
286
+ outputs = (hidden_states,)
287
+
288
+ if output_attentions:
289
+ outputs += (self_attn_weights,)
290
+
291
+ if use_cache:
292
+ outputs += (present_key_value,)
293
+
294
+ return outputs # type: ignore
295
+
296
+
297
+ class CogVLMPreTrainedModel(PreTrainedModel):
298
+ config_class = CogVLMConfig
299
+ base_model_prefix = "model"
300
+ supports_gradient_checkpointing = False
301
+ _no_split_modules = ["CogVLMDecoderLayer"]
302
+ _skip_keys_device_placement = "past_key_values"
303
+
304
+ def _init_weights(self, module):
305
+ std = self.config.initializer_range
306
+ if isinstance(module, nn.Linear):
307
+ module.weight.data.normal_(mean=0.0, std=std)
308
+ if module.bias is not None:
309
+ module.bias.data.zero_()
310
+ elif isinstance(module, nn.Embedding):
311
+ module.weight.data.normal_(mean=0.0, std=std)
312
+ if module.padding_idx is not None:
313
+ module.weight.data[module.padding_idx].zero_()
314
+
315
+
316
+ def is_empty(images_list: Optional[List[List[torch.Tensor]]]):
317
+ if images_list is None or len(images_list) == 0:
318
+ return True
319
+ for image_list in images_list:
320
+ if len(image_list):
321
+ return False
322
+ return True
323
+
324
+
325
+ def build_position_ids(x: "torch.BoolTensor(B, L)", attention_mask: Optional["torch.BoolTensor(B, L)"] = None) -> "torch.LongTensor(B, L)":
326
+ if attention_mask is not None:
327
+ tmp = x.clone()
328
+ tmp[~(attention_mask.bool())] = -1
329
+ else:
330
+ tmp = x.clone()
331
+ # image boi eoi token as LANGUAGE_TOKEN_TYPE
332
+ is_boi_eoi = torch.zeros_like(x, dtype=torch.bool)
333
+ is_boi_eoi[:, 1:] |= (tmp[:, 1:] == VISION_TOKEN_TYPE) & (tmp[:, :-1] == LANGUAGE_TOKEN_TYPE)
334
+ is_boi_eoi[:, 0] |= (tmp[:, 0] == VISION_TOKEN_TYPE)
335
+ is_boi_eoi[:, :-1] |= (tmp[:, :-1] == VISION_TOKEN_TYPE) & (tmp[:, 1:] == LANGUAGE_TOKEN_TYPE)
336
+ is_boi_eoi[:, -1] |= (tmp[:, -1] == VISION_TOKEN_TYPE)
337
+ tmp[is_boi_eoi] = LANGUAGE_TOKEN_TYPE
338
+ # final position ids
339
+ y = torch.zeros_like(x, dtype=torch.long)
340
+ y[:, 1:] = (tmp[:, 1:] == LANGUAGE_TOKEN_TYPE) | ((tmp[:, 1:] == VISION_TOKEN_TYPE) & (tmp[:, :-1] == LANGUAGE_TOKEN_TYPE))
341
+ y = y.cumsum(dim=-1)
342
+ return y
343
+
344
+
345
+ class CogVLMModel(CogVLMPreTrainedModel):
346
+ def __init__(self, config):
347
+ super().__init__(config)
348
+ self.padding_idx = 128002
349
+ self.vocab_size = config.vocab_size
350
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
351
+ self.layers = nn.ModuleList([CogVLMDecoderLayer(config) for _ in range(config.num_hidden_layers)])
352
+ self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
353
+
354
+ self.vision = EVA2CLIPModel(config)
355
+
356
+ self.gradient_checkpointing = False
357
+ # Initialize weights and apply final processing
358
+ self.post_init()
359
+
360
+ def encode_images(self, images: List[List[torch.Tensor]]) -> torch.Tensor:
361
+ images_list, images = images, []
362
+
363
+ images = []
364
+ for image_list in images_list:
365
+ for image in image_list:
366
+ images.append(image)
367
+
368
+ images = torch.stack(images)
369
+ images_features = self.vision(images)
370
+ return images_features
371
+
372
+ def forward(
373
+ self,
374
+ input_ids: torch.LongTensor = None,
375
+ images: List[List[torch.Tensor]] = None,
376
+ token_type_ids: Optional[torch.LongTensor] = None,
377
+ attention_mask: Optional[torch.Tensor] = None,
378
+ position_ids: Optional[torch.LongTensor] = None,
379
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
380
+ inputs_embeds: Optional[torch.FloatTensor] = None,
381
+ use_cache: Optional[bool] = None,
382
+ output_attentions: Optional[bool] = None,
383
+ output_hidden_states: Optional[bool] = None,
384
+ return_dict: Optional[bool] = None,
385
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
386
+ """take care of image_encode, token_type_ids, position_ids and (attention_mask = None is fine)"""
387
+
388
+ if past_key_values is not None:
389
+ pass # generate mode with past_key_values. the image features are already mapped
390
+ else:
391
+ # not allow for inputs_embeds, because we want to process image feature
392
+ assert input_ids is not None and inputs_embeds is None, f"{input_ids} {inputs_embeds}"
393
+ if not is_empty(images): # multi-modality
394
+ assert token_type_ids is not None, f"multi-modality requires `token_type_ids`!"
395
+ assert len(input_ids) == len(images), f"{len(input_ids)} {len(images)}"
396
+ inputs_embeds = self.embed_tokens(input_ids)
397
+ images_features = self.encode_images(images)
398
+ images_features = rearrange(images_features, 'b n d -> (b n) d')
399
+ images_features = images_features.to(dtype=inputs_embeds.dtype, device=inputs_embeds.device)
400
+ inputs_embeds = inputs_embeds.index_put([token_type_ids == VISION_TOKEN_TYPE], images_features)
401
+ else: # single-modality
402
+ if token_type_ids is None:
403
+ token_type_ids = torch.ones_like(input_ids, dtype=torch.long, device=input_ids.device) * LANGUAGE_TOKEN_TYPE
404
+ assert not (token_type_ids == VISION_TOKEN_TYPE).any(), f"{(token_type_ids == VISION_TOKEN_TYPE).sum()}"
405
+ inputs_embeds = self.embed_tokens(input_ids)
406
+
407
+ if position_ids is None:
408
+ position_ids = build_position_ids(token_type_ids, attention_mask)
409
+ input_ids = None
410
+ return self.llm_forward(
411
+ input_ids=input_ids,
412
+ token_type_ids=token_type_ids,
413
+ attention_mask=attention_mask,
414
+ position_ids=position_ids,
415
+ past_key_values=past_key_values,
416
+ inputs_embeds=inputs_embeds,
417
+ use_cache=use_cache,
418
+ output_attentions=output_attentions,
419
+ output_hidden_states=output_hidden_states,
420
+ return_dict=return_dict,
421
+ )
422
+
423
+ def llm_forward(
424
+ self,
425
+ input_ids: torch.LongTensor = None,
426
+ token_type_ids: torch.LongTensor = None,
427
+ attention_mask: Optional[torch.Tensor] = None,
428
+ position_ids: Optional[torch.LongTensor] = None,
429
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
430
+ inputs_embeds: Optional[torch.FloatTensor] = None,
431
+ use_cache: Optional[bool] = None,
432
+ output_attentions: Optional[bool] = None,
433
+ output_hidden_states: Optional[bool] = None,
434
+ return_dict: Optional[bool] = None,
435
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
436
+ """largely copy from llama forward and adapt for cogvlm with `token_type_ids`"""
437
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
438
+ output_hidden_states = (
439
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
440
+ )
441
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
442
+
443
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
444
+
445
+ # retrieve input_ids and inputs_embeds
446
+ if input_ids is not None and inputs_embeds is not None:
447
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
448
+ elif input_ids is not None:
449
+ batch_size, seq_length = input_ids.shape
450
+ elif inputs_embeds is not None:
451
+ batch_size, seq_length, _ = inputs_embeds.shape
452
+ else:
453
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
454
+
455
+ seq_length_with_past = seq_length
456
+ past_key_values_length = 0
457
+
458
+ if past_key_values is not None:
459
+ past_key_values_length = past_key_values[0][0].shape[2]
460
+ seq_length_with_past = seq_length_with_past + past_key_values_length
461
+
462
+ if position_ids is None:
463
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
464
+ position_ids = torch.arange(
465
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
466
+ )
467
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
468
+ else:
469
+ position_ids = position_ids.view(-1, seq_length).long()
470
+
471
+ if inputs_embeds is None:
472
+ inputs_embeds = self.embed_tokens(input_ids)
473
+ # embed positions
474
+ if attention_mask is None:
475
+ attention_mask = torch.ones(
476
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
477
+ )
478
+ attention_mask = self._prepare_decoder_attention_mask(
479
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
480
+ )
481
+
482
+ hidden_states = inputs_embeds
483
+
484
+ # decoder layers
485
+ all_hidden_states = () if output_hidden_states else None
486
+ all_self_attns = () if output_attentions else None
487
+ next_decoder_cache = () if use_cache else None
488
+
489
+ for idx, decoder_layer in enumerate(self.layers):
490
+ if output_hidden_states:
491
+ all_hidden_states += (hidden_states,)
492
+
493
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
494
+
495
+ def custom(index):
496
+ def custom_forward(
497
+ hidden_states,
498
+ token_type_ids=token_type_ids,
499
+ attention_mask=attention_mask,
500
+ position_ids=position_ids,
501
+ past_key_value=past_key_value,
502
+ output_attentions=output_attentions,
503
+ use_cache=use_cache,
504
+ ):
505
+ layer = self.layers[index]
506
+ outputs = layer(
507
+ hidden_states,
508
+ token_type_ids=token_type_ids,
509
+ attention_mask=attention_mask,
510
+ position_ids=position_ids,
511
+ past_key_value=past_key_value,
512
+ output_attentions=output_attentions,
513
+ use_cache=use_cache,
514
+ )
515
+ return outputs
516
+
517
+ return custom_forward
518
+ # layer_outputs = decoder_layer(
519
+ # hidden_states,
520
+ # token_type_ids=token_type_ids,
521
+ # attention_mask=attention_mask,
522
+ # position_ids=position_ids,
523
+ # past_key_value=past_key_value,
524
+ # output_attentions=output_attentions,
525
+ # use_cache=use_cache,
526
+ # )
527
+ layer_outputs = checkpoint(custom(idx),
528
+ hidden_states,
529
+ use_reentrant=False
530
+ )
531
+ hidden_states = layer_outputs[0]
532
+
533
+ if use_cache:
534
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
535
+
536
+ if output_attentions:
537
+ all_self_attns += (layer_outputs[1],)
538
+
539
+ hidden_states = self.norm(hidden_states)
540
+
541
+ # add hidden states from the last decoder layer
542
+ if output_hidden_states:
543
+ all_hidden_states += (hidden_states,)
544
+
545
+ next_cache = next_decoder_cache if use_cache else None
546
+ if not return_dict:
547
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
548
+ return BaseModelOutputWithPast(
549
+ last_hidden_state=hidden_states,
550
+ past_key_values=next_cache,
551
+ hidden_states=all_hidden_states,
552
+ attentions=all_self_attns,
553
+ )
554
+
555
+ def get_input_embeddings(self):
556
+ return self.embed_tokens
557
+
558
+ def set_input_embeddings(self, value):
559
+ self.embed_tokens = value
560
+
561
+ # noinspection PyMethodMayBeStatic
562
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
563
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
564
+ # create causal mask
565
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
566
+ combined_attention_mask = None
567
+ if input_shape[-1] > 1:
568
+ combined_attention_mask = _make_causal_mask(
569
+ input_shape,
570
+ inputs_embeds.dtype,
571
+ device=inputs_embeds.device,
572
+ past_key_values_length=past_key_values_length,
573
+ )
574
+
575
+ if attention_mask is not None:
576
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
577
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
578
+ inputs_embeds.device
579
+ )
580
+ combined_attention_mask = (
581
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
582
+ )
583
+
584
+ return combined_attention_mask
585
+
586
+
587
+ def _history_to_prompt(signal_type, history, query):
588
+ if signal_type == 'base':
589
+ return query
590
+ elif signal_type == 'vqa':
591
+ answer_format = 'Short answer:'
592
+ elif signal_type == 'chat':
593
+ answer_format = 'Answer:'
594
+ else:
595
+ assert False, f"Unknown signal type {signal_type}"
596
+
597
+ prompt = ''
598
+ for i, (old_query, response) in enumerate(history):
599
+ prompt += 'Question: ' + old_query + " {} ".format(answer_format) + response + "\n"
600
+ prompt += 'Question: {} {}'.format(query, answer_format)
601
+ return prompt
602
+
603
+
604
+ class CogVLMForCausalLM(CogVLMPreTrainedModel):
605
+ _auto_class = "AutoModelForCausalLM"
606
+
607
+ def __init__(self, config):
608
+ super().__init__(config)
609
+ self.model = CogVLMModel(config)
610
+ self.vocab_size = config.vocab_size
611
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
612
+
613
+ # Initialize weights and apply final processing
614
+ self.post_init()
615
+
616
+ def get_input_embeddings(self):
617
+ return self.model.embed_tokens
618
+
619
+ def set_input_embeddings(self, value):
620
+ self.model.embed_tokens = value
621
+
622
+ def get_output_embeddings(self):
623
+ return self.lm_head
624
+
625
+ def set_output_embeddings(self, new_embeddings):
626
+ self.lm_head = new_embeddings
627
+
628
+ def set_decoder(self, decoder):
629
+ self.model = decoder
630
+
631
+ def get_decoder(self):
632
+ return self.model
633
+
634
+ def forward(
635
+ self,
636
+ input_ids: torch.LongTensor = None,
637
+ images: List[List[torch.Tensor]] = None,
638
+ token_type_ids: Optional[torch.LongTensor] = None,
639
+ attention_mask: Optional[torch.Tensor] = None,
640
+ position_ids: Optional[torch.LongTensor] = None,
641
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
642
+ inputs_embeds: Optional[torch.FloatTensor] = None,
643
+ use_cache: Optional[bool] = None,
644
+ output_attentions: Optional[bool] = None,
645
+ output_hidden_states: Optional[bool] = None,
646
+ return_dict: Optional[bool] = None,
647
+ labels: Optional[torch.LongTensor] = None,
648
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
649
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
650
+ output_hidden_states = (
651
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
652
+ )
653
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
654
+
655
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
656
+ outputs = self.model(
657
+ input_ids=input_ids,
658
+ images=images,
659
+ token_type_ids=token_type_ids,
660
+ attention_mask=attention_mask,
661
+ position_ids=position_ids,
662
+ past_key_values=past_key_values,
663
+ inputs_embeds=inputs_embeds,
664
+ use_cache=use_cache,
665
+ output_attentions=output_attentions,
666
+ output_hidden_states=output_hidden_states,
667
+ return_dict=return_dict,
668
+ )
669
+
670
+ hidden_states = outputs[0]
671
+ logits = self.lm_head(hidden_states)
672
+ logits = logits.float()
673
+
674
+ loss = None
675
+ if labels is not None:
676
+ # Shift so that tokens < n predict n
677
+ shift_logits = logits[..., :-1, :].contiguous()
678
+ shift_labels = labels[..., 1:].contiguous()
679
+ # Flatten the tokens
680
+ loss_fct = CrossEntropyLoss()
681
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
682
+ shift_labels = shift_labels.view(-1)
683
+ # Enable model parallelism
684
+ shift_labels = shift_labels.to(shift_logits.device)
685
+ loss = loss_fct(shift_logits, shift_labels)
686
+
687
+ if not return_dict:
688
+ output = (logits,) + outputs[1:]
689
+ return (loss,) + output if loss is not None else output
690
+
691
+ return CausalLMOutputWithPast(
692
+ loss=loss,
693
+ logits=logits,
694
+ past_key_values=outputs.past_key_values,
695
+ hidden_states=outputs.hidden_states,
696
+ attentions=outputs.attentions,
697
+ )
698
+
699
+ def _prepare_attention_mask_for_generation(
700
+ self,
701
+ inputs: torch.Tensor,
702
+ pad_token_id: Optional[int],
703
+ eos_token_id: Optional[Union[int, List[int]]],
704
+ ) -> torch.LongTensor:
705
+ return torch.ones(inputs.shape[:2], dtype=torch.long, device=inputs.device) # type: ignore
706
+
707
+ def prepare_inputs_for_generation(
708
+ self, input_ids, token_type_ids, images=None, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
709
+ ):
710
+ # build position_ids if needed
711
+ position_ids = kwargs.get("position_ids", None)
712
+ if position_ids is None:
713
+ position_ids = build_position_ids(token_type_ids, attention_mask)
714
+
715
+ if past_key_values:
716
+ input_ids = input_ids[:, -1:]
717
+ token_type_ids = token_type_ids[:, -1:]
718
+ position_ids = position_ids[:, -1:]
719
+
720
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
721
+ if inputs_embeds is not None and past_key_values is None:
722
+ model_inputs = {"inputs_embeds": inputs_embeds}
723
+ else:
724
+ model_inputs = {"input_ids": input_ids}
725
+
726
+ model_inputs.update(
727
+ {
728
+ "token_type_ids": token_type_ids,
729
+ "images": images,
730
+ "position_ids": position_ids,
731
+ "past_key_values": past_key_values,
732
+ "use_cache": kwargs.get("use_cache"),
733
+ "attention_mask": attention_mask,
734
+ }
735
+ )
736
+ return model_inputs
737
+
738
+ def _update_model_kwargs_for_generation(
739
+ self,
740
+ outputs: "ModelOutput",
741
+ model_kwargs: Dict[str, Any],
742
+ is_encoder_decoder: bool = False,
743
+ standardize_cache_format: bool = False,
744
+ ) -> Dict[str, Any]:
745
+ # update past_key_values
746
+ if TRANSFORMERS_ABOVE_441:
747
+ cache_name, cache = self._extract_past_from_model_output(outputs)
748
+ model_kwargs[cache_name] = cache
749
+ else:
750
+ model_kwargs["past_key_values"] = self._extract_past_from_model_output(
751
+ outputs, standardize_cache_format=standardize_cache_format
752
+ )
753
+ if getattr(outputs, "state", None) is not None:
754
+ model_kwargs["state"] = outputs.state
755
+
756
+ # update token_type_ids with last value
757
+ if "token_type_ids" in model_kwargs:
758
+ token_type_ids = model_kwargs["token_type_ids"]
759
+ new_token_type_ids = torch.ones(size=(token_type_ids.shape[0], 1), dtype=token_type_ids.dtype, device=token_type_ids.device) * LANGUAGE_TOKEN_TYPE
760
+ model_kwargs["token_type_ids"] = torch.cat([token_type_ids, new_token_type_ids], dim=-1)
761
+
762
+ if not is_encoder_decoder:
763
+ # update attention mask
764
+ if "attention_mask" in model_kwargs:
765
+ attention_mask = model_kwargs["attention_mask"]
766
+ model_kwargs["attention_mask"] = torch.cat(
767
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
768
+ )
769
+ else:
770
+ # update decoder attention mask
771
+ if "decoder_attention_mask" in model_kwargs:
772
+ decoder_attention_mask = model_kwargs["decoder_attention_mask"]
773
+ model_kwargs["decoder_attention_mask"] = torch.cat(
774
+ [decoder_attention_mask, decoder_attention_mask.new_ones((decoder_attention_mask.shape[0], 1))],
775
+ dim=-1,
776
+ )
777
+
778
+ return model_kwargs
779
+
780
+ def _reorder_cache(self, past_key_values, beam_idx):
781
+ reordered_past = ()
782
+ for layer_past in past_key_values:
783
+ reordered_past += (
784
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
785
+ )
786
+ return reordered_past
787
+
788
+ def build_conversation_input_ids(
789
+ self,
790
+ tokenizer: "PreTrainedTokenizer",
791
+ *,
792
+ query: str,
793
+ history: Optional[List[Tuple[str, str]]] = None,
794
+ images: Optional[List["PIL.Image"]] = None,
795
+ template_version: Optional[Literal["base", "chat", "vqa"]] = None,
796
+ answer: str = None,
797
+ ):
798
+ image_size: int = self.config.vision_config['image_size']
799
+ patch_size: int = self.config.vision_config['patch_size']
800
+ template_version = template_version or self.config.template_version
801
+ assert images is None or len(images) <= 1, f"not support multi images by now."
802
+ history = history or []
803
+ text = _history_to_prompt(template_version, history, query)
804
+ input_ids = [tokenizer.bos_token_id]
805
+ token_type_ids = [LANGUAGE_TOKEN_TYPE]
806
+ if images is not None and len(images) == 1:
807
+ # vision
808
+ transform = transforms.Compose(
809
+ [
810
+ transforms.Resize(
811
+ (image_size, image_size), interpolation=transforms.InterpolationMode.BICUBIC
812
+ ),
813
+ transforms.ToTensor(),
814
+ transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
815
+ ]
816
+ )
817
+ images = [transform(images[0])]
818
+ # language
819
+ vision_token_num = (image_size // patch_size // 2) * (image_size // patch_size // 2) + 2
820
+
821
+ tokenizer.pad_token_id = 128002 # llama3 adapt for cogvlm
822
+
823
+ input_ids += [tokenizer.pad_token_id] * vision_token_num
824
+ token_type_ids += [VISION_TOKEN_TYPE] * vision_token_num
825
+ text_ids = tokenizer.encode(text, add_special_tokens=False)
826
+
827
+ if answer is not None:
828
+ answer_ids = tokenizer.encode(answer, add_special_tokens=False)
829
+ answer_ids += [tokenizer.eos_token_id]
830
+ text_ids += answer_ids
831
+
832
+
833
+ input_ids += text_ids
834
+ token_type_ids += [LANGUAGE_TOKEN_TYPE] * len(text_ids)
835
+ attention_mask = [1] * len(input_ids)
836
+ if answer is not None:
837
+ labels = [-100 for _ in range(len(input_ids) - len(answer_ids))] + answer_ids
838
+ labels = torch.tensor(labels, dtype=torch.long)
839
+ else:
840
+ labels = None
841
+
842
+ return {
843
+ 'input_ids': torch.tensor(input_ids, dtype=torch.long),
844
+ 'token_type_ids': torch.tensor(token_type_ids, dtype=torch.long),
845
+ 'attention_mask': torch.tensor(attention_mask, dtype=torch.long),
846
+ 'images': images,
847
+ 'labels': labels,
848
+ }
util.py ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Tuple, Union
2
+
3
+ import torch
4
+ from einops import rearrange, repeat
5
+ import torch.nn.functional as F
6
+
7
+ import triton
8
+ import triton.language as tl
9
+
10
+
11
+ # @triton.autotune(
12
+ # configs=[
13
+ # triton.Config({"BLOCK_M": 2}),
14
+ # triton.Config({"BLOCK_M": 4}),
15
+ # triton.Config({"BLOCK_M": 8}),
16
+ # triton.Config({"BLOCK_M": 16}),
17
+ # ],
18
+ # key=["CACHE_KEY_SEQLEN", "BLOCK_K", "INTERLEAVED"],
19
+ # )
20
+ @triton.jit
21
+ def rotary_kernel(
22
+ OUT, # Pointers to matrices
23
+ X,
24
+ COS,
25
+ SIN,
26
+ CU_SEQLENS,
27
+ SEQLEN_OFFSETS, # this could be int or a pointer
28
+ # Matrix dimensions
29
+ seqlen,
30
+ nheads,
31
+ rotary_dim,
32
+ seqlen_ro,
33
+ CACHE_KEY_SEQLEN,
34
+ # strides
35
+ stride_out_batch,
36
+ stride_out_nheads,
37
+ stride_out_seqlen,
38
+ stride_out_headdim,
39
+ stride_x_batch,
40
+ stride_x_nheads,
41
+ stride_x_seqlen,
42
+ stride_x_headdim,
43
+ # Meta-parameters
44
+ BLOCK_K: tl.constexpr,
45
+ IS_SEQLEN_OFFSETS_TENSOR: tl.constexpr,
46
+ IS_VARLEN: tl.constexpr,
47
+ INTERLEAVED: tl.constexpr,
48
+ CONJUGATE: tl.constexpr,
49
+ BLOCK_M: tl.constexpr,
50
+ ):
51
+ pid_m = tl.program_id(axis=0)
52
+ pid_batch = tl.program_id(axis=1)
53
+ pid_head = tl.program_id(axis=2)
54
+ rotary_dim_half = rotary_dim // 2
55
+
56
+ if not IS_VARLEN:
57
+ X = X + pid_batch * stride_x_batch + pid_head * stride_x_nheads
58
+ OUT = OUT + pid_batch * stride_out_batch + pid_head * stride_out_nheads
59
+ COS = COS + pid_batch * seqlen_ro * rotary_dim_half
60
+ SIN = SIN + pid_batch * seqlen_ro * rotary_dim_half
61
+ else:
62
+ start_idx = tl.load(CU_SEQLENS + pid_batch)
63
+ seqlen = tl.load(CU_SEQLENS + pid_batch + 1) - start_idx
64
+ X = X + start_idx * stride_x_seqlen + pid_head * stride_x_nheads
65
+ OUT = OUT + start_idx * stride_out_seqlen + pid_head * stride_out_nheads
66
+
67
+ if pid_m * BLOCK_M >= seqlen:
68
+ return
69
+ rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
70
+ if not IS_SEQLEN_OFFSETS_TENSOR:
71
+ rm_cs = rm + SEQLEN_OFFSETS
72
+ else:
73
+ rm_cs = rm + tl.load(SEQLEN_OFFSETS + pid_batch)
74
+ rk = tl.arange(0, BLOCK_K)
75
+ rk_half = tl.arange(0, BLOCK_K // 2)
76
+
77
+ if not INTERLEAVED:
78
+ # Load the 1st and 2nd halves of X, do calculation, then store to 1st and 2nd halves of OUT
79
+ X = X + (rm[:, None] * stride_x_seqlen + rk_half[None, :] * stride_x_headdim)
80
+ COS = COS + (rm_cs[:, None] * rotary_dim_half + rk_half[None, :])
81
+ SIN = SIN + (rm_cs[:, None] * rotary_dim_half + rk_half[None, :])
82
+ cos = tl.load(
83
+ COS, mask=(rm_cs[:, None] < seqlen_ro) & (rk_half[None, :] < rotary_dim_half), other=1.0
84
+ )
85
+ sin = tl.load(
86
+ SIN, mask=(rm_cs[:, None] < seqlen_ro) & (rk_half[None, :] < rotary_dim_half), other=0.0
87
+ )
88
+ x0 = tl.load(
89
+ X, mask=(rm[:, None] < seqlen) & (rk_half[None, :] < rotary_dim_half), other=0.0
90
+ )
91
+ x1 = tl.load(
92
+ X + rotary_dim_half * stride_x_headdim,
93
+ mask=(rm[:, None] < seqlen) & (rk_half[None, :] < rotary_dim_half),
94
+ other=0.0,
95
+ )
96
+ if CONJUGATE:
97
+ sin = -sin
98
+ o0 = x0 * cos - x1 * sin
99
+ o1 = x0 * sin + x1 * cos
100
+ # write back result
101
+ OUT = OUT + (rm[:, None] * stride_out_seqlen + rk_half[None, :] * stride_out_headdim)
102
+ tl.store(OUT, o0, mask=(rm[:, None] < seqlen) & (rk_half[None, :] < rotary_dim_half))
103
+ tl.store(
104
+ OUT + rotary_dim_half * stride_out_headdim,
105
+ o1,
106
+ mask=(rm[:, None] < seqlen) & (rk_half[None, :] < rotary_dim_half),
107
+ )
108
+ else:
109
+ # We don't want to load X[0, 2, 4, ...] and X[1, 3, 5, ...] separately since both are slow.
110
+ # Instead, we load x0 = X[0, 1, 2, 3, ...] and x1 = X[1, 0, 3, 2, ...].
111
+ # Loading x0 will be fast but x1 will be slow.
112
+ # Then we load cos = COS[0, 0, 1, 1, ...] and sin = SIN[0, 0, 1, 1, ...].
113
+ # Then we do the calculation and use tl.where to pick put the right outputs for the even
114
+ # and for the odd indices.
115
+ rk_swap = rk + ((rk + 1) % 2) * 2 - 1 # 1, 0, 3, 2, 5, 4, ...
116
+ rk_repeat = tl.arange(0, BLOCK_K) // 2
117
+ X0 = X + (rm[:, None] * stride_x_seqlen + rk[None, :] * stride_x_headdim)
118
+ X1 = X + (rm[:, None] * stride_x_seqlen + rk_swap[None, :] * stride_x_headdim)
119
+ COS = COS + (rm_cs[:, None] * rotary_dim_half + rk_repeat[None, :])
120
+ SIN = SIN + (rm_cs[:, None] * rotary_dim_half + rk_repeat[None, :])
121
+ cos = tl.load(
122
+ COS,
123
+ mask=(rm_cs[:, None] < seqlen_ro) & (rk_repeat[None, :] < rotary_dim_half),
124
+ other=1.0,
125
+ ).to(tl.float32)
126
+ sin = tl.load(
127
+ SIN,
128
+ mask=(rm_cs[:, None] < seqlen_ro) & (rk_repeat[None, :] < rotary_dim_half),
129
+ other=0.0,
130
+ ).to(tl.float32)
131
+ x0 = tl.load(X0, mask=(rm[:, None] < seqlen) & (rk[None, :] < rotary_dim), other=0.0).to(
132
+ tl.float32
133
+ )
134
+ x1 = tl.load(
135
+ X1, mask=(rm[:, None] < seqlen) & (rk_swap[None, :] < rotary_dim), other=0.0
136
+ ).to(tl.float32)
137
+ if CONJUGATE:
138
+ sin = -sin
139
+ x0_cos = x0 * cos
140
+ x1_sin = x1 * sin
141
+ out = tl.where(rk[None, :] % 2 == 0, x0_cos - x1_sin, x0_cos + x1_sin)
142
+ OUT = OUT + (rm[:, None] * stride_out_seqlen + rk[None, :] * stride_out_headdim)
143
+ tl.store(OUT, out, mask=(rm[:, None] < seqlen) & (rk[None, :] < rotary_dim))
144
+
145
+
146
+ def apply_rotary(
147
+ x: torch.Tensor,
148
+ cos: torch.Tensor,
149
+ sin: torch.Tensor,
150
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
151
+ cu_seqlens: Optional[torch.Tensor] = None,
152
+ max_seqlen: Optional[int] = None,
153
+ interleaved=False,
154
+ inplace=False,
155
+ conjugate=False,
156
+ ) -> torch.Tensor:
157
+ """
158
+ Arguments:
159
+ x: (batch, seqlen, nheads, headdim) if cu_seqlens is None
160
+ else (total_seqlen, nheads, headdim).
161
+ cos: (seqlen_ro, rotary_dim / 2)
162
+ sin: (seqlen_ro, rotary_dim / 2)
163
+ seqlen_offsets: integer or integer tensor of size (batch,)
164
+ cu_seqlens: (batch + 1,) or None
165
+ max_seqlen: int
166
+ Returns:
167
+ y: (batch, seqlen, nheads, headdim)
168
+ """
169
+
170
+ batch, nheads, seqlen, headdim = x.shape
171
+
172
+ batch_ro, seqlen_ro, rotary_dim = cos.shape
173
+
174
+ assert batch == batch_ro
175
+ assert sin.shape == cos.shape
176
+ rotary_dim *= 2
177
+ assert rotary_dim <= headdim, "rotary_dim must be <= headdim"
178
+ assert headdim <= 256, "Only support headdim <= 256"
179
+
180
+ assert seqlen_ro >= seqlen, "seqlen_ro must be >= seqlen"
181
+
182
+ assert (
183
+ cos.dtype == sin.dtype
184
+ ), f"cos and sin must have the same dtype, got {cos.dtype} and {sin.dtype}"
185
+ assert (
186
+ x.dtype == cos.dtype
187
+ ), f"Input and cos/sin must have the same dtype, got {x.dtype} and {cos.dtype}"
188
+
189
+ cos, sin = cos.contiguous(), sin.contiguous()
190
+ if isinstance(seqlen_offsets, torch.Tensor):
191
+ assert seqlen_offsets.shape == (batch,)
192
+ assert seqlen_offsets.dtype in [torch.int32, torch.int64]
193
+ seqlen_offsets = seqlen_offsets.contiguous()
194
+ else:
195
+ assert seqlen_offsets + seqlen <= seqlen_ro
196
+
197
+ output = torch.empty_like(x) if not inplace else x
198
+ if rotary_dim < headdim and not inplace:
199
+ output[..., rotary_dim:].copy_(x[..., rotary_dim:])
200
+
201
+ BLOCK_K = (
202
+ 32
203
+ if rotary_dim <= 32
204
+ else (64 if rotary_dim <= 64 else (128 if rotary_dim <= 128 else 256))
205
+ )
206
+ grid = lambda META: (triton.cdiv(seqlen, META["BLOCK_M"]), batch, nheads) # noqa
207
+ BLOCK_M = 4 if interleaved else (8 if rotary_dim <= 64 else 4)
208
+
209
+ # Need this, otherwise Triton tries to launch from cuda:0 and we get
210
+ # ValueError: Pointer argument (at 0) cannot be accessed from Triton (cpu tensor?)
211
+ with torch.cuda.device(x.device.index):
212
+ rotary_kernel[grid](
213
+ output, # data ptrs
214
+ x,
215
+ cos,
216
+ sin,
217
+ cu_seqlens,
218
+ seqlen_offsets,
219
+ seqlen, # shapes
220
+ nheads,
221
+ rotary_dim,
222
+ seqlen_ro,
223
+ seqlen // 128, # key for triton cache (limit number of compilations)
224
+ output.stride(0), # batch_strides
225
+ output.stride(-3), # nheads_stride
226
+ output.stride(-2), # seqlen_stride
227
+ output.stride(-1), # headdim_stride
228
+ x.stride(0), # batch_strides
229
+ x.stride(-3), # nheads stride
230
+ x.stride(-2), # seqlen stride
231
+ x.stride(-1), # headdim stride
232
+ BLOCK_K,
233
+ isinstance(seqlen_offsets, torch.Tensor),
234
+ False,
235
+ interleaved,
236
+ conjugate,
237
+ BLOCK_M,
238
+ )
239
+ return output
240
+
241
+
242
+ class ApplyRotaryEmb(torch.autograd.Function):
243
+ @staticmethod
244
+ def forward(
245
+ ctx,
246
+ x,
247
+ cos,
248
+ sin,
249
+ interleaved=False,
250
+ inplace=False,
251
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
252
+ cu_seqlens: Optional[torch.Tensor] = None,
253
+ max_seqlen: Optional[int] = None,
254
+ ):
255
+ out = apply_rotary(
256
+ x,
257
+ cos,
258
+ sin,
259
+ seqlen_offsets=seqlen_offsets,
260
+ cu_seqlens=cu_seqlens,
261
+ max_seqlen=max_seqlen,
262
+ interleaved=interleaved,
263
+ inplace=inplace,
264
+ )
265
+ if isinstance(seqlen_offsets, int):
266
+ ctx.save_for_backward(cos, sin, cu_seqlens) # Can't save int with save_for_backward
267
+ ctx.seqlen_offsets = seqlen_offsets
268
+ else:
269
+ ctx.save_for_backward(cos, sin, cu_seqlens, seqlen_offsets)
270
+ ctx.seqlen_offsets = None
271
+ ctx.interleaved = interleaved
272
+ ctx.inplace = inplace
273
+ ctx.max_seqlen = max_seqlen
274
+ return out if not inplace else x
275
+
276
+ @staticmethod
277
+ def backward(ctx, do):
278
+ seqlen_offsets = ctx.seqlen_offsets
279
+ if seqlen_offsets is None:
280
+ cos, sin, cu_seqlens, seqlen_offsets = ctx.saved_tensors
281
+ else:
282
+ cos, sin, cu_seqlens = ctx.saved_tensors
283
+ # TD [2023-09-02]: For some reason Triton (2.0.0.post1) errors with
284
+ # "[CUDA]: invalid device context", and cloning makes it work. Idk why. Triton 2.1.0 works.
285
+ if not ctx.interleaved and not ctx.inplace:
286
+ do = do.clone()
287
+ dx = apply_rotary(
288
+ do,
289
+ cos,
290
+ sin,
291
+ seqlen_offsets=seqlen_offsets,
292
+ cu_seqlens=cu_seqlens,
293
+ max_seqlen=ctx.max_seqlen,
294
+ interleaved=ctx.interleaved,
295
+ inplace=ctx.inplace,
296
+ conjugate=True,
297
+ )
298
+ return dx, None, None, None, None, None, None, None
299
+
300
+
301
+ def apply_rotary_emb(
302
+ x,
303
+ cos,
304
+ sin,
305
+ interleaved=False,
306
+ inplace=False,
307
+ seqlen_offsets: Union[int, torch.Tensor] = 0,
308
+ cu_seqlens: Optional[torch.Tensor] = None,
309
+ max_seqlen: Optional[int] = None,
310
+ ):
311
+ """
312
+ Arguments:
313
+ x: (batch_size, seqlen, nheads, headdim) if cu_seqlens is None
314
+ else (total_seqlen, nheads, headdim)
315
+ cos, sin: (seqlen_rotary, rotary_dim / 2)
316
+ interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead
317
+ of 1st half and 2nd half (GPT-NeoX style).
318
+ inplace: if True, apply rotary embedding in-place.
319
+ seqlen_offsets: (batch_size,) or int. Each sequence in x is shifted by this amount.
320
+ Most commonly used in inference when we have KV cache.
321
+ cu_seqlens: (batch + 1,) or None
322
+ max_seqlen: int
323
+ Return:
324
+ out: (batch_size, seqlen, nheads, headdim) if cu_seqlens is None
325
+ else (total_seqlen, nheads, headdim)
326
+ rotary_dim must be <= headdim
327
+ Apply rotary embedding to the first rotary_dim of x.
328
+ """
329
+ return ApplyRotaryEmb.apply(
330
+ x, cos, sin, interleaved, inplace, seqlen_offsets, cu_seqlens, max_seqlen
331
+ )
332
+
333
+
334
+ # For backward compatibility
335
+ apply_rotary_emb_func = apply_rotary_emb
336
+
337
+
338
+ class FastRotaryEmbedding(torch.nn.Module):
339
+ """
340
+ The rotary position embeddings from RoFormer_ (Su et. al).
341
+ A crucial insight from the method is that the query and keys are
342
+ transformed by rotation matrices which depend on the relative positions.
343
+
344
+ Other implementations are available in the Rotary Transformer repo_ and in
345
+ GPT-NeoX_, GPT-NeoX was an inspiration
346
+
347
+ .. _RoFormer: https://arxiv.org/abs/2104.09864
348
+ .. _repo: https://github.com/ZhuiyiTechnology/roformer
349
+ .. _GPT-NeoX: https://github.com/EleutherAI/gpt-neox
350
+
351
+ If scale_base is not None, this implements XPos (Sun et al., https://arxiv.org/abs/2212.10554).
352
+ A recommended value for scale_base is 512: https://github.com/HazyResearch/flash-attention/issues/96
353
+ Reference: https://github.com/sunyt32/torchscale/blob/main/torchscale/component/xpos_relative_position.py
354
+ """
355
+
356
+ def __init__(
357
+ self,
358
+ dim: int,
359
+ base=10000,
360
+ interleaved=False,
361
+ scale_base=None,
362
+ pos_idx_in_fp32=True,
363
+ device=None,
364
+ ):
365
+ """
366
+ interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead
367
+ of 1st half and 2nd half (GPT-NeoX style).
368
+ pos_idx_in_fp32: if True, the position indices [0.0, ..., seqlen - 1] are in fp32,
369
+ otherwise they might be in lower precision.
370
+ This option was added because previously (before 2023-07-02), when we construct
371
+ the position indices, we use the dtype of self.inv_freq. In most cases this would
372
+ be fp32, but if the model is trained in pure bf16 (not mixed precision), then
373
+ self.inv_freq would be bf16, and the position indices are also in bf16.
374
+ Because of the limited precision of bf16 (e.g. 1995.0 is rounded to 2000.0), the
375
+ embeddings for some positions will coincide.
376
+ To maintain compatibility with models previously trained in pure bf16,
377
+ we add this option.
378
+ """
379
+ super().__init__()
380
+ self.dim = dim
381
+ self.base = base
382
+ self.pos_idx_in_fp32 = pos_idx_in_fp32
383
+ # Generate and save the inverse frequency buffer (non trainable)
384
+ inv_freq = self._compute_inv_freq(device)
385
+ self.register_buffer("inv_freq", inv_freq)
386
+ self.interleaved = interleaved
387
+ self.scale_base = scale_base
388
+ scale = (
389
+ (torch.arange(0, dim, 2, device=device, dtype=torch.float32) + 0.4 * dim) / (1.4 * dim)
390
+ if scale_base is not None
391
+ else None
392
+ )
393
+ self.register_buffer("scale", scale, persistent=False)
394
+
395
+ self._seq_len_cached = 0
396
+ self._cos_cached = None
397
+ self._sin_cached = None
398
+ self._cos_k_cached = None
399
+ self._sin_k_cached = None
400
+ self.cos = None
401
+ self.sin = None
402
+
403
+ def _compute_inv_freq(self, device=None):
404
+ return 1.0 / (
405
+ self.base
406
+ ** (torch.arange(0, self.dim, 2, device=device) / self.dim)
407
+ # ** (torch.arange(0, self.dim, 2, device=device).float() / self.dim)
408
+ )
409
+
410
+ def _update_cos_sin_cache(self, seqlen, position_id, device=None, dtype=None):
411
+
412
+ if (
413
+ seqlen > self._seq_len_cached
414
+ ):
415
+ self._seq_len_cached = seqlen
416
+ # We want fp32 here, not self.inv_freq.dtype, since the model could be loaded in bf16
417
+ # And the output of arange can be quite large, so bf16 would lose a lot of precision.
418
+ # However, for compatibility reason, we add an option to use the dtype of self.inv_freq.
419
+ if self.pos_idx_in_fp32:
420
+ t = torch.arange(seqlen, device=device, dtype=torch.float32)
421
+ # We want fp32 here as well since inv_freq will be multiplied with t, and the output
422
+ # will be large. Having it in bf16 will lose a lot of precision and cause the
423
+ # cos & sin output to change significantly.
424
+ # We want to recompute self.inv_freq if it was not loaded in fp32
425
+ if self.inv_freq.dtype != torch.float32:
426
+ inv_freq = self._compute_inv_freq(device=device)
427
+ else:
428
+ inv_freq = self.inv_freq
429
+ else:
430
+ t = torch.arange(seqlen, device=device, dtype=self.inv_freq.dtype)
431
+ inv_freq = self.inv_freq
432
+ freqs = torch.einsum("i,j->ij", t, inv_freq)
433
+ if self.scale is None:
434
+ self._cos_cached = torch.cos(freqs).to(dtype)
435
+ self._sin_cached = torch.sin(freqs).to(dtype)
436
+
437
+ else:
438
+ power = (
439
+ torch.arange(seqlen, dtype=self.scale.dtype, device=self.scale.device)
440
+ - seqlen // 2
441
+ ) / self.scale_base
442
+ scale = self.scale.to(device=power.device) ** rearrange(power, "s -> s 1")
443
+ # We want the multiplication by scale to happen in fp32
444
+ self._cos_cached = (torch.cos(freqs) * scale).to(dtype)
445
+ self._sin_cached = (torch.sin(freqs) * scale).to(dtype)
446
+ self._cos_k_cached = (torch.cos(freqs) / scale).to(dtype)
447
+ self._sin_k_cached = (torch.sin(freqs) / scale).to(dtype)
448
+
449
+ def forward(
450
+ self,
451
+ q: torch.Tensor,
452
+ k: torch.Tensor,
453
+ position_ids: torch.Tensor,
454
+ max_seqlen,
455
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
456
+ """
457
+ q: (batch, nheads, seqlen, headdim)
458
+ k: (batch, nheads, seqlen, headdim)
459
+ position_id: (batch, seqlen)
460
+ max_seqlen: int
461
+ layer_id: int
462
+ only if layer_id == 0, then update cons and sin
463
+ Apply rotary embedding *inplace* to q k.
464
+ """
465
+
466
+ self._update_cos_sin_cache(max_seqlen, position_ids, device=q.device, dtype=q.dtype)
467
+ cos, sin = F.embedding(position_ids, self._cos_cached), F.embedding(position_ids, self._sin_cached)
468
+
469
+ q = apply_rotary_emb_func(
470
+ q,
471
+ cos,
472
+ sin,
473
+ interleaved=self.interleaved,
474
+ inplace=True
475
+ )
476
+ k = apply_rotary_emb_func(
477
+ k,
478
+ cos,
479
+ sin,
480
+ interleaved=self.interleaved,
481
+ inplace=True
482
+ )
483
+ return q, k
visual.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ from argparse import Namespace
4
+ import xformers.ops as xops
5
+ from transformers.activations import ACT2FN
6
+
7
+
8
+ class PatchEmbedding(nn.Module):
9
+ def __init__(self, config):
10
+ super().__init__()
11
+ self.proj = nn.Conv2d(config.in_channels, config.hidden_size, kernel_size=config.patch_size, stride=config.patch_size)
12
+ self.cls_embedding = nn.Parameter(torch.zeros(1, config.hidden_size))
13
+ self.position_embedding = nn.Embedding(config.num_positions, config.hidden_size)
14
+
15
+ def forward(self, images: "tensor(B, C, H, W)") -> "tensor(B, L, D)":
16
+ x = self.proj(images)
17
+ x = x.flatten(2).transpose(1, 2)
18
+ cls_token = self.cls_embedding.expand(x.shape[0], -1, -1)
19
+ x = torch.cat((cls_token, x), dim=1)
20
+ x += self.position_embedding.weight.unsqueeze(0)
21
+ return x
22
+
23
+
24
+ class Attention(nn.Module):
25
+ def __init__(self, config):
26
+ super().__init__()
27
+ self.num_heads = config.num_heads
28
+ head_dim = config.hidden_size // config.num_heads
29
+ self.scale = head_dim ** -0.5
30
+ self.query_key_value = nn.Linear(config.hidden_size, config.hidden_size * 3)
31
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
32
+ self.output_dropout = torch.nn.Dropout(config.dropout_prob)
33
+
34
+ def forward(self, x: "tensor(B, L, D)") -> "tensor(B, L, D)":
35
+ B, L, _ = x.shape
36
+ qkv = self.query_key_value(x)
37
+ qkv = qkv.reshape(B, L, 3, self.num_heads, -1).permute(2, 0, 1, 3, 4) # 3, B, L, H, D
38
+ q, k, v = qkv[0], qkv[1], qkv[2]
39
+
40
+ out = xops.memory_efficient_attention(
41
+ q, k, v, scale=self.scale,
42
+ )
43
+ output = self.dense(out.view(B, L, -1))
44
+ output = self.output_dropout(output)
45
+ return output
46
+
47
+ def attention(self, q, k, v):
48
+ attn_weights = torch.matmul(q * self.scale, k.transpose(-2, -1))
49
+ attn_weights = attn_weights.softmax(dim=-1)
50
+ output = torch.matmul(attn_weights, v)
51
+ return output
52
+
53
+
54
+ class MLP(nn.Module):
55
+ def __init__(self, config):
56
+ super().__init__()
57
+ self.config = config
58
+ self.activation_fn = ACT2FN[config.hidden_act]
59
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
60
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
61
+
62
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
63
+ x = self.fc1(x)
64
+ x = self.activation_fn(x)
65
+ x = self.fc2(x)
66
+ return x
67
+
68
+
69
+ class TransformerLayer(nn.Module):
70
+ def __init__(self, config):
71
+ super().__init__()
72
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
73
+ self.attention = Attention(config)
74
+ self.mlp = MLP(config)
75
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
76
+
77
+ def forward(self, hidden_states):
78
+ attention_input = hidden_states
79
+ attention_output = self.input_layernorm(self.attention(attention_input))
80
+ hidden_states = attention_input + attention_output
81
+ mlp_input = hidden_states
82
+ mlp_output = self.post_attention_layernorm(self.mlp(mlp_input))
83
+ output = mlp_input + mlp_output
84
+ return output
85
+
86
+
87
+ class Transformer(nn.Module):
88
+ def __init__(self, config):
89
+ super().__init__()
90
+ self.layers = nn.ModuleList([TransformerLayer(config) for _ in range(config.num_hidden_layers)])
91
+
92
+ def forward(self, hidden_states):
93
+ for layer_module in self.layers:
94
+ hidden_states = layer_module(hidden_states)
95
+ return hidden_states
96
+
97
+
98
+ class GLU(nn.Module):
99
+ def __init__(self, config, in_features):
100
+ super().__init__()
101
+ self.linear_proj = nn.Linear(in_features, config.hidden_size, bias=False)
102
+ self.norm1 = nn.LayerNorm(config.hidden_size)
103
+ self.act1 = nn.GELU()
104
+ self.act2 = nn.functional.silu
105
+ self.dense_h_to_4h = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
106
+ self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
107
+ self.dense_4h_to_h = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
108
+
109
+ def forward(self, x):
110
+ x = self.linear_proj(x)
111
+ x = self.act1(self.norm1(x))
112
+ x = self.act2(self.gate_proj(x)) * self.dense_h_to_4h(x)
113
+ x = self.dense_4h_to_h(x)
114
+ return x
115
+
116
+
117
+ class EVA2CLIPModel(nn.Module):
118
+ def __init__(self, config):
119
+ super().__init__()
120
+ vision_config = Namespace(**config.vision_config)
121
+ self.patch_embedding = PatchEmbedding(vision_config)
122
+ self.transformer = Transformer(vision_config)
123
+ self.linear_proj = GLU(config, in_features=vision_config.hidden_size)
124
+ self.conv = nn.Conv2d(in_channels=vision_config.hidden_size, out_channels=vision_config.hidden_size, kernel_size=2, stride=2)
125
+ self.boi = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
126
+ self.eoi = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
127
+
128
+ def forward(self, images: "tensor(B, C, H, W)") -> "tensor(B, L, D)":
129
+ x = self.patch_embedding(images)
130
+ x = self.transformer(x)
131
+ x = x[:, 1:]
132
+
133
+ b, s, h = x.shape
134
+ grid_size = int(s**0.5)
135
+ x = x.view(b, grid_size, grid_size, h).permute(0, 3, 1, 2)
136
+ x = self.conv(x)
137
+
138
+ x = x.flatten(2).transpose(1, 2)
139
+ x = self.linear_proj(x)
140
+ boi = self.boi.expand(x.shape[0], -1, -1)
141
+ eoi = self.eoi.expand(x.shape[0], -1, -1)
142
+ x = torch.cat((boi, x, eoi), dim=1)
143
+ return x