kmfoda commited on
Commit
a41c997
1 Parent(s): ced7def
config.json CHANGED
@@ -1,13 +1,13 @@
1
  {
2
- "_name_or_path": "distributed/optimized-gpt2-250m-v0.1.1",
3
  "activation_function": "gelu_new",
4
  "architectures": [
5
  "GPTOptim"
6
  ],
7
  "attn_pdrop": 0.1,
8
  "auto_map": {
9
- "AutoConfig": "distributed/optimized-gpt2-250m-v0.1.1--configuration_gpt_optimized.GPTOptimConfig",
10
- "AutoModelForCausalLM": "distributed/optimized-gpt2-250m-v0.1.1--modeling_gpt_optimized.GPTOptim"
11
  },
12
  "block_size": 1024,
13
  "bos_token_id": 50256,
 
1
  {
2
+ "_name_or_path": "distributed/optimized-gpt2-250m",
3
  "activation_function": "gelu_new",
4
  "architectures": [
5
  "GPTOptim"
6
  ],
7
  "attn_pdrop": 0.1,
8
  "auto_map": {
9
+ "AutoConfig": "distributed/optimized-gpt2-250m--configuration_gpt_optimized.GPTOptimConfig",
10
+ "AutoModelForCausalLM": "distributed/optimized-gpt2-250m--modeling_gpt_optimized.GPTOptim"
11
  },
12
  "block_size": 1024,
13
  "bos_token_id": 50256,
configuration_gpt_optimized.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig, GPT2Config
2
+ from typing import List
3
+
4
+
5
+ class GPTOptimConfig(GPT2Config):
6
+ model_type = "gpt_optimized"
7
+
8
+ def __init__(
9
+ self,
10
+ block_size: int = 1024, # max sequence length
11
+ vocab_size: int = 50257, # number of tokens: 50,000 BPE merges + 256 bytes tokens + 1 <|endoftext|> token
12
+ n_layer: int = 16, # number of layers
13
+ n_head: int = 16, # number of heads
14
+ n_embd: int = 1024, # embedding dimension
15
+ **kwargs,
16
+ ):
17
+ super().__init__(**kwargs)
18
+ self.block_size = block_size
19
+ self.vocab_size = vocab_size
20
+ self.n_layer = n_layer
21
+ self.n_head = n_head
22
+ self.n_embd = n_embd
modeling_gpt_optimized.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch.nn import CrossEntropyLoss, functional as F
4
+ from transformers import PreTrainedModel, GPT2PreTrainedModel
5
+ from .configuration_gpt_optimized import GPTOptimConfig
6
+ from transformers.modeling_outputs import CausalLMOutputWithCrossAttentions, BaseModelOutputWithPastAndCrossAttentions
7
+ from transformers.utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
8
+ from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask_for_sdpa, _prepare_4d_causal_attention_mask_for_sdpa
9
+ from typing import Optional, Tuple, Union
10
+
11
+ _CHECKPOINT_FOR_DOC = "openai-community/gpt2"
12
+ _CONFIG_FOR_DOC = "GPT2Config"
13
+
14
+ GPT2_INPUTS_DOCSTRING = r"""
15
+ Args:
16
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
17
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
18
+ `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
19
+ sequence tokens in the vocabulary.
20
+
21
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
22
+ `input_ids`.
23
+
24
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
25
+ [`PreTrainedTokenizer.__call__`] for details.
26
+
27
+ [What are input IDs?](../glossary#input-ids)
28
+ past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`):
29
+ Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
30
+ `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
31
+ their past given to this model should not be passed as `input_ids` as they have already been computed.
32
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
33
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
34
+
35
+ - 1 for tokens that are **not masked**,
36
+ - 0 for tokens that are **masked**.
37
+
38
+ If `past_key_values` is used, `attention_mask` needs to contain the masking strategy that was used for
39
+ `past_key_values`. In other words, the `attention_mask` always has to have the length:
40
+ `len(past_key_values) + len(input_ids)`
41
+
42
+ [What are attention masks?](../glossary#attention-mask)
43
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
44
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
45
+ 1]`:
46
+
47
+ - 0 corresponds to a *sentence A* token,
48
+ - 1 corresponds to a *sentence B* token.
49
+
50
+ [What are token type IDs?](../glossary#token-type-ids)
51
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
52
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
53
+ config.max_position_embeddings - 1]`.
54
+
55
+ [What are position IDs?](../glossary#position-ids)
56
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
57
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
58
+
59
+ - 1 indicates the head is **not masked**,
60
+ - 0 indicates the head is **masked**.
61
+
62
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
63
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
64
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
65
+ model's internal embedding lookup matrix.
66
+
67
+ If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
68
+ `past_key_values`).
69
+ use_cache (`bool`, *optional*):
70
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
71
+ `past_key_values`).
72
+ output_attentions (`bool`, *optional*):
73
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
74
+ tensors for more detail.
75
+ output_hidden_states (`bool`, *optional*):
76
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
77
+ more detail.
78
+ return_dict (`bool`, *optional*):
79
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
80
+ """
81
+
82
+ class CausalSelfAttention(nn.Module):
83
+
84
+ def __init__(self, config):
85
+ super().__init__()
86
+ assert config.n_embd % config.n_head == 0
87
+ # key, query, value projections for all heads, but in a batch
88
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
89
+ # output projection
90
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd)
91
+ self.c_proj.NANOGPT_SCALE_INIT = 1
92
+ # regularization
93
+ self.n_head = config.n_head
94
+ self.n_embd = config.n_embd
95
+
96
+ def forward(self, x):
97
+ B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
98
+ # calculate query, key, values for all heads in batch and move head forward to be the batch dim
99
+ # nh is "number of heads", hs is "head size", and C (number of channels) = nh * hs
100
+ # e.g. in GPT-2 (124M), n_head=12, hs=64, so nh*hs=C=768 channels in the Transformer
101
+ qkv = self.c_attn(x)
102
+ q, k, v = qkv.split(self.n_embd, dim=2)
103
+ k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
104
+ q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
105
+ v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
106
+ y = F.scaled_dot_product_attention(q, k, v, is_causal=True) # flash attention
107
+ y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
108
+ # output projection
109
+ y = self.c_proj(y)
110
+ return y
111
+
112
+ class MLP(nn.Module):
113
+
114
+ def __init__(self, config):
115
+ super().__init__()
116
+ self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd)
117
+ self.gelu = nn.GELU(approximate='tanh')
118
+ self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd)
119
+ self.c_proj.NANOGPT_SCALE_INIT = 1
120
+
121
+ def forward(self, x):
122
+ x = self.c_fc(x)
123
+ x = self.gelu(x)
124
+ x = self.c_proj(x)
125
+ return x
126
+
127
+ class Block(nn.Module):
128
+
129
+ def __init__(self, config):
130
+ super().__init__()
131
+ self.ln_1 = nn.LayerNorm(config.n_embd)
132
+ self.attn = CausalSelfAttention(config)
133
+ self.ln_2 = nn.LayerNorm(config.n_embd)
134
+ self.mlp = MLP(config)
135
+
136
+ def forward(self, x):
137
+ x = x + self.attn(self.ln_1(x))
138
+ x = x + self.mlp(self.ln_2(x))
139
+ return x
140
+
141
+ class GPT(nn.Module):
142
+
143
+ def __init__(self, config):
144
+ super().__init__()
145
+ self.config = config
146
+
147
+ self.transformer = nn.ModuleDict(dict(
148
+ wte = nn.Embedding(config.vocab_size, config.n_embd),
149
+ wpe = nn.Embedding(config.block_size, config.n_embd),
150
+ h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
151
+ ln_f = nn.LayerNorm(config.n_embd),
152
+ ))
153
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
154
+
155
+ # weight sharing scheme
156
+ self.transformer.wte.weight = self.lm_head.weight
157
+
158
+ # init params
159
+ self.apply(self._init_weights)
160
+
161
+ def _init_weights(self, module):
162
+ if isinstance(module, nn.Linear):
163
+ std = 0.02
164
+ if hasattr(module, 'NANOGPT_SCALE_INIT'):
165
+ std *= (2 * self.config.n_layer) ** -0.5
166
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
167
+ if module.bias is not None:
168
+ torch.nn.init.zeros_(module.bias)
169
+ elif isinstance(module, nn.Embedding):
170
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
171
+
172
+ class GPTOptim(GPT2PreTrainedModel):
173
+ config_class = GPTOptimConfig
174
+
175
+ def __init__(self, config):
176
+ super().__init__(config)
177
+ self.model = GPT(
178
+ config
179
+ )
180
+
181
+ def forward(self, input_ids, labels=None):
182
+ # input_ids is of shape (B, T)
183
+ B, T = input_ids.size()
184
+ assert T <= self.config.block_size, f"Cannot forward sequence of length {T}, block size is only {self.config.block_size}"
185
+ # forward the token and posisition embeddings
186
+ pos = torch.arange(0, T, dtype=torch.long, device=input_ids.device) # shape (T)
187
+ pos_emb = self.model.transformer.wpe(pos) # position embeddings of shape (T, n_embd)
188
+ tok_emb = self.model.transformer.wte(input_ids) # token embeddings of shape (B, T, n_embd)
189
+ x = tok_emb + pos_emb
190
+ # forward the blocks of the transformer
191
+ for block in self.model.transformer.h:
192
+ x = block(x)
193
+ # forward the final layernorm and the classifier
194
+ x = self.model.transformer.ln_f(x)
195
+ logits = self.model.lm_head(x) # (B, T, vocab_size)
196
+ loss = None
197
+ if labels is not None:
198
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.view(-1))
199
+ return logits, loss