ruixie commited on
Commit
be141ff
1 Parent(s): a749dfd

Delete modeling_kclgpt.py

Browse files
Files changed (1) hide show
  1. modeling_kclgpt.py +0 -939
modeling_kclgpt.py DELETED
@@ -1,939 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2023 The Bigcode team and HuggingFace Inc. team.
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- """PyTorch KCLGPT model."""
15
- import math
16
- from typing import List, Optional, Tuple, Union
17
-
18
- import torch
19
- import torch.utils.checkpoint
20
- from torch import nn
21
- from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
22
-
23
- from transformers.activations import ACT2FN
24
- from transformers.modeling_outputs import (
25
- BaseModelOutputWithPastAndCrossAttentions,
26
- CausalLMOutputWithCrossAttentions,
27
- )
28
- from transformers.modeling_utils import PreTrainedModel
29
- from transformers.utils import (
30
- add_start_docstrings,
31
- add_start_docstrings_to_model_forward,
32
- logging,
33
- )
34
- from .configuration_kclgpt import KCLGPTConfig
35
-
36
-
37
- logger = logging.get_logger(__name__)
38
-
39
- # Fused kernels
40
- # Use separate functions for each case because conditionals prevent kernel fusion.
41
- # TODO: Could have better fused kernels depending on scaling, dropout and head mask.
42
- # Is it doable without writing 32 functions?
43
- @torch.jit.script
44
- def upcast_masked_softmax(
45
- x: torch.Tensor, mask: torch.Tensor, mask_value: torch.Tensor, scale: float, softmax_dtype: torch.dtype
46
- ):
47
- input_dtype = x.dtype
48
- x = x.to(softmax_dtype) * scale
49
- x = torch.where(mask, x, mask_value)
50
- x = torch.nn.functional.softmax(x, dim=-1).to(input_dtype)
51
- return x
52
-
53
-
54
- @torch.jit.script
55
- def upcast_softmax(x: torch.Tensor, scale: float, softmax_dtype: torch.dtype):
56
- input_dtype = x.dtype
57
- x = x.to(softmax_dtype) * scale
58
- x = torch.nn.functional.softmax(x, dim=-1).to(input_dtype)
59
- return x
60
-
61
-
62
- @torch.jit.script
63
- def masked_softmax(x: torch.Tensor, mask: torch.Tensor, mask_value: torch.Tensor):
64
- x = torch.where(mask, x, mask_value)
65
- x = torch.nn.functional.softmax(x, dim=-1)
66
- return x
67
-
68
-
69
- class LlamaRotaryEmbedding(torch.nn.Module):
70
- def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
71
- super().__init__()
72
-
73
- self.dim = dim
74
- self.max_position_embeddings = max_position_embeddings
75
- self.base = base
76
- inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
77
- self.register_buffer("inv_freq", inv_freq)
78
-
79
- # Build here to make `torch.jit.trace` work.
80
- self._set_cos_sin_cache(
81
- seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
82
- )
83
-
84
- def _set_cos_sin_cache(self, seq_len, device, dtype):
85
- self.max_seq_len_cached = seq_len
86
- t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
87
-
88
- freqs = torch.einsum("i,j->ij", t, self.inv_freq)
89
- # Different from paper, but it uses a different permutation in order to obtain the same calculation
90
- emb = torch.cat((freqs, freqs), dim=-1)
91
- self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
92
- self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
93
-
94
- def forward(self, x, seq_len=None):
95
- # x: [bs, num_attention_heads, seq_len, head_size]
96
- if seq_len > self.max_seq_len_cached:
97
- self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
98
-
99
- return (
100
- self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
101
- self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
102
- )
103
-
104
-
105
- class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
106
- """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
107
-
108
- def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
109
- self.scaling_factor = scaling_factor
110
- super().__init__(dim, max_position_embeddings, base, device)
111
-
112
- def _set_cos_sin_cache(self, seq_len, device, dtype):
113
- self.max_seq_len_cached = seq_len
114
- t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
115
- t = t / self.scaling_factor
116
-
117
- freqs = torch.einsum("i,j->ij", t, self.inv_freq)
118
- # Different from paper, but it uses a different permutation in order to obtain the same calculation
119
- emb = torch.cat((freqs, freqs), dim=-1)
120
- self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
121
- self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
122
-
123
-
124
- class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
125
- """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
126
-
127
- def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
128
- self.scaling_factor = scaling_factor
129
- super().__init__(dim, max_position_embeddings, base, device)
130
-
131
- def _set_cos_sin_cache(self, seq_len, device, dtype):
132
- self.max_seq_len_cached = seq_len
133
-
134
- if seq_len > self.max_position_embeddings:
135
- base = self.base * (
136
- (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
137
- ) ** (self.dim / (self.dim - 2))
138
- inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
139
- self.register_buffer("inv_freq", inv_freq)
140
-
141
- t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
142
-
143
- freqs = torch.einsum("i,j->ij", t, self.inv_freq)
144
- # Different from paper, but it uses a different permutation in order to obtain the same calculation
145
- emb = torch.cat((freqs, freqs), dim=-1)
146
- self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
147
- self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
148
-
149
- def rotate_half(x):
150
- """Rotates half the hidden dims of the input."""
151
- x1 = x[..., : x.shape[-1] // 2]
152
- x2 = x[..., x.shape[-1] // 2 :]
153
- return torch.cat((-x2, x1), dim=-1)
154
-
155
-
156
- def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
157
- # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
158
- cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
159
- sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
160
- cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
161
- sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
162
- q_embed = (q * cos) + (rotate_half(q) * sin)
163
- k_embed = (k * cos) + (rotate_half(k) * sin)
164
- return q_embed, k_embed
165
-
166
-
167
- class KCLGPTAttention(nn.Module):
168
- def __init__(self, config, layer_idx=None):
169
- super().__init__()
170
- self.mask_value = None
171
-
172
- self.position_embedding_type = config.position_embedding_type
173
- self.rope_scaling = config.rope_scaling
174
- self.max_position_embeddings = config.max_position_embeddings
175
-
176
- self.group_query_attention = config.group_query_attention
177
- self.num_query_groups = config.num_query_groups
178
-
179
- self.embed_dim = config.hidden_size
180
- self.num_heads = config.num_attention_heads
181
- self.head_dim = self.embed_dim // self.num_heads
182
- self.kv_heads = config.num_query_groups if self.group_query_attention else self.num_heads
183
- self.kv_dim = self.kv_heads * self.head_dim
184
- self.split_size = self.embed_dim
185
- if self.head_dim * self.num_heads != self.embed_dim:
186
- raise ValueError(
187
- f"`embed_dim` must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
188
- f" {self.num_heads})."
189
- )
190
-
191
- self.scale_attn_weights = config.scale_attn_weights
192
-
193
- self.layer_idx = layer_idx
194
- self.attention_softmax_in_fp32 = config.attention_softmax_in_fp32
195
- self.scale_attention_softmax_in_fp32 = (
196
- config.scale_attention_softmax_in_fp32 and config.attention_softmax_in_fp32
197
- )
198
-
199
- self.c_attn = nn.Linear(self.embed_dim, self.embed_dim + 2 * self.kv_dim)
200
-
201
- self.c_proj = nn.Linear(self.embed_dim, self.embed_dim)
202
-
203
- self.attn_dropout = nn.Dropout(config.attn_pdrop)
204
- self.resid_dropout = nn.Dropout(config.resid_pdrop)
205
-
206
- if self.position_embedding_type == "rope":
207
- self._init_rope()
208
-
209
- def _init_rope(self):
210
- if self.rope_scaling is None:
211
- self.rotary_emb = LlamaRotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
212
- else:
213
- scaling_type = self.rope_scaling["type"]
214
- scaling_factor = self.rope_scaling["factor"]
215
- if scaling_type == "linear":
216
- self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
217
- self.head_dim, max_position_embeddings=self.max_position_embeddings, scaling_factor=scaling_factor
218
- )
219
- elif scaling_type == "dynamic":
220
- self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
221
- self.head_dim, max_position_embeddings=self.max_position_embeddings, scaling_factor=scaling_factor
222
- )
223
- else:
224
- raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
225
-
226
-
227
- def _get_mask_value(self, device, dtype):
228
- # torch.where expects a tensor. We use a cache to avoid recreating it every time.
229
- if self.mask_value is None or self.mask_value.dtype != dtype or self.mask_value.device != device:
230
- self.mask_value = torch.full([], torch.finfo(dtype).min, dtype=dtype, device=device)
231
- return self.mask_value
232
-
233
- def _attn(self, query, key, value, attention_mask=None, head_mask=None):
234
- dtype = query.dtype
235
- softmax_dtype = torch.float32 if self.attention_softmax_in_fp32 else dtype
236
- upcast = dtype != softmax_dtype
237
-
238
- unscale = self.layer_idx + 1 if self.scale_attention_softmax_in_fp32 and upcast else 1
239
- scale_factor = unscale**-1
240
- if self.scale_attn_weights:
241
- scale_factor /= self.head_dim**0.5
242
-
243
- # [b, np, sq, sk]
244
- output_size = (query.size(1),
245
- query.size(2),
246
- query.size(0),
247
- key.size(0))
248
- attn_view = (output_size[0]*output_size[1], output_size[2], output_size[3])
249
-
250
- # [sq, b, np, hn] -> [sq, b * np, hn]
251
- query = query.reshape(output_size[2],
252
- output_size[0] * output_size[1], -1)
253
- # [sk, b, np, hn] -> [sk, b * np, hn]
254
- key = key.reshape(output_size[3],
255
- output_size[0] * output_size[1], -1)
256
- attn_weights = torch.empty(attn_view, device=query.device, dtype=query.dtype)
257
- if query.device.type == "cpu":
258
- # This is needed because of a bug in pytorch https://github.com/pytorch/pytorch/issues/80588.
259
- # The bug was fixed in https://github.com/pytorch/pytorch/pull/96086,
260
- # but the fix has not been released as of pytorch version 2.0.0.
261
- attn_weights = torch.zeros_like(attn_weights)
262
- beta = 1
263
- else:
264
- beta = 0
265
-
266
- attn_weights = torch.baddbmm(attn_weights,
267
- query.transpose(0, 1),
268
- key.transpose(0, 1).transpose(1, 2),
269
- beta=beta, alpha=scale_factor).reshape(output_size)
270
-
271
- if upcast:
272
- # Use a fused kernel to prevent a large overhead from casting and scaling.
273
- # Sub-optimal when the key length is not a multiple of 8.
274
- if attention_mask is None:
275
- attn_weights = upcast_softmax(attn_weights, unscale, softmax_dtype)
276
- else:
277
- mask_value = self._get_mask_value(attn_weights.device, softmax_dtype)
278
- attn_weights = upcast_masked_softmax(attn_weights, attention_mask, mask_value, unscale, softmax_dtype)
279
- else:
280
- if attention_mask is not None:
281
- mask_value = self._get_mask_value(attn_weights.device, softmax_dtype)
282
-
283
- # The fused kernel is very slow when the key length is not a multiple of 8, so we skip fusion.
284
- attn_weights = torch.where(attention_mask, attn_weights, mask_value)
285
-
286
- attn_weights = torch.nn.functional.softmax(attn_weights, dim=-1)
287
-
288
- attn_weights = self.attn_dropout(attn_weights)
289
-
290
- attn_weights = attn_weights.reshape(attn_view)
291
-
292
- # value_layer -> context layer.
293
- # [sk, b, np, hn] --> [b, np, sq, hn]
294
-
295
- # context layer shape: [b, np, sq, hn]
296
- output_size = (value.size(1),
297
- value.size(2),
298
- query.size(0),
299
- value.size(3))
300
-
301
- # change view [sk, b * np, hn]
302
- value = value.reshape(value.size(0),
303
- output_size[0] * output_size[1], -1)
304
- attn_output = torch.bmm(attn_weights, value.transpose(0, 1))
305
-
306
- # change view [b, np, sq, hn]
307
- attn_output = attn_output.reshape(*output_size)
308
- # [b, np, sq, hn] --> [sq, b, np, hn]
309
- attn_output = attn_output.permute(2, 0, 1, 3).contiguous()
310
-
311
- # [sq, b, np, hn] --> [sq, b, hp]
312
- attn_output = attn_output.reshape(attn_output.size(0), attn_output.size(1), -1)
313
-
314
- return attn_output, attn_weights
315
-
316
- def forward(
317
- self,
318
- hidden_states: torch.Tensor,
319
- layer_past: Optional[torch.Tensor] = None,
320
- attention_mask: Optional[torch.Tensor] = None,
321
- position_ids: Optional[torch.LongTensor] = None,
322
- head_mask: Optional[torch.Tensor] = None,
323
- encoder_hidden_states: Optional[torch.Tensor] = None,
324
- encoder_attention_mask: Optional[torch.Tensor] = None,
325
- use_cache: Optional[bool] = False,
326
- output_attentions: Optional[bool] = False,
327
- ) -> Union[
328
- Tuple[torch.Tensor, Optional[torch.Tensor]],
329
- Tuple[torch.Tensor, Optional[torch.Tensor], Tuple[torch.Tensor, ...]],
330
- ]:
331
- if self.group_query_attention:
332
- query, key_value = self.c_attn(hidden_states).split((self.embed_dim, 2 * self.kv_dim), dim=2)
333
- else:
334
- # Note: We split as (self.num_heads, 3, self.head_dim) instead of (3, self.num_heads, self.head_dim),
335
- # i.e., the memory layout is not the same as GPT2.
336
- # This makes the concatenation with past_key_value more efficient.
337
- query, key_value = (
338
- self.c_attn(hidden_states)
339
- .reshape(*hidden_states.shape[:2], self.num_heads, 3 * self.head_dim)
340
- .transpose(1, 2)
341
- .split((self.head_dim, 2 * self.head_dim), dim=3)
342
- )
343
-
344
- query = query.reshape(query.size(0), query.size(1), -1, self.head_dim)
345
-
346
- key, value = key_value.split((self.head_dim*self.num_query_groups, self.head_dim*self.num_query_groups), dim=-1)
347
- # expand the key_layer and value_layer [sk, b, ng, hn] -> [sk, b, np, hn]
348
- key = key.reshape(key.size(0), key.size(1), -1, self.head_dim)
349
- value = value.reshape(value.size(0), value.size(1), -1, self.head_dim)
350
-
351
- key = key.repeat_interleave(
352
- self.num_heads // self.num_query_groups,
353
- dim = 2
354
- )
355
- value = value.repeat_interleave(
356
- self.num_heads // self.num_query_groups,
357
- dim = 2
358
- )
359
-
360
- if self.position_embedding_type == "rope":
361
- kv_seq_len = key.shape[-3]
362
- if layer_past is not None:
363
- kv_seq_len += layer_past[0].shape[-3]
364
-
365
- cos, sin = self.rotary_emb(value, seq_len=kv_seq_len)
366
- query = query.transpose(1, 2).contiguous()
367
- key = key.transpose(1, 2).contiguous()
368
- query, key = apply_rotary_pos_emb(query, key, cos, sin, position_ids)
369
- query = query.transpose(1, 2).contiguous()
370
- key = key.transpose(1, 2).contiguous()
371
-
372
- if layer_past is not None:
373
- key = torch.cat((layer_past[0], key), dim=-3)
374
- value = torch.cat((layer_past[1], value), dim=-3)
375
- present = (key, value) if use_cache else None
376
-
377
- attn_output, attn_weights = self._attn(query.transpose(0, 1), key.transpose(0, 1), value.transpose(0, 1), attention_mask, head_mask)
378
-
379
- attn_output = attn_output.transpose(0, 1).reshape(hidden_states.shape)
380
- attn_output = self.c_proj(attn_output)
381
- attn_output = self.resid_dropout(attn_output)
382
-
383
- outputs = (attn_output, present)
384
- if output_attentions:
385
- if self.group_query_attention:
386
- # Transpose to return weights in the usual format (batch_size, num_heads, query_length, key_length)
387
- attn_weights = attn_weights.transpose(1, 2)
388
- outputs += (attn_weights,)
389
-
390
- return outputs # a, present, (attentions)
391
-
392
-
393
- class KCLGPTMLP(nn.Module):
394
- def __init__(self, intermediate_size, config):
395
- super().__init__()
396
- embed_dim = config.hidden_size
397
- self.c_fc = nn.Linear(embed_dim, intermediate_size)
398
- self.c_proj = nn.Linear(intermediate_size, embed_dim)
399
- self.act = ACT2FN[config.activation_function]
400
- self.dropout = nn.Dropout(config.resid_pdrop)
401
-
402
- # Copied from transformers.models.gpt2.modeling_gpt2.GPT2MLP.forward
403
- def forward(self, hidden_states: Optional[Tuple[torch.Tensor]]) -> torch.Tensor:
404
- hidden_states = self.c_fc(hidden_states)
405
- hidden_states = self.act(hidden_states)
406
- hidden_states = self.c_proj(hidden_states)
407
- hidden_states = self.dropout(hidden_states)
408
- return hidden_states
409
-
410
-
411
- class KCLGPTBlock(nn.Module):
412
- def __init__(self, config, layer_idx=None):
413
- super().__init__()
414
- hidden_size = config.hidden_size
415
- self.inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
416
-
417
- self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
418
- self.attn = KCLGPTAttention(config, layer_idx=layer_idx)
419
- self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
420
-
421
- self.mlp = KCLGPTMLP(self.inner_dim, config)
422
-
423
- def forward(
424
- self,
425
- hidden_states: Optional[Tuple[torch.Tensor]],
426
- layer_past: Optional[torch.Tensor] = None,
427
- attention_mask: Optional[torch.Tensor] = None,
428
- position_ids: Optional[torch.LongTensor] = None,
429
- head_mask: Optional[torch.Tensor] = None,
430
- encoder_hidden_states: Optional[torch.Tensor] = None,
431
- encoder_attention_mask: Optional[torch.Tensor] = None,
432
- use_cache: Optional[bool] = False,
433
- output_attentions: Optional[bool] = False,
434
- ) -> Union[
435
- Tuple[torch.Tensor], Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor, torch.Tensor, torch.Tensor]
436
- ]:
437
- residual = hidden_states
438
- hidden_states = self.ln_1(hidden_states)
439
- attn_outputs = self.attn(
440
- hidden_states,
441
- layer_past=layer_past,
442
- attention_mask=attention_mask,
443
- position_ids=position_ids,
444
- head_mask=head_mask,
445
- use_cache=use_cache,
446
- output_attentions=output_attentions,
447
- )
448
- attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
449
-
450
- outputs = attn_outputs[1:]
451
- # residual connection
452
- hidden_states = attn_output + residual
453
-
454
- residual = hidden_states
455
- hidden_states = self.ln_2(hidden_states)
456
- feed_forward_hidden_states = self.mlp(hidden_states)
457
- # residual connection
458
- hidden_states = residual + feed_forward_hidden_states
459
-
460
- if use_cache:
461
- outputs = (hidden_states,) + outputs
462
- else:
463
- outputs = (hidden_states,) + outputs[1:]
464
-
465
- return outputs # hidden_states, present, (attentions, cross_attentions)
466
-
467
-
468
- class KCLGPTPreTrainedModel(PreTrainedModel):
469
- """
470
- An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
471
- models.
472
- """
473
-
474
- config_class = KCLGPTConfig
475
- base_model_prefix = "transformer"
476
- supports_gradient_checkpointing = True
477
- _no_split_modules = ["KCLGPTBlock"]
478
- _skip_keys_device_placement = "past_key_values"
479
-
480
- def __init__(self, *inputs, **kwargs):
481
- super().__init__(*inputs, **kwargs)
482
-
483
- def _init_weights(self, module):
484
- """Initialize the weights."""
485
- if isinstance(module, (KCLGPTMLP, KCLGPTAttention)):
486
- # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
487
- # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
488
- # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
489
- # > -- GPT-2 :: https://openai.com/blog/better-language-models/
490
- #
491
- # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
492
- module.c_proj.weight.data.normal_(
493
- mean=0.0, std=(self.config.initializer_range / math.sqrt(2 * self.config.n_layer))
494
- )
495
- module.c_proj._is_hf_initialized = True
496
- elif isinstance(module, nn.Linear):
497
- # Slightly different from the TF version which uses truncated_normal for initialization
498
- # cf https://github.com/pytorch/pytorch/pull/5617
499
- module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
500
- if module.bias is not None:
501
- module.bias.data.zero_()
502
- elif isinstance(module, nn.Embedding):
503
- module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
504
- if module.padding_idx is not None:
505
- module.weight.data[module.padding_idx].zero_()
506
- elif isinstance(module, nn.LayerNorm):
507
- module.bias.data.zero_()
508
- module.weight.data.fill_(1.0)
509
-
510
- # Copied from transformers.models.gpt2.modeling_gpt2.GPT2PreTrainedModel._set_gradient_checkpointing with GPT2->KCLGPT
511
- def _set_gradient_checkpointing(self, module, value=False):
512
- if isinstance(module, KCLGPTModel):
513
- module.gradient_checkpointing = value
514
-
515
-
516
- GPT_BIGCODE_START_DOCSTRING = r"""
517
-
518
- This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
519
- library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
520
- etc.)
521
-
522
- This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
523
- Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
524
- and behavior.
525
-
526
- Parameters:
527
- config ([`KCLGPTConfig`]): Model configuration class with all the parameters of the model.
528
- Initializing with a config file does not load the weights associated with the model, only the
529
- configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
530
- """
531
-
532
- GPT_BIGCODE_INPUTS_DOCSTRING = r"""
533
- Args:
534
- input_ids (`torch.Tensor` of shape `(batch_size, input_ids_length)`):
535
- `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
536
- `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
537
- sequence tokens in the vocabulary.
538
-
539
- If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
540
- `input_ids`.
541
-
542
- Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
543
- [`PreTrainedTokenizer.__call__`] for details.
544
-
545
- [What are input IDs?](../glossary#input-ids)
546
- past_key_values (`Tuple[torch.Tensor]` of length `config.n_layers`):
547
- Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
548
- `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
549
- their past given to this model should not be passed as `input_ids` as they have already been computed.
550
- attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
551
- Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
552
-
553
- - 1 for tokens that are **not masked**,
554
- - 0 for tokens that are **masked**.
555
-
556
- If `past_key_values` is used, `attention_mask` needs to contain the masking strategy that was used for
557
- `past_key_values`. In other words, the `attention_mask` always has to have the length:
558
- `len(past_key_values) + len(input_ids)`
559
-
560
- [What are attention masks?](../glossary#attention-mask)
561
- token_type_ids (`torch.Tensor` of shape `(batch_size, input_ids_length)`, *optional*):
562
- Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
563
- 1]`:
564
-
565
- - 0 corresponds to a *sentence A* token,
566
- - 1 corresponds to a *sentence B* token.
567
-
568
- [What are token type IDs?](../glossary#token-type-ids)
569
- position_ids (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
570
- Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
571
- config.max_position_embeddings - 1]`.
572
-
573
- [What are position IDs?](../glossary#position-ids)
574
- head_mask (`torch.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
575
- Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
576
-
577
- - 1 indicates the head is **not masked**,
578
- - 0 indicates the head is **masked**.
579
-
580
- inputs_embeds (`torch.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
581
- Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
582
- is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
583
- model's internal embedding lookup matrix.
584
-
585
- If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
586
- `past_key_values`).
587
- use_cache (`bool`, *optional*):
588
- If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
589
- `past_key_values`).
590
- output_attentions (`bool`, *optional*):
591
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
592
- tensors for more detail.
593
- output_hidden_states (`bool`, *optional*):
594
- Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
595
- more detail.
596
- return_dict (`bool`, *optional*):
597
- Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
598
- """
599
-
600
-
601
- @add_start_docstrings(
602
- "The bare GPT_BIGCODE Model transformer outputting raw hidden-states without any specific head on top.",
603
- GPT_BIGCODE_START_DOCSTRING,
604
- )
605
- class KCLGPTModel(KCLGPTPreTrainedModel):
606
- def __init__(self, config):
607
- super().__init__(config)
608
- self.group_query_attention = config.group_query_attention
609
- self.num_query_groups = config.num_query_groups
610
- self.position_embedding_type = config.position_embedding_type
611
- self.embed_dim = config.hidden_size
612
-
613
- self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
614
- if self.position_embedding_type == "learned_absolute":
615
- self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim)
616
- else:
617
- pass
618
-
619
- self.drop = nn.Dropout(config.embd_pdrop)
620
- self.h = nn.ModuleList([KCLGPTBlock(config, layer_idx=i) for i in range(config.num_hidden_layers)])
621
- self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
622
-
623
- max_positions = config.max_position_embeddings
624
- self.register_buffer(
625
- "bias", torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)), persistent=False
626
- )
627
-
628
- self.gradient_checkpointing = False
629
-
630
- # Initialize weights and apply final processing
631
- self.post_init()
632
-
633
- def get_input_embeddings(self):
634
- return self.wte
635
-
636
- def set_input_embeddings(self, new_embeddings):
637
- self.wte = new_embeddings
638
-
639
- @add_start_docstrings_to_model_forward(GPT_BIGCODE_INPUTS_DOCSTRING)
640
- def forward(
641
- self,
642
- input_ids: Optional[torch.Tensor] = None,
643
- past_key_values: Optional[List[torch.Tensor]] = None,
644
- attention_mask: Optional[torch.Tensor] = None,
645
- token_type_ids: Optional[torch.Tensor] = None,
646
- position_ids: Optional[torch.Tensor] = None,
647
- head_mask: Optional[torch.Tensor] = None,
648
- inputs_embeds: Optional[torch.Tensor] = None,
649
- encoder_hidden_states: Optional[torch.Tensor] = None,
650
- encoder_attention_mask: Optional[torch.Tensor] = None,
651
- use_cache: Optional[bool] = None,
652
- output_attentions: Optional[bool] = None,
653
- output_hidden_states: Optional[bool] = None,
654
- return_dict: Optional[bool] = None,
655
- ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
656
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
657
- output_hidden_states = (
658
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
659
- )
660
- use_cache = use_cache if use_cache is not None else self.config.use_cache
661
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
662
-
663
- if input_ids is not None and inputs_embeds is not None:
664
- raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
665
- elif input_ids is not None:
666
- input_shape = input_ids.size()
667
- input_ids = input_ids.reshape(-1, input_shape[-1])
668
- batch_size = input_ids.shape[0]
669
- elif inputs_embeds is not None:
670
- input_shape = inputs_embeds.size()[:-1]
671
- batch_size = inputs_embeds.shape[0]
672
- else:
673
- raise ValueError("You have to specify either input_ids or inputs_embeds")
674
-
675
- if batch_size <= 0:
676
- raise ValueError("batch_size has to be defined and > 0")
677
-
678
- device = input_ids.device if input_ids is not None else inputs_embeds.device
679
-
680
- if token_type_ids is not None:
681
- token_type_ids = token_type_ids.reshape(-1, input_shape[-1])
682
- if position_ids is not None:
683
- position_ids = position_ids.reshape(-1, input_shape[-1])
684
-
685
- if past_key_values is None:
686
- past_length = 0
687
- past_key_values = tuple([None] * len(self.h))
688
- else:
689
- past_length = past_key_values[0][0].size(-3)
690
-
691
- if attention_mask is not None and len(attention_mask.shape) == 2 and position_ids is None:
692
- # create position_ids on the fly for batch generation
693
- position_ids = attention_mask.long().cumsum(-1) - 1
694
- position_ids.masked_fill_(attention_mask == 0, 1)
695
- if past_length > 0:
696
- position_ids = position_ids[:, past_length : input_shape[-1] + past_length :]
697
- elif position_ids is None:
698
- position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
699
- position_ids = position_ids.unsqueeze(0).reshape(-1, input_shape[-1])
700
-
701
- # Self-attention mask.
702
- query_length = input_shape[-1]
703
- key_length = past_length + query_length
704
- self_attention_mask = self.bias[None, key_length - query_length : key_length, :key_length]
705
-
706
- if attention_mask is not None:
707
- self_attention_mask = self_attention_mask * attention_mask.reshape(batch_size, 1, -1).to(
708
- dtype=torch.bool, device=self_attention_mask.device
709
- )
710
-
711
- # MQA models: (batch_size, query_length, n_heads, key_length)
712
- # MHA models: (batch_size, n_heads, query_length, key_length)
713
- attention_mask = self_attention_mask.unsqueeze(1)
714
-
715
- encoder_attention_mask = None
716
-
717
- # Prepare head mask if needed
718
- # 1.0 in head_mask indicate we keep the head
719
- # attention_probs has shape bsz x n_heads x N x N
720
- # head_mask has shape n_layer x batch x n_heads x N x N
721
- head_mask = self.get_head_mask(head_mask, self.config.n_layer)
722
-
723
- if inputs_embeds is None:
724
- inputs_embeds = self.wte(input_ids)
725
-
726
- hidden_states = inputs_embeds
727
- if self.position_embedding_type == "learned_absolute":
728
- position_embeds = self.wpe(position_ids)
729
- hidden_states = hidden_states + position_embeds
730
-
731
- if token_type_ids is not None:
732
- token_type_embeds = self.wte(token_type_ids)
733
- hidden_states = hidden_states + token_type_embeds
734
-
735
- hidden_states = self.drop(hidden_states)
736
-
737
- output_shape = input_shape + (hidden_states.size(-1),)
738
-
739
- presents = [] if use_cache else None
740
- all_self_attentions = () if output_attentions else None
741
- all_hidden_states = () if output_hidden_states else None
742
- for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
743
- if output_hidden_states:
744
- all_hidden_states = all_hidden_states + (hidden_states,)
745
-
746
- if self.gradient_checkpointing and self.training:
747
-
748
- def create_custom_forward(module):
749
- def custom_forward(*inputs):
750
- # None for past_key_value
751
- return module(*inputs, use_cache, output_attentions)
752
-
753
- return custom_forward
754
-
755
- outputs = torch.utils.checkpoint.checkpoint(
756
- create_custom_forward(block),
757
- hidden_states,
758
- None,
759
- attention_mask,
760
- position_ids,
761
- head_mask[i],
762
- encoder_hidden_states,
763
- encoder_attention_mask,
764
- )
765
- else:
766
- outputs = block(
767
- hidden_states,
768
- layer_past=layer_past,
769
- attention_mask=attention_mask,
770
- position_ids=position_ids,
771
- head_mask=head_mask[i],
772
- encoder_hidden_states=encoder_hidden_states,
773
- encoder_attention_mask=encoder_attention_mask,
774
- use_cache=use_cache,
775
- output_attentions=output_attentions,
776
- )
777
-
778
- hidden_states = outputs[0]
779
- if use_cache:
780
- presents.append(outputs[1])
781
-
782
- if output_attentions:
783
- all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
784
-
785
- hidden_states = self.ln_f(hidden_states)
786
- hidden_states = hidden_states.reshape(output_shape)
787
- # Add last hidden state
788
- if output_hidden_states:
789
- all_hidden_states = all_hidden_states + (hidden_states,)
790
-
791
-
792
- if not return_dict:
793
- return tuple(
794
- v
795
- for v in [hidden_states, presents, all_hidden_states, all_self_attentions]
796
- if v is not None
797
- )
798
-
799
- return BaseModelOutputWithPastAndCrossAttentions(
800
- last_hidden_state=hidden_states,
801
- past_key_values=presents,
802
- hidden_states=all_hidden_states,
803
- attentions=all_self_attentions,
804
- )
805
-
806
-
807
- @add_start_docstrings(
808
- """
809
- The GPT_BIGCODE Model transformer with a language modeling head on top (linear layer with weights tied to the input
810
- embeddings).
811
- """,
812
- GPT_BIGCODE_START_DOCSTRING,
813
- )
814
- class KCLGPTForCausalLM(KCLGPTPreTrainedModel):
815
- _tied_weights_keys = ["lm_head.weight"]
816
-
817
- def __init__(self, config):
818
- super().__init__(config)
819
- self.transformer = KCLGPTModel(config)
820
- self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
821
-
822
- # Initialize weights and apply final processing
823
- self.post_init()
824
-
825
- def get_output_embeddings(self):
826
- return self.lm_head
827
-
828
- def set_output_embeddings(self, new_embeddings):
829
- self.lm_head = new_embeddings
830
-
831
- def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
832
- token_type_ids = kwargs.get("token_type_ids", None)
833
- # only last token for inputs_ids if past is defined in kwargs
834
- if past_key_values:
835
- input_ids = input_ids[:, -1].unsqueeze(-1)
836
- if token_type_ids is not None:
837
- token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
838
-
839
- attention_mask = kwargs.get("attention_mask", None)
840
- position_ids = kwargs.get("position_ids", None)
841
-
842
- if attention_mask is not None and position_ids is None:
843
- # create position_ids on the fly for batch generation
844
- position_ids = attention_mask.long().cumsum(-1) - 1
845
- position_ids.masked_fill_(attention_mask == 0, 1)
846
- if past_key_values:
847
- position_ids = position_ids[:, -1].unsqueeze(-1)
848
- else:
849
- position_ids = None
850
-
851
- # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
852
- if inputs_embeds is not None and past_key_values is None:
853
- model_inputs = {"inputs_embeds": inputs_embeds}
854
- else:
855
- model_inputs = {"input_ids": input_ids}
856
-
857
- model_inputs.update(
858
- {
859
- "past_key_values": past_key_values,
860
- "use_cache": kwargs.get("use_cache"),
861
- "position_ids": position_ids,
862
- "attention_mask": attention_mask,
863
- "token_type_ids": token_type_ids,
864
- }
865
- )
866
- return model_inputs
867
-
868
- @add_start_docstrings_to_model_forward(GPT_BIGCODE_INPUTS_DOCSTRING)
869
- def forward(
870
- self,
871
- input_ids: Optional[torch.Tensor] = None,
872
- past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
873
- attention_mask: Optional[torch.Tensor] = None,
874
- token_type_ids: Optional[torch.Tensor] = None,
875
- position_ids: Optional[torch.Tensor] = None,
876
- head_mask: Optional[torch.Tensor] = None,
877
- inputs_embeds: Optional[torch.Tensor] = None,
878
- encoder_hidden_states: Optional[torch.Tensor] = None,
879
- encoder_attention_mask: Optional[torch.Tensor] = None,
880
- labels: Optional[torch.Tensor] = None,
881
- use_cache: Optional[bool] = None,
882
- output_attentions: Optional[bool] = None,
883
- output_hidden_states: Optional[bool] = None,
884
- return_dict: Optional[bool] = None,
885
- ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
886
- r"""
887
- labels (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
888
- Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
889
- `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
890
- are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
891
- """
892
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
893
-
894
- transformer_outputs = self.transformer(
895
- input_ids,
896
- past_key_values=past_key_values,
897
- attention_mask=attention_mask,
898
- token_type_ids=token_type_ids,
899
- position_ids=position_ids,
900
- head_mask=head_mask,
901
- inputs_embeds=inputs_embeds,
902
- encoder_hidden_states=encoder_hidden_states,
903
- encoder_attention_mask=encoder_attention_mask,
904
- use_cache=use_cache,
905
- output_attentions=output_attentions,
906
- output_hidden_states=output_hidden_states,
907
- return_dict=return_dict,
908
- )
909
- hidden_states = transformer_outputs[0]
910
- lm_logits = self.lm_head(hidden_states)
911
- loss = None
912
- if labels is not None:
913
- # Shift so that tokens < n predict n
914
- shift_logits = lm_logits[..., :-1, :].contiguous()
915
- shift_labels = labels[..., 1:].contiguous().to(shift_logits.device)
916
- # Flatten the tokens
917
- loss_fct = CrossEntropyLoss()
918
- loss = loss_fct(shift_logits.reshape(-1, shift_logits.size(-1)), shift_labels.reshape(-1))
919
-
920
- if not return_dict:
921
- output = (lm_logits,) + transformer_outputs[1:]
922
- return ((loss,) + output) if loss is not None else output
923
-
924
- return CausalLMOutputWithCrossAttentions(
925
- loss=loss,
926
- logits=lm_logits,
927
- past_key_values=transformer_outputs.past_key_values,
928
- hidden_states=transformer_outputs.hidden_states,
929
- attentions=transformer_outputs.attentions,
930
- )
931
-
932
- @staticmethod
933
- def _reorder_cache(past_key_values, beam_idx):
934
- reordered_past = ()
935
- for layer_past in past_key_values:
936
- reordered_past += (
937
- tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
938
- )
939
- return reordered_past