OPEA
/

Safetensors
weiweiz1 commited on
Commit
7ddd721
1 Parent(s): 9457c34

auto_round format

Browse files

Signed-off-by: Zhang, Weiwei1 <weiwei1.zhang@intel.com>

.gitattributes CHANGED
@@ -33,3 +33,10 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ config.json filter=lfs diff=lfs merge=lfs -text
37
+ generation_config.json filter=lfs diff=lfs merge=lfs -text
38
+ model.safetensors.index.json filter=lfs diff=lfs merge=lfs -text
39
+ quantization_config.json filter=lfs diff=lfs merge=lfs -text
40
+ special_tokens_map.json filter=lfs diff=lfs merge=lfs -text
41
+ tokenizer_config.json filter=lfs diff=lfs merge=lfs -text
42
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cac7e657c2146e027607ecbef6dc3f473c4822edc5d9a7eb24dd61b0d079e5b6
3
+ size 5512
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,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1b4bc735ef5fc9e69a29fd564b31db24af170752f1a0f885ccdeb97d878587d2
3
+ size 250
model-00001-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9189c7b9c858c8bcef8a885b70e741e0fa8980651772915b9d24be6b0a5c5d7f
3
+ size 4982219848
model-00002-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6ba190aa703fe95382aa123911636071bf180a6ef4869094e8158df4bda82026
3
+ size 4999021392
model-00003-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ae0211653778f23f445b8b5944c249fb85722784524fd92d2af97a51441482ca
3
+ size 2040541744
model.safetensors.index.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34d15988fe0e544225c3d86884bf620ff9a897dd9c14826121a407de77e5ff87
3
+ size 285978
modeling_cogvlm.py ADDED
@@ -0,0 +1,818 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """largely copy from llama and adapt for cogvlm"""
2
+ import warnings
3
+ from typing import TYPE_CHECKING, Optional, Tuple, List, Union, Literal, Dict, Any
4
+
5
+ import math
6
+ import torch
7
+ from torch import nn
8
+ from torch.nn import CrossEntropyLoss
9
+ from torchvision import transforms
10
+ from einops import rearrange
11
+
12
+ from transformers import PreTrainedModel, PreTrainedTokenizer
13
+ from transformers.utils.logging import get_logger
14
+ from transformers.activations import ACT2FN
15
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
16
+
17
+ from .configuration_cogvlm import CogVLMConfig
18
+ from .util import FastRotaryEmbedding
19
+ from .visual import EVA2CLIPModel
20
+
21
+ if TYPE_CHECKING:
22
+ from transformers.utils import ModelOutput
23
+
24
+ logger = get_logger(__name__)
25
+
26
+ LANGUAGE_TOKEN_TYPE = 0
27
+ VISION_TOKEN_TYPE = 1
28
+
29
+
30
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
31
+ def _make_causal_mask(
32
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
33
+ ):
34
+ """
35
+ Make causal mask used for bi-directional self-attention.
36
+ """
37
+ bsz, tgt_len = input_ids_shape
38
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
39
+ mask_cond = torch.arange(mask.size(-1), device=device)
40
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
41
+ mask = mask.to(dtype)
42
+
43
+ if past_key_values_length > 0:
44
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
45
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
46
+
47
+
48
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
49
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
50
+ """
51
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
52
+ """
53
+ bsz, src_len = mask.size()
54
+ tgt_len = tgt_len if tgt_len is not None else src_len
55
+
56
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
57
+
58
+ inverted_mask = 1.0 - expanded_mask
59
+
60
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
61
+
62
+
63
+ class RMSNorm(nn.Module):
64
+ def __init__(self, hidden_size, eps=1e-5):
65
+ super().__init__()
66
+ self.weight = nn.Parameter(torch.ones(hidden_size))
67
+ self.variance_epsilon = eps
68
+
69
+ def forward(self, hidden_states):
70
+ input_dtype = hidden_states.dtype
71
+ hidden_states = hidden_states.to(torch.float32)
72
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
73
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
74
+ return (self.weight * hidden_states).to(input_dtype)
75
+
76
+
77
+ class MLP(nn.Module):
78
+ def __init__(self, config):
79
+ super().__init__()
80
+ self.hidden_size = config.hidden_size
81
+ self.intermediate_size = config.intermediate_size
82
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
83
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
84
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
85
+ self.act_fn = ACT2FN[config.hidden_act]
86
+
87
+ def forward(self, x):
88
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
89
+ return down_proj
90
+
91
+
92
+ def get_expert_mask(token_type_ids: "torch.LongTensor(B, L)") -> "[torch.BoolTensor(B, L), torch.BoolTensor(B, L)]":
93
+ vision_token_mask = torch.zeros_like(token_type_ids, dtype=torch.bool)
94
+ vision_token_mask[:, :-1] = (token_type_ids[:, :-1] == VISION_TOKEN_TYPE) & (token_type_ids[:, 1:] == VISION_TOKEN_TYPE)
95
+ language_token_mask = ~vision_token_mask
96
+ return vision_token_mask, language_token_mask
97
+
98
+
99
+ class VisionExpertMLP(nn.Module):
100
+ def __init__(self, config):
101
+ super().__init__()
102
+ self.language_mlp = MLP(config)
103
+ self.vision_mlp = MLP(config)
104
+
105
+ def forward(self, hidden_states: "torch.Tensor(B, L, D)", token_type_ids: "torch.LongTensor(B, L)"):
106
+ output = torch.empty(hidden_states.shape, dtype=hidden_states.dtype, device=hidden_states.device)
107
+ vision_token_mask, language_token_mask = get_expert_mask(token_type_ids)
108
+ output[vision_token_mask] = self.vision_mlp(hidden_states[vision_token_mask])
109
+ output[language_token_mask] = self.language_mlp(hidden_states[language_token_mask])
110
+ return output
111
+
112
+
113
+ def attention_fn(
114
+ query_layer: "torch.tensor(B, H, L, HD)",
115
+ key_layer: "torch.tensor(B, H, L, HD)",
116
+ value_layer: "torch.tensor(B, H, L, HD)",
117
+ attention_mask: "torch.tensor(B, H, L, HD)",
118
+ *,
119
+ scaling_attention_score: bool = True,
120
+ attention_dropout: nn.Module = None
121
+ ):
122
+ attention_mask_bool = (attention_mask == 0)
123
+ is_low_triangle = (attention_mask_bool == torch.ones_like(attention_mask_bool, dtype=torch.float).tril()).all()
124
+ is_full = (attention_mask_bool > 0).all()
125
+ if not (int(torch.__version__.split('.')[0]) >= 2):
126
+ warnings.warn("It's recommended to use torch2.0 or higher.")
127
+ if int(torch.__version__.split('.')[0]) >= 2 and scaling_attention_score and (is_full or is_low_triangle):
128
+ dropout_p = 0. if attention_dropout is None or not attention_dropout.training else attention_dropout.p
129
+ return torch.nn.functional.scaled_dot_product_attention(
130
+ query_layer, key_layer, value_layer,
131
+ attn_mask=None,
132
+ dropout_p=dropout_p,
133
+ is_causal=not is_full
134
+ )
135
+ else:
136
+ if scaling_attention_score:
137
+ query_layer = query_layer / math.sqrt(query_layer.shape[-1])
138
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
139
+ attention_scores = attention_scores + attention_mask
140
+ attention_scores = nn.functional.softmax(attention_scores, dim=-1, dtype=torch.float32).to(query_layer.dtype)
141
+ if attention_dropout is not None:
142
+ attention_scores = attention_dropout(attention_scores)
143
+ context_layer = torch.matmul(attention_scores, value_layer)
144
+ return context_layer
145
+
146
+
147
+ class VisionExpertAttention(nn.Module):
148
+ def __init__(self, config):
149
+ super().__init__()
150
+ self.config = config
151
+ self.hidden_size = config.hidden_size
152
+ self.num_attention_heads = config.num_attention_heads
153
+ self.num_multi_query_heads = config.num_multi_query_heads
154
+ self.hidden_size_per_attention_head = self.hidden_size // self.num_attention_heads
155
+ self.stride = [self.num_attention_heads, self.num_multi_query_heads, self.num_multi_query_heads]
156
+ self.qkv_size = self.hidden_size + self.hidden_size_per_attention_head * self.num_multi_query_heads * 2
157
+ self.head_dim = self.hidden_size // self.num_attention_heads
158
+ self.max_position_embeddings = config.max_position_embeddings
159
+ self.rotary_emb = FastRotaryEmbedding(dim=self.head_dim, pos_idx_in_fp32=False, base=500000)
160
+ self.vision_expert_query_key_value = nn.Linear(self.hidden_size, self.qkv_size, bias=True)
161
+ self.vision_expert_dense = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
162
+ self.language_expert_query_key_value = nn.Linear(self.hidden_size, self.qkv_size, bias=False)
163
+ self.language_expert_dense = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
164
+
165
+ def _transpose_for_scores(self, tensor):
166
+ """Transpose a 3D tensor [B, L, H*HD] into a 4D tensor with size [B H L HD]."""
167
+ new_tensor_shape = tensor.size()[:-1] + \
168
+ (-1, # flexible for multi-query
169
+ self.hidden_size_per_attention_head)
170
+ tensor = tensor.view(*new_tensor_shape)
171
+ return tensor.permute(0, 2, 1, 3)
172
+
173
+ def forward(
174
+ self,
175
+ hidden_states: torch.Tensor,
176
+ token_type_ids: torch.LongTensor,
177
+ position_ids: torch.LongTensor,
178
+ attention_mask: Optional[torch.Tensor] = None,
179
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
180
+ output_attentions: bool = False,
181
+ use_cache: bool = False,
182
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
183
+ bsz, q_len, _ = hidden_states.size()
184
+ vision_token_mask, language_token_mask = get_expert_mask(token_type_ids)
185
+
186
+ shape = list(hidden_states.shape)
187
+ shape[-1] = self.qkv_size
188
+ mixed_raw_layer = torch.empty(shape, dtype=hidden_states.dtype, device=hidden_states.device)
189
+ mixed_raw_layer[vision_token_mask] = self.vision_expert_query_key_value(hidden_states[vision_token_mask])
190
+ mixed_raw_layer[language_token_mask] = self.language_expert_query_key_value(hidden_states[language_token_mask])
191
+
192
+ # query_states, key_states, value_states = torch.split(mixed_raw_layer, self.hidden_size, dim=-1)
193
+ factor = mixed_raw_layer.size()[-1] // sum(self.stride)
194
+ query_states, key_states, value_states = torch.split(mixed_raw_layer, [factor * x for x in self.stride], dim=-1)
195
+
196
+ query_states = self._transpose_for_scores(query_states) # B, H, L, HD
197
+ key_states = self._transpose_for_scores(key_states) # B, H, L, HD
198
+ value_states = self._transpose_for_scores(value_states) # B, H, L, HD
199
+
200
+ kv_seq_len = key_states.shape[-2]
201
+ if past_key_value is not None:
202
+ kv_seq_len += past_key_value[0].shape[-2]
203
+
204
+
205
+ query_states, key_states = self.rotary_emb(query_states, key_states, position_ids=position_ids, max_seqlen=position_ids.max() + 1)
206
+
207
+ if past_key_value is not None:
208
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
209
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
210
+
211
+ past_key_value = (key_states, value_states) if use_cache else None
212
+
213
+ key_states = key_states.unsqueeze(2).expand(-1, -1, self.num_attention_heads // self.num_multi_query_heads, -1, -1).contiguous().view(
214
+ bsz, self.num_attention_heads, *key_states.shape[2:])
215
+ value_states = value_states.unsqueeze(2).expand(-1, -1, self.num_attention_heads // self.num_multi_query_heads, -1,
216
+ -1).contiguous().view(bsz, self.num_attention_heads, *value_states.shape[2:])
217
+
218
+ context_layer = attention_fn(
219
+ query_layer=query_states, key_layer=key_states, value_layer=value_states, attention_mask=attention_mask,
220
+ scaling_attention_score=True, attention_dropout=None)
221
+ if context_layer.size() != (bsz, self.num_attention_heads, q_len, self.head_dim):
222
+ raise ValueError(
223
+ f"`attn_output` should be of size {(bsz, self.num_attention_heads, q_len, self.head_dim)}, but is"
224
+ f" {context_layer.size()}"
225
+ )
226
+ context_layer = context_layer.transpose(1, 2).contiguous().reshape(bsz, q_len, self.hidden_size)
227
+
228
+ attn_output = torch.empty(context_layer.shape, dtype=hidden_states.dtype, device=hidden_states.device)
229
+ attn_output[vision_token_mask] = self.vision_expert_dense(context_layer[vision_token_mask])
230
+ attn_output[language_token_mask] = self.language_expert_dense(context_layer[language_token_mask])
231
+
232
+ if output_attentions:
233
+ warnings.warn("output_attentions is not implemented.")
234
+
235
+ return attn_output, None, past_key_value
236
+
237
+
238
+ class CogVLMDecoderLayer(nn.Module):
239
+ def __init__(self, config):
240
+ super().__init__()
241
+ self.hidden_size = config.hidden_size
242
+ self.self_attn = VisionExpertAttention(config=config)
243
+ self.mlp = VisionExpertMLP(config)
244
+ self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
245
+ self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
246
+
247
+ def forward(
248
+ self,
249
+ hidden_states: torch.Tensor,
250
+ token_type_ids: torch.LongTensor,
251
+ position_ids: torch.LongTensor,
252
+ attention_mask: Optional[torch.Tensor] = None,
253
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
254
+ output_attentions: Optional[bool] = False,
255
+ use_cache: Optional[bool] = False,
256
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
257
+ residual = hidden_states
258
+
259
+ hidden_states = self.input_layernorm(hidden_states)
260
+
261
+ # Self Attention
262
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
263
+ hidden_states=hidden_states,
264
+ token_type_ids=token_type_ids,
265
+ position_ids=position_ids,
266
+ attention_mask=attention_mask,
267
+ past_key_value=past_key_value,
268
+ output_attentions=output_attentions,
269
+ use_cache=use_cache,
270
+ )
271
+ hidden_states = residual + hidden_states
272
+
273
+ # Fully Connected
274
+ residual = hidden_states
275
+ hidden_states = self.post_attention_layernorm(hidden_states)
276
+ hidden_states = self.mlp(hidden_states, token_type_ids=token_type_ids)
277
+ hidden_states = residual + hidden_states
278
+
279
+ outputs = (hidden_states,)
280
+
281
+ if output_attentions:
282
+ outputs += (self_attn_weights,)
283
+
284
+ if use_cache:
285
+ outputs += (present_key_value,)
286
+
287
+ return outputs # type: ignore
288
+
289
+
290
+ class CogVLMPreTrainedModel(PreTrainedModel):
291
+ config_class = CogVLMConfig
292
+ base_model_prefix = "model"
293
+ supports_gradient_checkpointing = False
294
+ _no_split_modules = ["CogVLMDecoderLayer"]
295
+ _skip_keys_device_placement = "past_key_values"
296
+
297
+ def _init_weights(self, module):
298
+ std = self.config.initializer_range
299
+ if isinstance(module, nn.Linear):
300
+ module.weight.data.normal_(mean=0.0, std=std)
301
+ if module.bias is not None:
302
+ module.bias.data.zero_()
303
+ elif isinstance(module, nn.Embedding):
304
+ module.weight.data.normal_(mean=0.0, std=std)
305
+ if module.padding_idx is not None:
306
+ module.weight.data[module.padding_idx].zero_()
307
+
308
+
309
+ def is_empty(images_list: Optional[List[List[torch.Tensor]]]):
310
+ if images_list is None or len(images_list) == 0:
311
+ return True
312
+ for image_list in images_list:
313
+ if len(image_list):
314
+ return False
315
+ return True
316
+
317
+
318
+ def build_position_ids(x: "torch.BoolTensor(B, L)", attention_mask: Optional["torch.BoolTensor(B, L)"] = None) -> "torch.LongTensor(B, L)":
319
+ if attention_mask is not None:
320
+ tmp = x.clone()
321
+ tmp[~(attention_mask.bool())] = -1
322
+ else:
323
+ tmp = x.clone()
324
+ # image boi eoi token as LANGUAGE_TOKEN_TYPE
325
+ is_boi_eoi = torch.zeros_like(x, dtype=torch.bool)
326
+ is_boi_eoi[:, 1:] |= (tmp[:, 1:] == VISION_TOKEN_TYPE) & (tmp[:, :-1] == LANGUAGE_TOKEN_TYPE)
327
+ is_boi_eoi[:, 0] |= (tmp[:, 0] == VISION_TOKEN_TYPE)
328
+ is_boi_eoi[:, :-1] |= (tmp[:, :-1] == VISION_TOKEN_TYPE) & (tmp[:, 1:] == LANGUAGE_TOKEN_TYPE)
329
+ is_boi_eoi[:, -1] |= (tmp[:, -1] == VISION_TOKEN_TYPE)
330
+ tmp[is_boi_eoi] = LANGUAGE_TOKEN_TYPE
331
+ # final position ids
332
+ y = torch.zeros_like(x, dtype=torch.long)
333
+ y[:, 1:] = (tmp[:, 1:] == LANGUAGE_TOKEN_TYPE) | ((tmp[:, 1:] == VISION_TOKEN_TYPE) & (tmp[:, :-1] == LANGUAGE_TOKEN_TYPE))
334
+ y = y.cumsum(dim=-1)
335
+ return y
336
+
337
+
338
+ class CogVLMModel(CogVLMPreTrainedModel):
339
+ def __init__(self, config):
340
+ super().__init__(config)
341
+ self.padding_idx = 128002
342
+ self.vocab_size = config.vocab_size
343
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
344
+ self.layers = nn.ModuleList([CogVLMDecoderLayer(config) for _ in range(config.num_hidden_layers)])
345
+ self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
346
+
347
+ self.vision = EVA2CLIPModel(config)
348
+
349
+ self.gradient_checkpointing = False
350
+ # Initialize weights and apply final processing
351
+ self.post_init()
352
+
353
+ def encode_images(self, images: List[List[torch.Tensor]]) -> torch.Tensor:
354
+ images_list, images = images, []
355
+
356
+ images = []
357
+ for image_list in images_list:
358
+ for image in image_list:
359
+ images.append(image)
360
+
361
+ images = torch.stack(images)
362
+ images_features = self.vision(images)
363
+ return images_features
364
+
365
+ def forward(
366
+ self,
367
+ input_ids: torch.LongTensor = None,
368
+ images: List[List[torch.Tensor]] = None,
369
+ token_type_ids: Optional[torch.LongTensor] = None,
370
+ attention_mask: Optional[torch.Tensor] = None,
371
+ position_ids: Optional[torch.LongTensor] = None,
372
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
373
+ inputs_embeds: Optional[torch.FloatTensor] = None,
374
+ use_cache: Optional[bool] = None,
375
+ output_attentions: Optional[bool] = None,
376
+ output_hidden_states: Optional[bool] = None,
377
+ return_dict: Optional[bool] = None,
378
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
379
+ """take care of image_encode, token_type_ids, position_ids and (attention_mask = None is fine)"""
380
+
381
+ if past_key_values is not None:
382
+ pass # generate mode with past_key_values. the image features are already mapped
383
+ else:
384
+ # not allow for inputs_embeds, because we want to process image feature
385
+ assert input_ids is not None and inputs_embeds is None, f"{input_ids} {inputs_embeds}"
386
+ if not is_empty(images): # multi-modality
387
+ assert token_type_ids is not None, f"multi-modality requires `token_type_ids`!"
388
+ assert len(input_ids) == len(images), f"{len(input_ids)} {len(images)}"
389
+ inputs_embeds = self.embed_tokens(input_ids)
390
+ images_features = self.encode_images(images)
391
+ images_features = rearrange(images_features, 'b n d -> (b n) d')
392
+ images_features = images_features.to(dtype=inputs_embeds.dtype, device=inputs_embeds.device)
393
+ inputs_embeds = inputs_embeds.index_put([token_type_ids == VISION_TOKEN_TYPE], images_features)
394
+ else: # single-modality
395
+ if token_type_ids is None:
396
+ token_type_ids = torch.ones_like(input_ids, dtype=torch.long, device=input_ids.device) * LANGUAGE_TOKEN_TYPE
397
+ assert not (token_type_ids == VISION_TOKEN_TYPE).any(), f"{(token_type_ids == VISION_TOKEN_TYPE).sum()}"
398
+ inputs_embeds = self.embed_tokens(input_ids)
399
+
400
+ if position_ids is None:
401
+ position_ids = build_position_ids(token_type_ids, attention_mask)
402
+ input_ids = None
403
+ return self.llm_forward(
404
+ input_ids=input_ids,
405
+ token_type_ids=token_type_ids,
406
+ attention_mask=attention_mask,
407
+ position_ids=position_ids,
408
+ past_key_values=past_key_values,
409
+ inputs_embeds=inputs_embeds,
410
+ use_cache=use_cache,
411
+ output_attentions=output_attentions,
412
+ output_hidden_states=output_hidden_states,
413
+ return_dict=return_dict,
414
+ )
415
+
416
+ def llm_forward(
417
+ self,
418
+ input_ids: torch.LongTensor = None,
419
+ token_type_ids: torch.LongTensor = None,
420
+ attention_mask: Optional[torch.Tensor] = None,
421
+ position_ids: Optional[torch.LongTensor] = None,
422
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
423
+ inputs_embeds: Optional[torch.FloatTensor] = None,
424
+ use_cache: Optional[bool] = None,
425
+ output_attentions: Optional[bool] = None,
426
+ output_hidden_states: Optional[bool] = None,
427
+ return_dict: Optional[bool] = None,
428
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
429
+ """largely copy from llama forward and adapt for cogvlm with `token_type_ids`"""
430
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
431
+ output_hidden_states = (
432
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
433
+ )
434
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
435
+
436
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
437
+
438
+ # retrieve input_ids and inputs_embeds
439
+ if input_ids is not None and inputs_embeds is not None:
440
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
441
+ elif input_ids is not None:
442
+ batch_size, seq_length = input_ids.shape
443
+ elif inputs_embeds is not None:
444
+ batch_size, seq_length, _ = inputs_embeds.shape
445
+ else:
446
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
447
+
448
+ seq_length_with_past = seq_length
449
+ past_key_values_length = 0
450
+
451
+ if past_key_values is not None:
452
+ if isinstance(past_key_values, tuple):
453
+ past_key_values_length = past_key_values[1][0][0].shape[2]
454
+ else:
455
+ past_key_values_length = past_key_values[0][0].shape[2]
456
+ seq_length_with_past = seq_length_with_past + past_key_values_length
457
+
458
+ if position_ids is None:
459
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
460
+ position_ids = torch.arange(
461
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
462
+ )
463
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
464
+ else:
465
+ position_ids = position_ids.view(-1, seq_length).long()
466
+
467
+ if inputs_embeds is None:
468
+ inputs_embeds = self.embed_tokens(input_ids)
469
+ # embed positions
470
+ if attention_mask is None:
471
+ attention_mask = torch.ones(
472
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
473
+ )
474
+ attention_mask = self._prepare_decoder_attention_mask(
475
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
476
+ )
477
+
478
+ hidden_states = inputs_embeds
479
+
480
+ # decoder layers
481
+ all_hidden_states = () if output_hidden_states else None
482
+ all_self_attns = () if output_attentions else None
483
+ next_decoder_cache = () if use_cache else None
484
+
485
+ for idx, decoder_layer in enumerate(self.layers):
486
+ if output_hidden_states:
487
+ all_hidden_states += (hidden_states,)
488
+
489
+ if isinstance(past_key_values,tuple):
490
+ past_key_value = past_key_values[1][idx] if past_key_values is not None else None
491
+ else:
492
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
493
+ layer_outputs = decoder_layer(
494
+ hidden_states,
495
+ token_type_ids=token_type_ids,
496
+ attention_mask=attention_mask,
497
+ position_ids=position_ids,
498
+ past_key_value=past_key_value,
499
+ output_attentions=output_attentions,
500
+ use_cache=use_cache,
501
+ )
502
+ hidden_states = layer_outputs[0]
503
+
504
+ if use_cache:
505
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
506
+
507
+ if output_attentions:
508
+ all_self_attns += (layer_outputs[1],)
509
+
510
+ hidden_states = self.norm(hidden_states)
511
+
512
+ # add hidden states from the last decoder layer
513
+ if output_hidden_states:
514
+ all_hidden_states += (hidden_states,)
515
+
516
+ next_cache = next_decoder_cache if use_cache else None
517
+ if not return_dict:
518
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
519
+ return BaseModelOutputWithPast(
520
+ last_hidden_state=hidden_states,
521
+ past_key_values=next_cache,
522
+ hidden_states=all_hidden_states,
523
+ attentions=all_self_attns,
524
+ )
525
+
526
+ def get_input_embeddings(self):
527
+ return self.embed_tokens
528
+
529
+ def set_input_embeddings(self, value):
530
+ self.embed_tokens = value
531
+
532
+ # noinspection PyMethodMayBeStatic
533
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
534
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
535
+ # create causal mask
536
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
537
+ combined_attention_mask = None
538
+ if input_shape[-1] > 1:
539
+ combined_attention_mask = _make_causal_mask(
540
+ input_shape,
541
+ inputs_embeds.dtype,
542
+ device=inputs_embeds.device,
543
+ past_key_values_length=past_key_values_length,
544
+ )
545
+
546
+ if attention_mask is not None:
547
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
548
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
549
+ inputs_embeds.device
550
+ )
551
+ combined_attention_mask = (
552
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
553
+ )
554
+
555
+ return combined_attention_mask
556
+
557
+
558
+ def _history_to_prompt(signal_type, history, query):
559
+ if signal_type == 'base':
560
+ return query
561
+ elif signal_type == 'vqa':
562
+ answer_format = 'Short answer:'
563
+ elif signal_type == 'chat':
564
+ answer_format = 'Answer:'
565
+ else:
566
+ assert False, f"Unknown signal type {signal_type}"
567
+
568
+ prompt = ''
569
+ for i, (old_query, response) in enumerate(history):
570
+ prompt += 'Question: ' + old_query + " {} ".format(answer_format) + response + "\n"
571
+ prompt += 'Question: {} {}'.format(query, answer_format)
572
+ return prompt
573
+
574
+
575
+ class CogVLMForCausalLM(CogVLMPreTrainedModel):
576
+ _auto_class = "AutoModelForCausalLM"
577
+
578
+ def __init__(self, config):
579
+ super().__init__(config)
580
+ self.model = CogVLMModel(config)
581
+ self.vocab_size = config.vocab_size
582
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
583
+
584
+ # Initialize weights and apply final processing
585
+ self.post_init()
586
+
587
+ def get_input_embeddings(self):
588
+ return self.model.embed_tokens
589
+
590
+ def set_input_embeddings(self, value):
591
+ self.model.embed_tokens = value
592
+
593
+ def get_output_embeddings(self):
594
+ return self.lm_head
595
+
596
+ def set_output_embeddings(self, new_embeddings):
597
+ self.lm_head = new_embeddings
598
+
599
+ def set_decoder(self, decoder):
600
+ self.model = decoder
601
+
602
+ def get_decoder(self):
603
+ return self.model
604
+
605
+ def forward(
606
+ self,
607
+ input_ids: torch.LongTensor = None,
608
+ images: List[List[torch.Tensor]] = None,
609
+ token_type_ids: Optional[torch.LongTensor] = None,
610
+ attention_mask: Optional[torch.Tensor] = None,
611
+ position_ids: Optional[torch.LongTensor] = None,
612
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
613
+ inputs_embeds: Optional[torch.FloatTensor] = None,
614
+ use_cache: Optional[bool] = None,
615
+ output_attentions: Optional[bool] = None,
616
+ output_hidden_states: Optional[bool] = None,
617
+ return_dict: Optional[bool] = None,
618
+ labels: Optional[torch.LongTensor] = None,
619
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
620
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
621
+ output_hidden_states = (
622
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
623
+ )
624
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
625
+
626
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
627
+ outputs = self.model(
628
+ input_ids=input_ids,
629
+ images=images,
630
+ token_type_ids=token_type_ids,
631
+ attention_mask=attention_mask,
632
+ position_ids=position_ids,
633
+ past_key_values=past_key_values,
634
+ inputs_embeds=inputs_embeds,
635
+ use_cache=use_cache,
636
+ output_attentions=output_attentions,
637
+ output_hidden_states=output_hidden_states,
638
+ return_dict=return_dict,
639
+ )
640
+
641
+ hidden_states = outputs[0]
642
+ logits = self.lm_head(hidden_states)
643
+ logits = logits.float()
644
+
645
+ loss = None
646
+ if labels is not None:
647
+ # Shift so that tokens < n predict n
648
+ shift_logits = logits[..., :-1, :].contiguous()
649
+ shift_labels = labels[..., 1:].contiguous()
650
+ # Flatten the tokens
651
+ loss_fct = CrossEntropyLoss()
652
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
653
+ shift_labels = shift_labels.view(-1)
654
+ # Enable model parallelism
655
+ shift_labels = shift_labels.to(shift_logits.device)
656
+ loss = loss_fct(shift_logits, shift_labels)
657
+
658
+ if not return_dict:
659
+ output = (logits,) + outputs[1:]
660
+ return (loss,) + output if loss is not None else output
661
+
662
+ return CausalLMOutputWithPast(
663
+ loss=loss,
664
+ logits=logits,
665
+ past_key_values=outputs.past_key_values,
666
+ hidden_states=outputs.hidden_states,
667
+ attentions=outputs.attentions,
668
+ )
669
+
670
+ def _prepare_attention_mask_for_generation(
671
+ self,
672
+ inputs: torch.Tensor,
673
+ pad_token_id: Optional[int],
674
+ eos_token_id: Optional[Union[int, List[int]]],
675
+ ) -> torch.LongTensor:
676
+ return torch.ones(inputs.shape[:2], dtype=torch.long, device=inputs.device) # type: ignore
677
+
678
+ def prepare_inputs_for_generation(
679
+ self, input_ids, token_type_ids, images=None, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
680
+ ):
681
+ # build position_ids if needed
682
+ position_ids = kwargs.get("position_ids", None)
683
+ if position_ids is None:
684
+ position_ids = build_position_ids(token_type_ids, attention_mask)
685
+
686
+ if past_key_values:
687
+ input_ids = input_ids[:, -1:]
688
+ token_type_ids = token_type_ids[:, -1:]
689
+ position_ids = position_ids[:, -1:]
690
+
691
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
692
+ if inputs_embeds is not None and past_key_values is None:
693
+ model_inputs = {"inputs_embeds": inputs_embeds}
694
+ else:
695
+ model_inputs = {"input_ids": input_ids}
696
+
697
+ model_inputs.update(
698
+ {
699
+ "token_type_ids": token_type_ids,
700
+ "images": images,
701
+ "position_ids": position_ids,
702
+ "past_key_values": past_key_values,
703
+ "use_cache": kwargs.get("use_cache"),
704
+ "attention_mask": attention_mask,
705
+ }
706
+ )
707
+ return model_inputs
708
+
709
+ def _update_model_kwargs_for_generation(
710
+ self,
711
+ outputs: "ModelOutput",
712
+ model_kwargs: Dict[str, Any],
713
+ is_encoder_decoder: bool = False,
714
+ standardize_cache_format: bool = False,
715
+ ) -> Dict[str, Any]:
716
+ # update past_key_values
717
+ model_kwargs["past_key_values"] = self._extract_past_from_model_output(
718
+ outputs, #standardize_cache_format=standardize_cache_format
719
+ )
720
+ if getattr(outputs, "state", None) is not None:
721
+ model_kwargs["state"] = outputs.state
722
+
723
+ # update token_type_ids with last value
724
+ if "token_type_ids" in model_kwargs:
725
+ token_type_ids = model_kwargs["token_type_ids"]
726
+ 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
727
+ model_kwargs["token_type_ids"] = torch.cat([token_type_ids, new_token_type_ids], dim=-1)
728
+
729
+ if not is_encoder_decoder:
730
+ # update attention mask
731
+ if "attention_mask" in model_kwargs:
732
+ attention_mask = model_kwargs["attention_mask"]
733
+ model_kwargs["attention_mask"] = torch.cat(
734
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
735
+ )
736
+ else:
737
+ # update decoder attention mask
738
+ if "decoder_attention_mask" in model_kwargs:
739
+ decoder_attention_mask = model_kwargs["decoder_attention_mask"]
740
+ model_kwargs["decoder_attention_mask"] = torch.cat(
741
+ [decoder_attention_mask, decoder_attention_mask.new_ones((decoder_attention_mask.shape[0], 1))],
742
+ dim=-1,
743
+ )
744
+
745
+ return model_kwargs
746
+
747
+ def _reorder_cache(self, past_key_values, beam_idx):
748
+ reordered_past = ()
749
+ for layer_past in past_key_values:
750
+ reordered_past += (
751
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
752
+ )
753
+ return reordered_past
754
+
755
+ def build_conversation_input_ids(
756
+ self,
757
+ tokenizer: "PreTrainedTokenizer",
758
+ *,
759
+ query: str,
760
+ history: Optional[List[Tuple[str, str]]] = None,
761
+ images: Optional[List["PIL.Image"]] = None,
762
+ template_version: Optional[Literal["base", "chat", "vqa"]] = None,
763
+ answer: str = None,
764
+ ):
765
+ image_size: int = self.config.vision_config['image_size']
766
+ patch_size: int = self.config.vision_config['patch_size']
767
+ template_version = template_version or self.config.template_version
768
+ assert images is None or len(images) <= 1, f"not support multi images by now."
769
+ history = history or []
770
+ text = _history_to_prompt(template_version, history, query)
771
+ input_ids = [tokenizer.bos_token_id]
772
+ token_type_ids = [LANGUAGE_TOKEN_TYPE]
773
+ if images is not None and len(images) == 1:
774
+ # vision
775
+ transform = transforms.Compose(
776
+ [
777
+ transforms.Resize(
778
+ (image_size, image_size), interpolation=transforms.InterpolationMode.BICUBIC
779
+ ),
780
+ transforms.ToTensor(),
781
+ transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
782
+ ]
783
+ )
784
+ if images[0] is None:
785
+ images = None
786
+ else:
787
+ images = [transform(images[0])]
788
+ # language
789
+ vision_token_num = (image_size // patch_size // 2) * (image_size // patch_size // 2) + 2
790
+
791
+ tokenizer.pad_token_id = 128002 # llama3 adapt for cogvlm
792
+
793
+ input_ids += [tokenizer.pad_token_id] * vision_token_num
794
+ token_type_ids += [VISION_TOKEN_TYPE] * vision_token_num
795
+ text_ids = tokenizer.encode(text, add_special_tokens=False)
796
+
797
+ if answer is not None:
798
+ answer_ids = tokenizer.encode(answer, add_special_tokens=False)
799
+ answer_ids += [tokenizer.eos_token_id]
800
+ text_ids += answer_ids
801
+
802
+
803
+ input_ids += text_ids
804
+ token_type_ids += [LANGUAGE_TOKEN_TYPE] * len(text_ids)
805
+ attention_mask = [1] * len(input_ids)
806
+ if answer is not None:
807
+ labels = [-100 for _ in range(len(input_ids) - len(answer_ids))] + answer_ids
808
+ labels = torch.tensor(labels, dtype=torch.long)
809
+ else:
810
+ labels = None
811
+
812
+ return {
813
+ 'input_ids': torch.tensor(input_ids, dtype=torch.long),
814
+ 'token_type_ids': torch.tensor(token_type_ids, dtype=torch.long),
815
+ 'attention_mask': torch.tensor(attention_mask, dtype=torch.long),
816
+ 'images': images,
817
+ 'labels': labels,
818
+ }
quantization_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c73dc0e84d0e079d49e6101a82e78817d7b7ea8827cab7940ce2632f54541dcb
3
+ size 4160
special_tokens_map.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cc2e013b7545f183ef03e079a3c91c6f364fa37e4068c512d7dd843e59024535
3
+ size 301
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3c5cf44023714fb39b05e71e425f8d7b92805ff73f7988b083b8c87f0bf87393
3
+ size 17209961
tokenizer_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f05beada81734485478a52246564e0748b5934d7c0f252ab88ee6324074b90a
3
+ size 51102
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