Update gpt2.py
Browse files
gpt2.py
CHANGED
|
@@ -14,6 +14,7 @@ class CasualSelfAttention(nn.Module):
|
|
| 14 |
|
| 15 |
self.c_attn = nn.Linear(config.n_embd, config.n_embd * 3)
|
| 16 |
self.c_proj = nn.Linear(config.n_embd,config.n_embd)
|
|
|
|
| 17 |
|
| 18 |
self.n_head = config.n_head
|
| 19 |
self.n_embd = config.n_embd
|
|
@@ -48,7 +49,7 @@ class MLP(nn.Module):
|
|
| 48 |
self.c_fc = nn.Linear(config.n_embd,config.n_embd * 4)
|
| 49 |
self.gelu = nn.GELU(approximate="tanh")
|
| 50 |
self.c_proj = nn.Linear(config.n_embd * 4,config.n_embd)
|
| 51 |
-
|
| 52 |
|
| 53 |
def forward(self,x):
|
| 54 |
x = self.c_fc(x)
|
|
@@ -89,6 +90,19 @@ class GPT2(nn.Module):
|
|
| 89 |
#Weight sharing
|
| 90 |
self.transformer.wte.weight = self.lm_head.weight
|
| 91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
def forward(self,idx, targets= None):
|
| 93 |
B,T = idx.size()
|
| 94 |
|
|
|
|
| 14 |
|
| 15 |
self.c_attn = nn.Linear(config.n_embd, config.n_embd * 3)
|
| 16 |
self.c_proj = nn.Linear(config.n_embd,config.n_embd)
|
| 17 |
+
self.c_proj.NANOGPT_SCALE_INIT = 1
|
| 18 |
|
| 19 |
self.n_head = config.n_head
|
| 20 |
self.n_embd = config.n_embd
|
|
|
|
| 49 |
self.c_fc = nn.Linear(config.n_embd,config.n_embd * 4)
|
| 50 |
self.gelu = nn.GELU(approximate="tanh")
|
| 51 |
self.c_proj = nn.Linear(config.n_embd * 4,config.n_embd)
|
| 52 |
+
self.c_proj.NANOGPT_SCALE_INIT = 1
|
| 53 |
|
| 54 |
def forward(self,x):
|
| 55 |
x = self.c_fc(x)
|
|
|
|
| 90 |
#Weight sharing
|
| 91 |
self.transformer.wte.weight = self.lm_head.weight
|
| 92 |
|
| 93 |
+
self.apply(self._init_weights)
|
| 94 |
+
|
| 95 |
+
#
|
| 96 |
+
def _init_weights(self,module):
|
| 97 |
+
if isinstance(module,nn.Linear):
|
| 98 |
+
if hasattr(module,"NANOGPT_SCALE_INIT"):
|
| 99 |
+
std += (2*self.config.n_layer) ** -0.5
|
| 100 |
+
torch.nn.init.normal_(module.weight,mean=0.0,std=0.02)
|
| 101 |
+
if module.bias is not None:
|
| 102 |
+
torch.nn.init.zeros_(module.bias)
|
| 103 |
+
elif isinstance(module,nn.Embedding):
|
| 104 |
+
torch.nn.init.normal_(module.weight,mean=0.0,std=0.02)
|
| 105 |
+
|
| 106 |
def forward(self,idx, targets= None):
|
| 107 |
B,T = idx.size()
|
| 108 |
|