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