zhengwenzhen commited on
Commit
4de4402
·
verified ·
1 Parent(s): ee9cc9c

Upload modeling_step1.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_step1.py +414 -0
modeling_step1.py ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Optional, Tuple, Union, List
3
+
4
+ import torch
5
+ import torch.utils.checkpoint
6
+ from torch import nn
7
+ from transformers.generation import GenerationMixin
8
+
9
+ from transformers.modeling_utils import PreTrainedModel
10
+ from transformers.utils import logging
11
+ from .configuration_step1 import Step1Config
12
+ from transformers.cache_utils import Cache, DynamicCache
13
+ from einops import rearrange
14
+ from transformers.modeling_outputs import (
15
+ BaseModelOutputWithPast,
16
+ CausalLMOutputWithPast,
17
+ )
18
+
19
+ logger = logging.get_logger(__name__)
20
+
21
+
22
+ def build_alibi_cache(block_size, n_heads, dtype, device):
23
+ # get slopes
24
+ n = 2 ** math.floor(math.log2(n_heads)) # nearest 2**n to n_heads
25
+ m0 = 2.0 ** (-8.0 / n)
26
+ # 2^(-8/n), 2^(-8*2/n), 2^(-8*3/n), ...
27
+ slopes = torch.pow(m0, torch.arange(1, n + 1))
28
+ if n < n_heads:
29
+ m1 = 2.0 ** (-4.0 / n)
30
+ # 2^(-8/(2n)), 2^(-8*3/(2n)), 2^(-8*5/(2n)), ...
31
+ mm = torch.pow(m1, torch.arange(1, 1 + 2 * (n_heads - n), 2))
32
+ slopes = torch.cat([slopes, mm])
33
+ slopes = slopes.to(device)
34
+
35
+ tril = torch.tril(torch.ones(1, 1, block_size, block_size, device=device))
36
+
37
+ bias_rows = torch.arange(block_size, device=device).view(1, -1)
38
+ bias_cols = torch.arange(block_size, device=device).view(-1, 1)
39
+ bias = -torch.sqrt(bias_cols - bias_rows)
40
+ bias = bias.view(1, block_size, block_size) * slopes.view(-1, 1, 1)
41
+ bias = bias.masked_fill(tril == 0, float("-inf"))
42
+
43
+ return bias.type(dtype)
44
+
45
+
46
+ class StepRMSNorm(torch.nn.Module):
47
+ def __init__(self, hidden_size, eps=1e-5):
48
+ super().__init__()
49
+ self.weight = torch.nn.Parameter(torch.ones(hidden_size))
50
+ self.eps = eps
51
+
52
+ def forward(self, x: torch.Tensor):
53
+ var = x.float().pow(2).mean(-1, keepdim=True)
54
+ x = x * torch.rsqrt(var + self.eps).to(x.dtype)
55
+ x = x * self.weight
56
+ return x
57
+
58
+
59
+ class StepAttention(torch.nn.Module):
60
+ def __init__(self, hidden_size, num_heads, num_groups, layer_idx: int):
61
+ super().__init__()
62
+
63
+ self.num_heads = num_heads
64
+ self.num_groups = num_groups
65
+ self.hidden_size = hidden_size
66
+ self.head_dim = hidden_size // num_heads
67
+
68
+ self.q_proj = torch.nn.Linear(hidden_size, hidden_size, bias=False)
69
+ self.k_proj = torch.nn.Linear(
70
+ hidden_size, num_groups * self.head_dim, bias=False
71
+ )
72
+ self.v_proj = torch.nn.Linear(
73
+ hidden_size, num_groups * self.head_dim, bias=False
74
+ )
75
+ self.o_proj = torch.nn.Linear(hidden_size, hidden_size, bias=False)
76
+
77
+ self.layer_idx = layer_idx
78
+
79
+ def flash_attn_func(self, q, k, v, dropout_p=0.0, softmax_scale=None, causal=True,
80
+ return_attn_probs=False, tp_group_rank=0, tp_group_size=1):
81
+ softmax_scale = q.size(-1) ** (-0.5) if softmax_scale is None else softmax_scale
82
+ return torch.ops.Optimus.fwd(q, k, v, None, dropout_p, softmax_scale, causal, return_attn_probs, None, tp_group_rank, tp_group_size)[0]
83
+
84
+ def forward(
85
+ self,
86
+ x: torch.Tensor,
87
+ past_key_value: Optional[Cache] = None,
88
+ attention_mask: Optional[torch.Tensor] = None,
89
+ cache_position: Optional[torch.LongTensor] = None,
90
+ ):
91
+
92
+ q: torch.Tensor = self.q_proj(x)
93
+ k: torch.Tensor = self.k_proj(x)
94
+ v: torch.Tensor = self.v_proj(x)
95
+ if past_key_value is not None:
96
+ cache_kwargs = {"cache_position": cache_position}
97
+ k, v = past_key_value.update(k, v, self.layer_idx, cache_kwargs)
98
+
99
+ q = rearrange(q, "b s (h d) -> b s h d", h=self.num_heads)
100
+ k = rearrange(k, "b s (g d) -> b s g d", g=self.num_groups)
101
+ v = rearrange(v, "b s (g d) -> b s g d", g=self.num_groups)
102
+
103
+ try:
104
+ if self.head_dim not in (64, 128):
105
+ raise ValueError("head_dim must be 64 or 128")
106
+ attn_output = self.flash_attn_func(q, k, v)
107
+ attn_output = attn_output.flatten(-2, -1)
108
+ except:
109
+ k = k.repeat_interleave(self.num_heads // self.num_groups, dim=-2)
110
+ v = v.repeat_interleave(self.num_heads // self.num_groups, dim=-2)
111
+
112
+ attention_mask = build_alibi_cache(
113
+ k.size(1), self.num_heads, dtype=q.dtype, device=q.device
114
+ )[:, :, -q.size(1) :, :].contiguous()
115
+
116
+ q = q.transpose(1, 2)
117
+ k = k.transpose(1, 2)
118
+ v = v.transpose(1, 2)
119
+
120
+ attn_output: torch.Tensor = torch.nn.functional.scaled_dot_product_attention(
121
+ q, k, v, attn_mask=attention_mask
122
+ )
123
+
124
+ attn_output = attn_output.transpose(1, 2).flatten(-2, -1)
125
+
126
+ out = self.o_proj(attn_output)
127
+ return out, None # attn weights are not returned
128
+
129
+
130
+ class StepMLP(torch.nn.Module):
131
+ def __init__(self, hidden_size, intermediate_size):
132
+ super().__init__()
133
+ self.gate_proj = torch.nn.Linear(hidden_size, intermediate_size, bias=False)
134
+ self.up_proj = torch.nn.Linear(hidden_size, intermediate_size, bias=False)
135
+ self.down_proj = torch.nn.Linear(intermediate_size, hidden_size, bias=False)
136
+
137
+ def forward(self, x):
138
+ gate = self.gate_proj(x)
139
+ up = self.up_proj(x)
140
+ x = torch.nn.functional.silu(gate) * up
141
+ x = self.down_proj(x)
142
+ return x
143
+
144
+
145
+ class StepLayer(torch.nn.Module):
146
+ def __init__(self, config: Step1Config, layer_idx: int):
147
+ super().__init__()
148
+ self.layer_idx = layer_idx
149
+ self.self_attn = StepAttention(
150
+ hidden_size=config.hidden_size,
151
+ num_heads=config.num_attention_heads,
152
+ num_groups=config.num_attention_groups,
153
+ layer_idx=layer_idx,
154
+ )
155
+ self.mlp = StepMLP(
156
+ hidden_size=config.hidden_size,
157
+ intermediate_size=config.intermediate_size,
158
+ )
159
+ self.input_layernorm = StepRMSNorm(
160
+ hidden_size=config.hidden_size, eps=config.rms_norm_eps
161
+ )
162
+ self.post_attention_layernorm = StepRMSNorm(
163
+ hidden_size=config.hidden_size, eps=config.rms_norm_eps
164
+ )
165
+
166
+ def forward(
167
+ self,
168
+ hidden_states: torch.Tensor,
169
+ attention_mask: Optional[torch.Tensor] = None,
170
+ past_key_value: Optional[Cache] = None,
171
+ output_attentions: Optional[bool] = False,
172
+ cache_position: Optional[torch.LongTensor] = None,
173
+ ):
174
+ residual = hidden_states
175
+ hidden_states = self.input_layernorm(hidden_states)
176
+ hidden_states, self_attn_weights = self.self_attn(hidden_states, past_key_value, attention_mask, cache_position)
177
+ hidden_states = residual + hidden_states
178
+
179
+ residual = hidden_states
180
+ hidden_states = self.post_attention_layernorm(hidden_states)
181
+ hidden_states = self.mlp(hidden_states)
182
+ hidden_states = residual + hidden_states
183
+
184
+ outputs = (hidden_states, )
185
+ if output_attentions:
186
+ outputs += (self_attn_weights,)
187
+ return outputs
188
+
189
+
190
+ class StepPreTrainedModel(PreTrainedModel):
191
+ config_class = Step1Config
192
+ base_model_prefix = "model"
193
+ supports_gradient_checkpointing = True
194
+ _no_split_modules = ["StepLayer"]
195
+ _skip_keys_device_placement = ["past_key_values"]
196
+ _supports_cache_class = True
197
+ _supports_static_cache = True
198
+
199
+ def _init_weights(self, module):
200
+ std = self.config.initializer_range
201
+ if isinstance(module, nn.Linear):
202
+ module.weight.data.normal_(mean=0.0, std=std)
203
+ if module.bias is not None:
204
+ module.bias.data.zero_()
205
+ elif isinstance(module, nn.Embedding):
206
+ module.weight.data.normal_(mean=0.0, std=std)
207
+ if module.padding_idx is not None:
208
+ module.weight.data[module.padding_idx].zero_()
209
+
210
+
211
+ class Step1Model(StepPreTrainedModel):
212
+ """
213
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
214
+
215
+ Args:
216
+ config: Step1Config
217
+ """
218
+
219
+ def __init__(self, config: Step1Config):
220
+ super().__init__(config)
221
+ self.config = config
222
+ self.embed_tokens = torch.nn.Embedding(config.vocab_size, config.hidden_size)
223
+
224
+ self.layers = torch.nn.Sequential(
225
+ *[
226
+ StepLayer(config, layer_idx)
227
+ for layer_idx in range(config.num_hidden_layers)
228
+ ]
229
+ )
230
+
231
+ self.norm = StepRMSNorm(
232
+ hidden_size=config.hidden_size, eps=config.rms_norm_eps
233
+ )
234
+
235
+ # Initialize weights and apply final processing
236
+ self.post_init()
237
+
238
+ def get_input_embeddings(self):
239
+ return self.embed_tokens
240
+
241
+ def set_input_embeddings(self, value):
242
+ self.embed_tokens = value
243
+
244
+ def forward(
245
+ self,
246
+ input_ids: torch.LongTensor = None,
247
+ attention_mask: Optional[torch.Tensor] = None,
248
+ past_key_values: Optional[Cache] = None,
249
+ inputs_embeds: Optional[torch.FloatTensor] = None,
250
+ use_cache: Optional[bool] = None,
251
+ output_attentions: Optional[bool] = None,
252
+ output_hidden_states: Optional[bool] = None,
253
+ return_dict: Optional[bool] = None,
254
+ cache_position: Optional[torch.LongTensor] = None,
255
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
256
+ output_attentions = (
257
+ output_attentions
258
+ if output_attentions is not None
259
+ else self.config.output_attentions
260
+ )
261
+ output_hidden_states = (
262
+ output_hidden_states
263
+ if output_hidden_states is not None
264
+ else self.config.output_hidden_states
265
+ )
266
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
267
+ return_dict = (
268
+ return_dict if return_dict is not None else self.config.use_return_dict
269
+ )
270
+
271
+ if (input_ids is None) ^ (inputs_embeds is not None):
272
+ raise ValueError(
273
+ "You must specify exactly one of input_ids or inputs_embeds"
274
+ )
275
+
276
+ if inputs_embeds is None:
277
+ inputs_embeds = self.embed_tokens(input_ids)
278
+
279
+ if use_cache and past_key_values is None:
280
+ past_key_values = DynamicCache()
281
+
282
+ if cache_position is None:
283
+ past_seen_tokens = (
284
+ past_key_values.get_seq_length() if past_key_values is not None else 0
285
+ )
286
+ cache_position = torch.arange(
287
+ past_seen_tokens,
288
+ past_seen_tokens + inputs_embeds.shape[1],
289
+ device=inputs_embeds.device,
290
+ )
291
+
292
+ causal_mask = attention_mask
293
+
294
+ hidden_states = inputs_embeds
295
+
296
+ # decoder layers
297
+ all_hidden_states = () if output_hidden_states else None
298
+ all_self_attns = () if output_attentions else None
299
+
300
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
301
+ if output_hidden_states:
302
+ all_hidden_states += (hidden_states,)
303
+
304
+ layer_outputs = decoder_layer(
305
+ hidden_states,
306
+ attention_mask=causal_mask,
307
+ past_key_value=past_key_values,
308
+ cache_position=cache_position,
309
+ output_attentions=output_attentions,
310
+ )
311
+
312
+ hidden_states = layer_outputs[0]
313
+
314
+ if output_attentions:
315
+ all_self_attns += (layer_outputs[1],)
316
+
317
+ hidden_states = self.norm(hidden_states)
318
+
319
+ # add hidden states from the last decoder layer
320
+ if output_hidden_states:
321
+ all_hidden_states += (hidden_states,)
322
+
323
+ output = BaseModelOutputWithPast(
324
+ last_hidden_state=hidden_states,
325
+ past_key_values=past_key_values if use_cache else None,
326
+ hidden_states=all_hidden_states,
327
+ attentions=None,
328
+ )
329
+ return output if return_dict else output.to_tuple()
330
+
331
+
332
+ class Step1ForCausalLM(StepPreTrainedModel, GenerationMixin):
333
+ _tied_weights_keys = ["lm_head.weight"]
334
+
335
+ def __init__(self, config):
336
+ super().__init__(config)
337
+ self.model = Step1Model(config)
338
+ self.vocab_size = config.vocab_size
339
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
340
+
341
+ # Initialize weights and apply final processing
342
+ self.post_init()
343
+
344
+ def get_input_embeddings(self):
345
+ return self.model.embed_tokens
346
+
347
+ def set_input_embeddings(self, value):
348
+ self.model.embed_tokens = value
349
+
350
+ def set_decoder(self, decoder):
351
+ self.model = decoder
352
+
353
+ def get_decoder(self):
354
+ return self.model
355
+
356
+ def forward(
357
+ self,
358
+ input_ids: torch.LongTensor = None,
359
+ attention_mask: Optional[torch.Tensor] = None,
360
+ position_ids: Optional[torch.LongTensor] = None,
361
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
362
+ inputs_embeds: Optional[torch.FloatTensor] = None,
363
+ labels: Optional[torch.LongTensor] = None,
364
+ use_cache: Optional[bool] = None,
365
+ output_attentions: Optional[bool] = None,
366
+ output_hidden_states: Optional[bool] = None,
367
+ return_dict: Optional[bool] = None,
368
+ cache_position: Optional[torch.LongTensor] = None,
369
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
370
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
371
+ output_hidden_states = (
372
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
373
+ )
374
+ return_dict = (
375
+ return_dict if return_dict is not None else self.config.use_return_dict
376
+ )
377
+
378
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
379
+ outputs = self.model(
380
+ input_ids=input_ids,
381
+ attention_mask=attention_mask,
382
+ past_key_values=past_key_values,
383
+ inputs_embeds=inputs_embeds,
384
+ use_cache=use_cache,
385
+ output_attentions=output_attentions,
386
+ output_hidden_states=output_hidden_states,
387
+ return_dict=return_dict,
388
+ cache_position=cache_position,
389
+ )
390
+
391
+ hidden_states = outputs[0]
392
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
393
+
394
+ logits = self.lm_head(hidden_states)
395
+
396
+ loss = None
397
+ if labels is not None:
398
+ loss = self.loss_function(
399
+ logits=logits,
400
+ labels=labels,
401
+ vocab_size=self.config.vocab_size,
402
+ )
403
+
404
+ if not return_dict:
405
+ output = (logits,) + outputs[1:]
406
+ return (loss,) + output if loss is not None else output
407
+
408
+ return CausalLMOutputWithPast(
409
+ loss=loss,
410
+ logits=logits,
411
+ past_key_values=outputs.past_key_values,
412
+ hidden_states=outputs.hidden_states,
413
+ attentions=outputs.attentions,
414
+ )