Spaces:
Sleeping
Sleeping
Download model.py from ShubhWorking/StoicGPT: direct link, hf CLI and curl.
- Browser
- Download file 3.26 kB
-
https://huggingface.co/spaces/ShubhWorking/StoicGPT/resolve/main/model.py
- Command line
-
hf download hf://spaces/ShubhWorking/StoicGPT/model.py
-
curl -L -o model.py https://huggingface.co/spaces/ShubhWorking/StoicGPT/resolve/main/model.py
3.26 kB
| import torch | |
| import torch.nn as nn | |
| from attention import MultiHeadAttention | |
| class LayerNorm(nn.Module): | |
| def __init__(self, emb_dim): | |
| super().__init__() | |
| self.eps = 1e-5 | |
| self.scale = nn.Parameter(torch.ones(emb_dim)) | |
| self.shift = nn.Parameter(torch.zeros(emb_dim)) | |
| def forward(self, x): | |
| mean = x.mean(dim=-1, keepdim=True) | |
| var = x.var(dim=-1, keepdim=True, unbiased=False) | |
| norm_x = (x - mean) / torch.sqrt(var + self.eps) | |
| return self.scale * norm_x + self.shift | |
| class GELU(nn.Module): | |
| def __init__(self): | |
| super().__init__() | |
| def forward(self, x): | |
| return 0.5 * x * (1 + torch.tanh( | |
| torch.sqrt(torch.tensor(2.0 / torch.pi)) * | |
| (x + 0.044715 * torch.pow(x, 3)) | |
| )) | |
| class FeedForward(nn.Module): | |
| def __init__(self, cfg): | |
| super().__init__() | |
| self.layers = nn.Sequential( | |
| nn.Linear(cfg["emb_dim"], 4 * cfg["emb_dim"]), | |
| GELU(), | |
| nn.Linear(4 * cfg["emb_dim"], cfg["emb_dim"]), | |
| ) | |
| def forward(self, x): | |
| return self.layers(x) | |
| class TransformerBlock(nn.Module): | |
| def __init__(self, cfg): | |
| super().__init__() | |
| self.att = MultiHeadAttention( | |
| d_in=cfg["emb_dim"], | |
| d_out=cfg["emb_dim"], | |
| context_length=cfg["context_length"], | |
| num_heads=cfg["n_heads"], | |
| dropout=cfg["drop_rate"], | |
| qkv_bias=cfg["qkv_bias"]) | |
| self.ff = FeedForward(cfg) | |
| self.norm1 = LayerNorm(cfg["emb_dim"]) | |
| self.norm2 = LayerNorm(cfg["emb_dim"]) | |
| self.drop_shortcut = nn.Dropout(cfg["drop_rate"]) | |
| def forward(self, x, kv_cache=None): | |
| shortcut = x | |
| x = self.norm1(x) | |
| x, updated_cache = self.att(x, kv_cache=kv_cache) | |
| x = self.drop_shortcut(x) | |
| x = x + shortcut | |
| shortcut = x | |
| x = self.norm2(x) | |
| x = self.ff(x) | |
| x = self.drop_shortcut(x) | |
| x = x + shortcut | |
| return x, updated_cache | |
| class GPTModel(nn.Module): | |
| def __init__(self, cfg): | |
| super().__init__() | |
| self.tok_emb = nn.Embedding(cfg["vocab_size"], cfg["emb_dim"]) | |
| self.pos_emb = nn.Embedding(cfg["context_length"], cfg["emb_dim"]) | |
| self.drop_emb = nn.Dropout(cfg["drop_rate"]) | |
| self.trf_blocks = nn.ModuleList( | |
| [TransformerBlock(cfg) for _ in range(cfg["n_layers"])]) | |
| self.final_norm = LayerNorm(cfg["emb_dim"]) | |
| self.out_head = nn.Linear(cfg["emb_dim"], cfg["vocab_size"], bias=False) | |
| def forward(self, in_idx, kv_caches=None, start_pos=0): | |
| batch_size, seq_len = in_idx.shape | |
| tok_embeds = self.tok_emb(in_idx) | |
| positions = torch.arange(start_pos, start_pos + seq_len, device=in_idx.device) | |
| pos_embeds = self.pos_emb(positions) | |
| x = tok_embeds + pos_embeds | |
| x = self.drop_emb(x) | |
| new_caches = [] | |
| for i, block in enumerate(self.trf_blocks): | |
| cache = kv_caches[i] if kv_caches is not None else None | |
| x, updated_cache = block(x, kv_cache=cache) | |
| new_caches.append(updated_cache) | |
| x = self.final_norm(x) | |
| logits = self.out_head(x) | |
| return logits, new_caches | |