-
Notifications
You must be signed in to change notification settings - Fork 0
/
layers.py
77 lines (63 loc) · 2.45 KB
/
layers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 12 13:08:32 2024
@author: Mels
"""
import torch
import torch.nn as nn
from torch.nn import functional as F
#%% Head
class Head(nn.Module):
"""
Simple verion of the Attention mechanism as described in the Attention is all you need paper"
Can be added together for the Multi-Headed Attention mechanism.
"""
def __init__(self, n_embd, head_size, block_size, dropout):
super().__init__()
self.key = nn.Linear(n_embd, head_size, bias=False)
self.query = nn.Linear(n_embd, head_size, bias=False)
self.value = nn.Linear(n_embd, head_size, bias=False)
self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))
self.dropout = nn.Dropout(dropout)
def forward(self, x):
B,T,C = x.shape
k = self.key(x)
q = self.query(x)
# compute attention scores ("affinities")
wei = q @ k.transpose(-2,-1) * C**-0.5 # (B, T, C) @ (B, C, T) -> (B, T, T)
wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # (B, T, T)
wei = F.softmax(wei, dim=-1) # (B, T, T)
wei = self.dropout(wei)
# perform the weighted aggregation of the values
v = self.value(x) # (B,T,C)
out = wei @ v # (B, T, T) @ (B, T, C) -> (B, T, C)
return out
#%% MultiHeadAttention
class MultiHeadAttention(nn.Module):
"""
Adds together multiple Heads to form the multi head attention
"""
def __init__(self, n_heads, n_embd, head_size, block_size, dropout):
super().__init__()
self.heads = nn.ModuleList([Head(n_embd=n_embd, head_size=head_size,
block_size=block_size, dropout=dropout) for _ in range(n_heads)])
#self.proj = nn.Linear(n_embd, n_embd)
self.proj = nn.Linear(n_heads * head_size, n_embd)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
out = torch.cat([h(x) for h in self.heads], dim=-1)
out = self.dropout(self.proj(out))
return out
#%% FeedFoward
class FeedFoward(nn.Module):
""" a simple linear layer followed by a non-linearity """
def __init__(self, n_embd, dropout):
super().__init__()
self.net = nn.Sequential(
nn.Linear(n_embd, 4 * n_embd),
nn.ReLU(),
nn.Linear(4 * n_embd, n_embd),
nn.Dropout(dropout),
)
def forward(self, x):
return self.net(x)