3 # Any copyright is dedicated to the Public Domain.
4 # https://creativecommons.org/publicdomain/zero/1.0/
6 # Written by Francois Fleuret <francois@fleuret.org>
13 from torch.nn import functional as F
15 ##############################
17 class Residual(nn.Module):
18 def __init__(self, *f):
20 self.f = f[0] if len(f) == 1 else nn.Sequential(*f)
25 ##############################
27 class PositionalEncoding(nn.Module):
28 def __init__(self, len_max):
30 self.len_max = len_max
32 # From Vaswani et al 2018
33 # PE_{t,2i} = sin(t/(L^{2i/D}))
34 # PE_{t,2i+1} = cos(t/(L^{2i/D}))
36 t = torch.arange(x.size(1), dtype = x.dtype, device = x.device)[:, None]
37 j = torch.arange(x.size(2), dtype = x.dtype, device = x.device)[None, :]
39 return x + torch.sin(t / (self.len_max ** ((j - k) / x.size(2))) + math.pi/2 * k)[None, :, :]
41 ##############################
43 class QKVAttention(nn.Module):
46 dim_in, dim_qk, dim_v,
47 nb_heads = 1, causal = False, attention_dropout = 0.0
52 return nn.Parameter(torch.randn(*d) / math.sqrt(d[-1]))
55 self.attention_dropout = attention_dropout
57 self.w_q = randw(nb_heads, dim_qk, dim_in)
58 self.w_k = randw(nb_heads, dim_qk, dim_in)
59 self.w_v = randw(nb_heads, dim_v, dim_in)
60 self.w_o = randw(dim_v * nb_heads, dim_in)
62 def forward(self, x_q, x_kv = None):
63 if x_kv is None: x_kv = x_q
65 q = torch.einsum('ntc,hdc->nhtd', x_q, self.w_q)
66 k = torch.einsum('ntc,hdc->nhtd', x_kv, self.w_k)
67 v = torch.einsum('ntc,hdc->nhtd', x_kv, self.w_v)
69 a = torch.einsum('nhtd,nhsd->nhts', q, k) / math.sqrt(q.size(3))
72 mask = torch.arange(a.size(2), device = q.device)[None, None, :, None] \
73 < torch.arange(a.size(3), device = q.device)[None, None, None, :]
74 a = a.masked_fill(mask, float('-inf'))
76 a = a.softmax(dim = 3)
77 a = F.dropout(a, self.attention_dropout, self.training)
78 y = torch.einsum('nhts,nhsd->nthd', a, v).flatten(2)
84 ##############################
86 class MyGPT(nn.Module):
89 dim_model, dim_keys, dim_hidden,
90 nb_heads, nb_blocks, dropout = 0.):
94 assert dim_model % nb_heads == 0
96 self.embedding = nn.Sequential(
97 nn.Embedding(vocabulary_size, dim_model),
99 PositionalEncoding(len_max = 1e5),
104 for _ in range(nb_blocks):
107 nn.LayerNorm(dim_model),
111 dim_v = dim_model // nb_heads,
113 causal = True, attention_dropout = dropout
117 nn.LayerNorm(dim_model),
118 nn.Linear(in_features = dim_model, out_features = dim_hidden),
120 nn.Linear(in_features = dim_hidden, out_features = dim_model),
125 self.trunk = nn.Sequential(*trunk_blocks)
127 self.readout = nn.Linear(in_features = dim_model, out_features = vocabulary_size)
129 def forward(self, x):
131 x = self.embedding(x)
136 ######################################################################
138 if __name__ == '__main__':
139 print('Basic check.')
142 x = torch.randint(vocabulary_size, (25, 100))
145 vocabulary_size = vocabulary_size,
146 dim_model = 18, dim_keys = 50, dim_hidden = 100,
147 nb_heads = 2, nb_blocks = 3,
153 ######################################################################