Update
[beaver.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 # A BracketedSequence is a BxTx... tensor with a first and a nb time
18 # steps to compute.
19
20 # Modules able to process it expect that they will have to process a
21 # first bracket starting at t=0, followed by a succession of brackets
22 # that move forward in time, do not overlap, and cover the axis T with
23 # no holes.
24 #
25 # Although it is more general, for a classical prompt-conditioned
26 # auto-regressive process it will be a first bracket starting at 0 and
27 # of arbitrary length for the "prompt", followed by brackets of length
28 # 1 for the successive tokens.
29 #
30 # Modules able to process brackets may implement a cache that is
31 # resetted when the input bracket starts at t=0
32
33
34 class BracketedSequence:
35     def __init__(self, x, first=None, nb=None):
36         self.x = x
37         self.first = 0 if first is None else first
38         self.nb = x.size(1) if nb is None else nb
39
40     def slice(self):
41         return self.x[:, self.first : self.first + self.nb]
42
43
44 ######################################################################
45
46
47 class WithResidual(nn.Module):
48     def __init__(self, *f):
49         super().__init__()
50         self.f = f[0] if len(f) == 1 else nn.Sequential(*f)
51
52     def forward(self, bs):
53         bs.x = bs.x + self.f(bs).x
54         return bs
55
56
57 ######################################################################
58
59
60 class CacheWrapper(nn.Module):
61     def __init__(self, *f):
62         super().__init__()
63         self.f = f[0] if len(f) == 1 else nn.Sequential(*f)
64
65     def forward(self, bs):
66         if bs.first == 0:
67             y = self.f(bs.slice())
68             self.cache_y = y.new(*((y.size(0), bs.x.size(1)) + y.size()[2:]))
69             self.cache_y[:, bs.first : bs.first + bs.nb] = y
70         else:
71             self.cache_y[:, bs.first : bs.first + bs.nb] = self.f(bs.slice())
72
73         bs.x = self.cache_y
74
75         return bs
76
77
78 ##############################
79
80
81 class AddPositionalEncoding(nn.Module):
82     def __init__(self, len_max):
83         super().__init__()
84         self.len_max = len_max
85
86     # [Vaswani et al 2018] PE_{t,2i} = sin(t/(L^{2i/D})), PE_{t,2i+1} = cos(t/(L^{2i/D}))
87
88     def forward(self, bs, order=None):
89         if bs.first == 0:
90             t = torch.arange(bs.x.size(1), dtype=bs.x.dtype, device=bs.x.device)[
91                 :, None
92             ]
93             j = torch.arange(bs.x.size(2), dtype=bs.x.dtype, device=bs.x.device)[
94                 None, :
95             ]
96             k = j % 2
97             self.pe = torch.sin(
98                 t / (self.len_max ** ((j - k) / bs.x.size(2))) + math.pi / 2 * k
99             )
100
101             if order is not None:
102                 self.pe = self.pe.gather(1, order.unsqueeze(-1).expand_as(self.pe))
103
104             self.cache_y = bs.x.new(bs.x.size())
105
106         self.cache_y[:, bs.first : bs.first + bs.nb] = (
107             bs.slice() + self.pe[bs.first : bs.first + bs.nb]
108         )
109
110         bs.x = self.cache_y
111
112         return bs
113
114
115 ##############################
116
117
118 class QKVAttention(nn.Module):
119     def __init__(
120         self, dim_in, dim_qk, dim_v, nb_heads=1, causal=False, attention_dropout=0.0
121     ):
122         super().__init__()
123
124         def randw(*d):
125             return nn.Parameter(torch.randn(*d) / math.sqrt(d[-1]))
126
127         self.causal = causal
128         self.attention_dropout = attention_dropout
129
130         self.w_q = randw(nb_heads, dim_qk, dim_in)
131         self.w_k = randw(nb_heads, dim_qk, dim_in)
132         self.w_v = randw(nb_heads, dim_v, dim_in)
133         self.w_o = randw(dim_v * nb_heads, dim_in)
134
135     def forward(self, bs_q):
136         x_q = bs_q.x
137
138         if bs_q.first == 0:
139             self.cache_k = x_q.new_zeros(
140                 x_q.size(0), self.w_k.size(0), x_q.size(1), self.w_k.size(1)
141             )
142             self.cache_v = x_q.new_zeros(
143                 x_q.size(0), self.w_v.size(0), x_q.size(1), self.w_v.size(1)
144             )
145             self.cache_y = x_q.new_zeros(x_q.size(0), x_q.size(1), self.w_o.size(1))
146
147         q = torch.einsum(
148             "ntc,hdc->nhtd", x_q[:, bs_q.first : bs_q.first + bs_q.nb], self.w_q
149         )
150         self.cache_k[:, :, bs_q.first : bs_q.first + bs_q.nb] = torch.einsum(
151             "ntc,hdc->nhtd", x_q[:, bs_q.first : bs_q.first + bs_q.nb], self.w_k
152         )
153         self.cache_v[:, :, bs_q.first : bs_q.first + bs_q.nb] = torch.einsum(
154             "ntc,hdc->nhtd", x_q[:, bs_q.first : bs_q.first + bs_q.nb], self.w_v
155         )
156
157         a = torch.einsum(
158             "nhtd,nhsd->nhts", q, self.cache_k[:, :, : bs_q.first + bs_q.nb]
159         ) / math.sqrt(self.w_q.size(1))
160
161         if self.causal:
162             if bs_q.first == 0:
163                 self.cache_attzero = (
164                     torch.arange(x_q.size(1), device=q.device)[None, None, :, None]
165                     < torch.arange(x_q.size(1), device=q.device)[None, None, None, :]
166                 )
167             a = a.masked_fill(
168                 self.cache_attzero[
169                     :, :, bs_q.first : bs_q.first + bs_q.nb, : bs_q.first + bs_q.nb
170                 ],
171                 float("-inf"),
172             )
173
174         a = a.softmax(dim=3)
175         a = F.dropout(a, self.attention_dropout, self.training)
176
177         y = torch.einsum(
178             "nhts,nhsd->nthd", a, self.cache_v[:, :, : bs_q.first + bs_q.nb]
179         ).flatten(2)
180
181         self.cache_y[:, bs_q.first : bs_q.first + bs_q.nb] = y @ self.w_o
182
183         bs_q.x = self.cache_y
184
185         return bs_q
186
187
188 ##############################
189
190
191 class MyGPT(nn.Module):
192     def __init__(
193         self,
194         vocabulary_size,
195         dim_model,
196         dim_keys,
197         dim_hidden,
198         nb_heads,
199         nb_blocks,
200         causal=False,
201         dropout=0.0,
202         len_max=1e5,
203     ):
204         super().__init__()
205
206         assert dim_model % nb_heads == 0
207
208         self.embedding = CacheWrapper(
209             nn.Embedding(vocabulary_size, dim_model), nn.Dropout(dropout)
210         )
211         self.pe = AddPositionalEncoding(len_max)
212
213         trunk_blocks = []
214
215         for b in range(nb_blocks):
216             trunk_blocks += [
217                 WithResidual(
218                     CacheWrapper(nn.LayerNorm((dim_model,))),
219                     QKVAttention(
220                         dim_in=dim_model,
221                         dim_qk=dim_keys,
222                         dim_v=dim_model // nb_heads,
223                         nb_heads=nb_heads,
224                         causal=causal,
225                         attention_dropout=dropout,
226                     ),
227                 ),
228                 WithResidual(
229                     CacheWrapper(
230                         nn.LayerNorm((dim_model,)),
231                         nn.Linear(in_features=dim_model, out_features=dim_hidden),
232                         nn.ReLU(),
233                         nn.Linear(in_features=dim_hidden, out_features=dim_model),
234                         nn.Dropout(dropout),
235                     ),
236                 ),
237             ]
238
239         self.trunk = nn.Sequential(*trunk_blocks)
240
241         self.readout = CacheWrapper(
242             nn.Linear(in_features=dim_model, out_features=vocabulary_size)
243         )
244
245         with torch.no_grad():
246             for m in self.modules():
247                 if isinstance(m, nn.Embedding):
248                     m.weight.normal_(mean=0, std=2e-2)
249                 elif isinstance(m, nn.LayerNorm):
250                     m.bias.zero_()
251                     m.weight.fill_(1.0)
252
253     def forward(self, bs, mode="standard", order=None):
254         bs = BracketedSequence(F.pad(bs.x, (1, -1)), bs.first, bs.nb)
255         if order is not None:
256             order = F.pad(order + 1, (1, -1))
257         bs = self.embedding(bs)
258         bs = self.pe(bs, order)
259
260         if mode == "standard":
261             bs = self.trunk(bs)
262             bs = self.readout(bs)
263         elif mode == "head":
264             bs = self.trunk(bs)
265         elif mode == "deep":
266             r = []
267             for l in self.trunk:
268                 bs = l(bs)
269                 r += [bs.slice()]
270             bs = BracketedSequence(torch.cat(r, -1))
271         else:
272             raise ValueError
273         return bs
274
275
276 ######################################################################
277
278 if __name__ == "__main__":
279     print("Basic check.")
280
281     vocabulary_size = 10
282     x = torch.randint(vocabulary_size, (9, 7))
283
284     model = MyGPT(
285         vocabulary_size=vocabulary_size,
286         dim_model=18,
287         dim_keys=50,
288         dim_hidden=100,
289         nb_heads=2,
290         nb_blocks=1,
291         dropout=0.1,
292     )
293
294     model.eval()
295
296     y1 = model(BracketedSequence(x)).x
297
298     y2 = torch.randn_like(y1)
299     for s in range(x.size(1)):
300         z = model(BracketedSequence(x, s, 1))
301         y2[:, s] = z.x[:, s]
302
303     # print(y1.max(dim = 2).values)
304     # print(y2.max(dim = 2).values)
305     print(f"error={((y1 - y2).norm() / (y1.norm() + y2.norm())).item()}")
306
307 ######################################################################