Update.
[mygpt.git] / mygpt.py
1 #!/usr/bin/env python
2
3 # Any copyright is dedicated to the Public Domain.
4 # https://creativecommons.org/publicdomain/zero/1.0/
5
6 # Written by Francois Fleuret <francois@fleuret.org>
7
8 import math
9
10 import torch
11
12 from torch import nn
13 from torch.nn import functional as F
14
15 ##############################
16
17 class Residual(nn.Module):
18     def __init__(self, *f):
19         super().__init__()
20         self.f = f[0] if len(f) == 1 else nn.Sequential(*f)
21
22     def forward(self, x):
23         return x + self.f(x)
24
25 ##############################
26
27 class PositionalEncoding(nn.Module):
28     def __init__(self, len_max):
29         super().__init__()
30         self.len_max = len_max
31
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}))
35     def forward(self, x):
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, :]
38         k = j%2
39         pe = torch.sin(t / (self.len_max ** ((j - k) / x.size(2))) + math.pi/2 * k)
40         return x + pe # Let broadcasting to its job
41
42 ##############################
43
44 class QKVAttention(nn.Module):
45     def __init__(
46             self,
47             dim_in, dim_qk, dim_v,
48             nb_heads = 1, causal = False, attention_dropout = 0.0
49     ):
50         super().__init__()
51
52         def randw(*d):
53             return nn.Parameter(torch.randn(*d) / math.sqrt(d[-1]))
54
55         self.causal = causal
56         self.attention_dropout = attention_dropout
57
58         self.w_q = randw(nb_heads, dim_qk, dim_in)
59         self.w_k = randw(nb_heads, dim_qk, dim_in)
60         self.w_v = randw(nb_heads, dim_v, dim_in)
61         self.w_o = randw(dim_v * nb_heads, dim_in)
62
63     def forward(self, x_q, x_kv = None):
64         if x_kv is None: x_kv = x_q
65
66         q = torch.einsum('ntc,hdc->nhtd', x_q, self.w_q)
67         k = torch.einsum('ntc,hdc->nhtd', x_kv, self.w_k)
68         v = torch.einsum('ntc,hdc->nhtd', x_kv, self.w_v)
69
70         a = torch.einsum('nhtd,nhsd->nhts', q, k) / math.sqrt(q.size(3))
71
72         if self.causal:
73             mask = torch.arange(a.size(2), device = q.device)[None, None, :, None] \
74                    < torch.arange(a.size(3), device = q.device)[None, None, None, :]
75             a = a.masked_fill(mask, float('-inf'))
76
77         a = a.softmax(dim = 3)
78         a = F.dropout(a, self.attention_dropout, self.training)
79         y = torch.einsum('nhts,nhsd->nthd', a, v).flatten(2)
80
81         y = y @ self.w_o
82
83         return y
84
85 ##############################
86
87 class MyGPT(nn.Module):
88     def __init__(self,
89                  vocabulary_size,
90                  dim_model, dim_keys, dim_hidden,
91                  nb_heads, nb_blocks, dropout = 0.):
92
93         super().__init__()
94
95         assert dim_model % nb_heads == 0
96
97         self.embedding = nn.Sequential(
98             nn.Embedding(vocabulary_size, dim_model),
99             nn.Dropout(dropout),
100             PositionalEncoding(len_max = 1e5),
101         )
102
103         trunk_blocks = [ ]
104
105         for _ in range(nb_blocks):
106             trunk_blocks += [
107                 Residual(
108                     nn.LayerNorm(dim_model),
109                     QKVAttention(
110                         dim_in = dim_model,
111                         dim_qk = dim_keys,
112                         dim_v = dim_model // nb_heads,
113                         nb_heads = nb_heads,
114                         causal = True, attention_dropout = dropout
115                     ),
116                 ),
117                 Residual(
118                     nn.LayerNorm(dim_model),
119                     nn.Linear(in_features = dim_model, out_features = dim_hidden),
120                     nn.ReLU(),
121                     nn.Linear(in_features = dim_hidden, out_features = dim_model),
122                     nn.Dropout(dropout),
123                 ),
124             ]
125
126         self.trunk = nn.Sequential(*trunk_blocks)
127
128         self.readout = nn.Linear(in_features = dim_model, out_features = vocabulary_size)
129
130     def forward(self, x):
131         x = F.pad(x, (1, 0))
132         x = self.embedding(x)
133         x = self.trunk(x)
134         x = self.readout(x)
135         return x[:, :-1]
136
137 ######################################################################
138
139 if __name__ == '__main__':
140     print('Basic check.')
141
142     vocabulary_size = 10
143     x = torch.randint(vocabulary_size, (25, 100))
144
145     model = MyGPT(
146         vocabulary_size = vocabulary_size,
147         dim_model = 18, dim_keys = 50, dim_hidden = 100,
148         nb_heads = 2, nb_blocks = 3,
149         dropout = 0.1
150     )
151
152     y = model(x)
153
154 ######################################################################