vtabbott commited on
Commit
81a61ce
1 Parent(s): 71cff16

Upload neural circuit diagrams.ipynb

Browse files
Files changed (1) hide show
  1. neural circuit diagrams.ipynb +898 -0
neural circuit diagrams.ipynb ADDED
@@ -0,0 +1,898 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 19,
6
+ "metadata": {},
7
+ "outputs": [],
8
+ "source": [
9
+ "import torch\n",
10
+ "import typing\n",
11
+ "import functorch\n",
12
+ "import itertools"
13
+ ]
14
+ },
15
+ {
16
+ "cell_type": "markdown",
17
+ "metadata": {},
18
+ "source": [
19
+ "# 2.3 Tensors\n",
20
+ "### We diagrams tensors, which can be vertically and horizontally decomposed.\n",
21
+ "<img src=\"SVG/rediagram.svg\" width=\"700\">"
22
+ ]
23
+ },
24
+ {
25
+ "cell_type": "code",
26
+ "execution_count": 20,
27
+ "metadata": {},
28
+ "outputs": [
29
+ {
30
+ "data": {
31
+ "text/plain": [
32
+ "tensor([[0.6837, 0.6853]])"
33
+ ]
34
+ },
35
+ "execution_count": 20,
36
+ "metadata": {},
37
+ "output_type": "execute_result"
38
+ }
39
+ ],
40
+ "source": [
41
+ "# This diagram shows a function h : 3, 4 2, 6 -> 1 2 constructed out of f: 4 2, 6 -> 3 3 and g: 3, 3 3 -> 1 2\n",
42
+ "# We use assertions and random outputs to represent generic functions, and how diagrams relate to code.\n",
43
+ "T = torch.Tensor\n",
44
+ "def f(x0 : T, x1 : T):\n",
45
+ " \"\"\" f: 4 2, 6 -> 3 3 \"\"\"\n",
46
+ " assert x0.size() == torch.Size([4,2])\n",
47
+ " assert x1.size() == torch.Size([6])\n",
48
+ " return torch.rand([3,3])\n",
49
+ "def g(x0 : T, x1: T):\n",
50
+ " \"\"\" g: 3, 3 3 -> 1 2 \"\"\"\n",
51
+ " assert x0.size() == torch.Size([3])\n",
52
+ " assert x1.size() == torch.Size([3, 3])\n",
53
+ " return torch.rand([1,2])\n",
54
+ "def h(x0 : T, x1 : T, x2 : T):\n",
55
+ " \"\"\" h: 3, 4 2, 6 -> 1 2\"\"\"\n",
56
+ " assert x0.size() == torch.Size([3])\n",
57
+ " assert x1.size() == torch.Size([4, 2])\n",
58
+ " assert x2.size() == torch.Size([6])\n",
59
+ " return g(x0, f(x1,x2))\n",
60
+ "\n",
61
+ "h(torch.rand([3]), torch.rand([4, 2]), torch.rand([6]))"
62
+ ]
63
+ },
64
+ {
65
+ "cell_type": "markdown",
66
+ "metadata": {},
67
+ "source": [
68
+ "## 2.3.1 Indexes\n",
69
+ "### Figure 8: Indexes\n",
70
+ "<img src=\"SVG/indexes.svg\" width=\"700\">"
71
+ ]
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "execution_count": 21,
76
+ "metadata": {},
77
+ "outputs": [
78
+ {
79
+ "data": {
80
+ "text/plain": [
81
+ "tensor([6, 7, 8])"
82
+ ]
83
+ },
84
+ "execution_count": 21,
85
+ "metadata": {},
86
+ "output_type": "execute_result"
87
+ }
88
+ ],
89
+ "source": [
90
+ "# Extracting a subtensor is a process we are familiar with. Consider,\n",
91
+ "# A (4 3) tensor\n",
92
+ "table = torch.arange(0,12).view(4,3)\n",
93
+ "row = table[2,:]\n",
94
+ "row"
95
+ ]
96
+ },
97
+ {
98
+ "cell_type": "markdown",
99
+ "metadata": {},
100
+ "source": [
101
+ "### Figure 9: Subtensors\n",
102
+ "<img src=\"SVG/subtensors.svg\" width=\"700\">"
103
+ ]
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "execution_count": 22,
108
+ "metadata": {},
109
+ "outputs": [],
110
+ "source": [
111
+ "# Different orders of access give the same result.\n",
112
+ "# Set up a random (5 7) tensor\n",
113
+ "a, b = 5, 7\n",
114
+ "Xab = torch.rand([a] + [b])\n",
115
+ "# Show that all pairs of indexes give the same result\n",
116
+ "for ia, jb in itertools.product(range(a), range(b)):\n",
117
+ " assert Xab[ia, jb] == Xab[ia, :][jb]\n",
118
+ " assert Xab[ia, jb] == Xab[:, jb][ia]"
119
+ ]
120
+ },
121
+ {
122
+ "cell_type": "markdown",
123
+ "metadata": {},
124
+ "source": [
125
+ "## 2.3.2 Broadcasting\n",
126
+ "### Figure 10: Broadcasting\n",
127
+ "<img src=\"SVG/broadcasting0.svg\" width=\"700\">\n",
128
+ "<img src=\"SVG/broadcasting0a.svg\" width=\"700\">"
129
+ ]
130
+ },
131
+ {
132
+ "cell_type": "code",
133
+ "execution_count": 23,
134
+ "metadata": {},
135
+ "outputs": [],
136
+ "source": [
137
+ "a, b, c, d = [3], [2], [4], [3]\n",
138
+ "T = torch.Tensor\n",
139
+ "\n",
140
+ "# We have some function from a to b;\n",
141
+ "def G(Xa: T) -> T:\n",
142
+ " \"\"\" G: a -> b \"\"\"\n",
143
+ " return sum(Xa**2) + torch.ones(b)\n",
144
+ "\n",
145
+ "# We could bootstrap a definition of broadcasting,\n",
146
+ "# Note that we are using spaces to indicate tensoring. \n",
147
+ "# We will use commas for tupling, which is in line with standard notation while writing code.\n",
148
+ "def Gc(Xac: T) -> T:\n",
149
+ " \"\"\" G c : a c -> b c \"\"\"\n",
150
+ " Ybc = torch.zeros(b + c)\n",
151
+ " for j in range(c[0]):\n",
152
+ " Ybc[:,jc] = G(Xac[:,jc])\n",
153
+ " return Ybc\n",
154
+ "\n",
155
+ "# Or use a PyTorch command,\n",
156
+ "# G *: a * -> b *\n",
157
+ "Gs = torch.vmap(G, -1, -1)\n",
158
+ "\n",
159
+ "# We feed a random input, and see whether applying an index before or after\n",
160
+ "# gives the same result.\n",
161
+ "Xac = torch.rand(a + c)\n",
162
+ "for jc in range(c[0]):\n",
163
+ " assert torch.allclose(G(Xac[:,jc]), Gc(Xac)[:,jc])\n",
164
+ " assert torch.allclose(G(Xac[:,jc]), Gs(Xac)[:,jc])\n",
165
+ "\n",
166
+ "# This shows how our definition of broadcasting lines up with that used by PyTorch vmap."
167
+ ]
168
+ },
169
+ {
170
+ "cell_type": "markdown",
171
+ "metadata": {},
172
+ "source": [
173
+ "### Figure 11: Inner Broadcasting\n",
174
+ "<img src=\"SVG/inner_broadcasting0.svg\" width=\"700\">\n",
175
+ "<img src=\"SVG/inner broadcasting0a.svg\" width=\"700\">"
176
+ ]
177
+ },
178
+ {
179
+ "cell_type": "code",
180
+ "execution_count": 24,
181
+ "metadata": {},
182
+ "outputs": [],
183
+ "source": [
184
+ "a, b, c, d = [3], [2], [4], [3]\n",
185
+ "T = torch.Tensor\n",
186
+ "\n",
187
+ "# We have some function which can be inner broadcast,\n",
188
+ "def H(Xa: T, Xd: T) -> T:\n",
189
+ " \"\"\" H: a, d -> b \"\"\"\n",
190
+ " return torch.sum(torch.sqrt(Xa**2)) + torch.sum(torch.sqrt(Xd ** 2)) + torch.ones(b)\n",
191
+ "\n",
192
+ "# We can bootstrap inner broadcasting,\n",
193
+ "def Hc0(Xca: T, Xd : T) -> T:\n",
194
+ " \"\"\" c0 H: c a, d -> c d \"\"\"\n",
195
+ " # Recall that we defined a, b, c, d in [_] arrays.\n",
196
+ " Ycb = torch.zeros(c + b)\n",
197
+ " for ic in range(c[0]):\n",
198
+ " Ycb[ic, :] = H(Xca[ic, :], Xd)\n",
199
+ " return Ycb\n",
200
+ "\n",
201
+ "# But vmap offers a clear way of doing it,\n",
202
+ "# *0 H: * a, d -> * c\n",
203
+ "Hs0 = torch.vmap(H, (0, None), 0)\n",
204
+ "\n",
205
+ "# We can show this satisfies Definition 2.14 by,\n",
206
+ "Xca = torch.rand(c + a)\n",
207
+ "Xd = torch.rand(d)\n",
208
+ "for ic in range(c[0]):\n",
209
+ " assert torch.allclose(Hc0(Xca, Xd)[ic, :], H(Xca[ic, :], Xd))\n",
210
+ " assert torch.allclose(Hs0(Xca, Xd)[ic, :], H(Xca[ic, :], Xd))\n"
211
+ ]
212
+ },
213
+ {
214
+ "cell_type": "markdown",
215
+ "metadata": {},
216
+ "source": [
217
+ "### Figure 12 Elementwise operations\n",
218
+ "<img src=\"SVG/elementwise0.svg\" width=\"700\">"
219
+ ]
220
+ },
221
+ {
222
+ "cell_type": "code",
223
+ "execution_count": 25,
224
+ "metadata": {},
225
+ "outputs": [],
226
+ "source": [
227
+ "\n",
228
+ "# Elementwise operations are implemented as usual ie\n",
229
+ "def f(x):\n",
230
+ " \"f : 1 -> 1\"\n",
231
+ " return x ** 2\n",
232
+ "\n",
233
+ "# We broadcast an elementwise operation,\n",
234
+ "# f *: * -> *\n",
235
+ "fs = torch.vmap(f)\n",
236
+ "\n",
237
+ "Xa = torch.rand(a)\n",
238
+ "for i in range(a[0]):\n",
239
+ " # And see that it aligns with the index before = index after framework.\n",
240
+ " assert torch.allclose(f(Xa[i]), fs(Xa)[i])\n",
241
+ " # But, elementwise operations are implied, so no special implementation is needed. \n",
242
+ " assert torch.allclose(f(Xa[i]), f(Xa)[i])"
243
+ ]
244
+ },
245
+ {
246
+ "cell_type": "markdown",
247
+ "metadata": {},
248
+ "source": [
249
+ "# 2.4 Linearity\n",
250
+ "## 2.4.2 Implementing Linearity and Common Operations\n",
251
+ "### Figure 17: Multi-head Attention and Einsum\n",
252
+ "<img src=\"SVG/implementation.svg\" width=\"700\">"
253
+ ]
254
+ },
255
+ {
256
+ "cell_type": "code",
257
+ "execution_count": 26,
258
+ "metadata": {},
259
+ "outputs": [],
260
+ "source": [
261
+ "import math\n",
262
+ "import einops\n",
263
+ "x, y, k, h = 5, 3, 4, 2\n",
264
+ "Q = torch.rand([y, k, h])\n",
265
+ "K = torch.rand([x, k, h])\n",
266
+ "\n",
267
+ "# Local memory contains,\n",
268
+ "# Q: y k h # K: x k h\n",
269
+ "# Outer products, transposes, inner products, and\n",
270
+ "# diagonalization reduce to einops expressions.\n",
271
+ "# Transpose K,\n",
272
+ "K = einops.einsum(K, 'x k h -> k x h')\n",
273
+ "# Outer product and diagonalize,\n",
274
+ "X = einops.einsum(Q, K, 'y k1 h, k2 x h -> y k1 k2 x h')\n",
275
+ "# Inner product,\n",
276
+ "X = einops.einsum(X, 'y k k x h -> y x h')\n",
277
+ "# Scale,\n",
278
+ "X = X / math.sqrt(k)\n",
279
+ "\n",
280
+ "Q = torch.rand([y, k, h])\n",
281
+ "K = torch.rand([x, k, h])\n",
282
+ "\n",
283
+ "# Local memory contains,\n",
284
+ "# Q: y k h # K: x k h\n",
285
+ "X = einops.einsum(Q, K, 'y k h, x k h -> y x h')\n",
286
+ "X = X / math.sqrt(k)\n"
287
+ ]
288
+ },
289
+ {
290
+ "cell_type": "markdown",
291
+ "metadata": {},
292
+ "source": [
293
+ "## 2.4.3 Linear Algebra\n",
294
+ "### Figure 18: Graphical Linear Algebra\n",
295
+ "<img src=\"SVG/linear_algebra.svg\" width=\"700\">"
296
+ ]
297
+ },
298
+ {
299
+ "cell_type": "code",
300
+ "execution_count": 27,
301
+ "metadata": {},
302
+ "outputs": [],
303
+ "source": [
304
+ "# We will do an exercise implementing some of these equivalences.\n",
305
+ "# The reader can follow this exercise to get a better sense of how linear functions can be implemented,\n",
306
+ "# and how different forms are equivalent.\n",
307
+ "\n",
308
+ "a, b, c, d = [3], [4], [5], [3]\n",
309
+ "\n",
310
+ "# We will be using this function *a lot*\n",
311
+ "es = einops.einsum\n",
312
+ "\n",
313
+ "# F: a b c\n",
314
+ "F_matrix = torch.rand(a + b + c)\n",
315
+ "\n",
316
+ "# As an exericse we will show that the linear map F: a -> b c can be transposed in two ways.\n",
317
+ "# Either, we can broadcast, or take an outer product. We will show these are the same.\n",
318
+ "\n",
319
+ "# Transposing by broadcasting\n",
320
+ "# \n",
321
+ "def F_func(Xa: T):\n",
322
+ " \"\"\" F: a -> b c \"\"\"\n",
323
+ " return es(Xa,F_matrix,'a,a b c->b c',)\n",
324
+ "# * F: * a -> * b c\n",
325
+ "F_broadcast = torch.vmap(F_func, 0, 0)\n",
326
+ "\n",
327
+ "# We then reduce it, as in the diagram,\n",
328
+ "# b a -> b b c -> c\n",
329
+ "def F_broadcast_transpose(Xba: T):\n",
330
+ " \"\"\" (b F) (.b c): b a -> c \"\"\"\n",
331
+ " Xbbc = F_broadcast(Xba)\n",
332
+ " return es(Xbbc, 'b b c -> c')\n",
333
+ "\n",
334
+ "# Transpoing by linearity\n",
335
+ "#\n",
336
+ "# We take the outer product of Id(b) and F, and follow up with a inner product.\n",
337
+ "# This gives us,\n",
338
+ "F_outerproduct = es(torch.eye(b[0]), F_matrix,'b0 b1, a b2 c->b0 b1 a b2 c',)\n",
339
+ "# Think of this as Id(b) F: b0 a -> b1 b2 c arranged into an associated b0 b1 a b2 c tensor.\n",
340
+ "# We then take the inner product. This gives a (b a c) matrix, which can be used for a (b a -> c) map.\n",
341
+ "F_linear_transpose = es(F_outerproduct,'b B a B c->b a c',)\n",
342
+ "\n",
343
+ "# We contend that these are the same.\n",
344
+ "#\n",
345
+ "Xba = torch.rand(b + a)\n",
346
+ "assert torch.allclose(\n",
347
+ " F_broadcast_transpose(Xba), \n",
348
+ " es(Xba,F_linear_transpose, 'b a, b a c -> c'))\n",
349
+ "\n",
350
+ "# Furthermore, lets prove the unit-inner product identity.\n",
351
+ "#\n",
352
+ "# The first step is an outer product with the unit,\n",
353
+ "outerUnit = lambda Xb: es(Xb, torch.eye(b[0]), 'b0, b1 b2 -> b0 b1 b2')\n",
354
+ "# The next is a inner product over the first two axes,\n",
355
+ "dotOuter = lambda Xbbb: es(Xbbb, 'b0 b0 b1 -> b1')\n",
356
+ "# Applying both of these *should* be the identity, and hence leave any input unchanged.\n",
357
+ "Xb = torch.rand(b)\n",
358
+ "assert torch.allclose(\n",
359
+ " Xb,\n",
360
+ " dotOuter(outerUnit(Xb)))\n",
361
+ "\n",
362
+ "# Therefore, we can confidently use the expressions in Figure 18 to manipulate expressions."
363
+ ]
364
+ },
365
+ {
366
+ "cell_type": "markdown",
367
+ "metadata": {},
368
+ "source": [
369
+ "# 3.1 Basic Multi-Layer Perceptron\n",
370
+ "### Figure 19: Implementing a Basic Multi-Layer Perceptron\n",
371
+ "<img src=\"SVG/imagerec.svg\" width=\"700\">"
372
+ ]
373
+ },
374
+ {
375
+ "cell_type": "code",
376
+ "execution_count": 28,
377
+ "metadata": {},
378
+ "outputs": [
379
+ {
380
+ "data": {
381
+ "text/plain": [
382
+ "Softmax(\n",
383
+ " dim=tensor([[ 0.0150, -0.0301, 0.1395, -0.0558, 0.0024, -0.0613, -0.0163, 0.0134,\n",
384
+ " 0.0577, -0.0624]], grad_fn=<AddmmBackward0>)\n",
385
+ ")"
386
+ ]
387
+ },
388
+ "execution_count": 28,
389
+ "metadata": {},
390
+ "output_type": "execute_result"
391
+ }
392
+ ],
393
+ "source": [
394
+ "import torch.nn as nn\n",
395
+ "# Basic Image Recogniser\n",
396
+ "# This is a close copy of an introductory PyTorch tutorial:\n",
397
+ "# https://pytorch.org/tutorials/beginner/basics/buildmodel_tutorial.html\n",
398
+ "class BasicImageRecogniser(nn.Module):\n",
399
+ " def __init__(self):\n",
400
+ " super().__init__()\n",
401
+ " self.flatten = nn.Flatten()\n",
402
+ " self.linear_relu_stack = nn.Sequential(\n",
403
+ " nn.Linear(28*28, 512),\n",
404
+ " nn.ReLU(),\n",
405
+ " nn.Linear(512, 512),\n",
406
+ " nn.ReLU(),\n",
407
+ " nn.Linear(512, 10),\n",
408
+ " )\n",
409
+ " def forward(self, x):\n",
410
+ " x = self.flatten(x)\n",
411
+ " x = self.linear_relu_stack(x)\n",
412
+ " y_pred = nn.Softmax(x)\n",
413
+ " return y_pred\n",
414
+ " \n",
415
+ "my_BasicImageRecogniser = BasicImageRecogniser()\n",
416
+ "my_BasicImageRecogniser.forward(torch.rand([1,28,28]))"
417
+ ]
418
+ },
419
+ {
420
+ "cell_type": "markdown",
421
+ "metadata": {},
422
+ "source": [
423
+ "# 3.2 Neural Circuit Diagrams for the Transformer Architecture\n",
424
+ "### Figure 20: Scaled Dot-Product Attention\n",
425
+ "<img src=\"SVG/scaled_attention.svg\" width=\"700\">"
426
+ ]
427
+ },
428
+ {
429
+ "cell_type": "code",
430
+ "execution_count": 29,
431
+ "metadata": {},
432
+ "outputs": [],
433
+ "source": [
434
+ "# Note, that we need to accomodate batches, hence the ... to capture additional axes.\n",
435
+ "\n",
436
+ "# We can do the algorithm step by step,\n",
437
+ "def ScaledDotProductAttention(q: T, k: T, v: T) -> T:\n",
438
+ " ''' yk, xk, xk -> yk '''\n",
439
+ " klength = k.size()[-1]\n",
440
+ " # Transpose\n",
441
+ " k = einops.einsum(k, '... x k -> ... k x')\n",
442
+ " # Matrix Multiply / Inner Product\n",
443
+ " x = einops.einsum(q, k, '... y k, ... k x -> ... y x')\n",
444
+ " # Scale\n",
445
+ " x = x / math.sqrt(klength)\n",
446
+ " # SoftMax\n",
447
+ " x = torch.nn.Softmax(-1)(x)\n",
448
+ " # Matrix Multiply / Inner Product\n",
449
+ " x = einops.einsum(x, v, '... y x, ... x k -> ... y k')\n",
450
+ " return x\n",
451
+ "\n",
452
+ "# Alternatively, we can simultaneously broadcast linear functions.\n",
453
+ "def ScaledDotProductAttention(q: T, k: T, v: T) -> T:\n",
454
+ " ''' yk, xk, xk -> yk '''\n",
455
+ " klength = k.size()[-1]\n",
456
+ " # Inner Product and Scale\n",
457
+ " x = einops.einsum(q, k, '... y k, ... x k -> ... y x')\n",
458
+ " # Scale and SoftMax \n",
459
+ " x = torch.nn.Softmax(-1)(x / math.sqrt(klength))\n",
460
+ " # Final Inner Product\n",
461
+ " x = einops.einsum(x, v, '... y x, ... x k -> ... y k')\n",
462
+ " return x"
463
+ ]
464
+ },
465
+ {
466
+ "cell_type": "markdown",
467
+ "metadata": {},
468
+ "source": [
469
+ "### Figure 21: Multi-Head Attention\n",
470
+ "<img src=\"SVG/multihead0.svg\" width=\"700\">\n",
471
+ "\n",
472
+ "We will be implementing this algorithm. This shows us how we go from diagrams to implementations, and begins to give an idea of how organized diagrams leads to organized code."
473
+ ]
474
+ },
475
+ {
476
+ "cell_type": "code",
477
+ "execution_count": 30,
478
+ "metadata": {},
479
+ "outputs": [],
480
+ "source": [
481
+ "def MultiHeadDotProductAttention(q: T, k: T, v: T) -> T:\n",
482
+ " ''' ykh, xkh, xkh -> ykh '''\n",
483
+ " klength = k.size()[-2]\n",
484
+ " x = einops.einsum(q, k, '... y k h, ... x k h -> ... y x h')\n",
485
+ " x = torch.nn.Softmax(-2)(x / math.sqrt(klength))\n",
486
+ " x = einops.einsum(x, v, '... y x h, ... x k h -> ... y k h')\n",
487
+ " return x\n",
488
+ "\n",
489
+ "# We implement this component as a neural network model.\n",
490
+ "# This is necessary when there are bold, learned components that need to be initialized.\n",
491
+ "class MultiHeadAttention(nn.Module):\n",
492
+ " # Multi-Head attention has various settings, which become variables\n",
493
+ " # for the initializer.\n",
494
+ " def __init__(self, m, k, h):\n",
495
+ " super().__init__()\n",
496
+ " self.m, self.k, self.h = m, k, h\n",
497
+ " # Set up all the boldface, learned components\n",
498
+ " # Note how they bind axes we want to split, which we do later with einops.\n",
499
+ " self.Lq = nn.Linear(m, k*h, False)\n",
500
+ " self.Lk = nn.Linear(m, k*h, False)\n",
501
+ " self.Lv = nn.Linear(m, k*h, False)\n",
502
+ " self.Lo = nn.Linear(k*h, m, False)\n",
503
+ "\n",
504
+ "\n",
505
+ " # We have endogenous data (Eym) and external / injected data (Xxm)\n",
506
+ " def forward(self, Eym, Xxm):\n",
507
+ " \"\"\" y m, x m -> y m \"\"\"\n",
508
+ " # We first generate query, key, and value vectors.\n",
509
+ " # Linear layers are automatically broadcast.\n",
510
+ "\n",
511
+ " # However, the k and h axes are bound. We define an unbinder to handle the outputs,\n",
512
+ " unbind = lambda x: einops.rearrange(x, '... (k h)->... k h', h=self.h)\n",
513
+ " q = unbind(self.Lq(Eym))\n",
514
+ " k = unbind(self.Lk(Xxm))\n",
515
+ " v = unbind(self.Lv(Xxm))\n",
516
+ "\n",
517
+ " # We feed q, k, and v to standard Multi-Head inner product Attention\n",
518
+ " o = MultiHeadDotProductAttention(q, k, v)\n",
519
+ "\n",
520
+ " # Rebind to feed to the final learned layer,\n",
521
+ " o = einops.rearrange(o, '... k h-> ... (k h)', h=self.h)\n",
522
+ " return self.Lo(o)\n",
523
+ "\n",
524
+ "# Now we can run it on fake data;\n",
525
+ "y, x, m, jc, heads = [20], [22], [128], [16], 4\n",
526
+ "# Internal Data\n",
527
+ "Eym = torch.rand(y + m)\n",
528
+ "# External Data\n",
529
+ "Xxm = torch.rand(x + m)\n",
530
+ "\n",
531
+ "mha = MultiHeadAttention(m[0],jc[0],heads)\n",
532
+ "assert list(mha.forward(Eym, Xxm).size()) == y + m\n"
533
+ ]
534
+ },
535
+ {
536
+ "cell_type": "markdown",
537
+ "metadata": {},
538
+ "source": [
539
+ "# 3.4 Computer Vision\n",
540
+ "\n",
541
+ "Here, we really start to understand why splitting diagrams into ``fenced off'' blocks aids implementation. \n",
542
+ "In addition to making diagrams easier to understand and patterns more clearn, blocks indicate how code can structured and organized.\n",
543
+ "\n",
544
+ "## Figure 26: Identity Residual Network\n",
545
+ "<img src=\"SVG/IdResNet_overall.svg\" width=\"700\">\n"
546
+ ]
547
+ },
548
+ {
549
+ "cell_type": "code",
550
+ "execution_count": 31,
551
+ "metadata": {},
552
+ "outputs": [],
553
+ "source": [
554
+ "# For Figure 26, every fenced off region is its own module.\n",
555
+ "\n",
556
+ "# Batch norm and then activate is a repeated motif,\n",
557
+ "class NormActivate(nn.Sequential):\n",
558
+ " def __init__(self, nf, Norm=nn.BatchNorm2d, Activation=nn.ReLU):\n",
559
+ " super().__init__(Norm(nf), Activation())\n",
560
+ "\n",
561
+ "def size_to_string(size):\n",
562
+ " return \" \".join(map(str,list(size)))\n",
563
+ "\n",
564
+ "# The Identity ResNet block breaks down into a manageable sequence of components.\n",
565
+ "class IdentityResNet(nn.Sequential):\n",
566
+ " def __init__(self, N=3, n_mu=[16,64,128,256], y=10):\n",
567
+ " super().__init__(\n",
568
+ " nn.Conv2d(3, n_mu[0], 3, padding=1),\n",
569
+ " Block(1, N, n_mu[0], n_mu[1]),\n",
570
+ " Block(2, N, n_mu[1], n_mu[2]),\n",
571
+ " Block(2, N, n_mu[2], n_mu[3]),\n",
572
+ " NormActivate(n_mu[3]),\n",
573
+ " nn.AdaptiveAvgPool2d(1),\n",
574
+ " nn.Flatten(),\n",
575
+ " nn.Linear(n_mu[3], y),\n",
576
+ " nn.Softmax(-1),\n",
577
+ " )"
578
+ ]
579
+ },
580
+ {
581
+ "cell_type": "markdown",
582
+ "metadata": {},
583
+ "source": [
584
+ "The Block can be defined in a seperate model, keeping the code manageable and closely connected to the diagram.\n",
585
+ "\n",
586
+ "<img src=\"SVG/IdResNet_block.svg\" width=\"700\">"
587
+ ]
588
+ },
589
+ {
590
+ "cell_type": "code",
591
+ "execution_count": 32,
592
+ "metadata": {},
593
+ "outputs": [],
594
+ "source": [
595
+ "# We then follow how diagrams define each ``block''\n",
596
+ "class Block(nn.Sequential):\n",
597
+ " def __init__(self, s, N, n0, n1):\n",
598
+ " \"\"\" n0 and n1 as inputs to the initializer are implicit from having them in the domain and codomain in the diagram. \"\"\"\n",
599
+ " nb = n1 // 4\n",
600
+ " super().__init__(\n",
601
+ " *[\n",
602
+ " NormActivate(n0),\n",
603
+ " ResidualConnection(\n",
604
+ " nn.Sequential(\n",
605
+ " nn.Conv2d(n0, nb, 1, s),\n",
606
+ " NormActivate(nb),\n",
607
+ " nn.Conv2d(nb, nb, 3, padding=1),\n",
608
+ " NormActivate(nb),\n",
609
+ " nn.Conv2d(nb, n1, 1),\n",
610
+ " ),\n",
611
+ " nn.Conv2d(n0, n1, 1, s),\n",
612
+ " )\n",
613
+ " ] + [\n",
614
+ " ResidualConnection(\n",
615
+ " nn.Sequential(\n",
616
+ " NormActivate(n1),\n",
617
+ " nn.Conv2d(n1, nb, 1),\n",
618
+ " NormActivate(nb),\n",
619
+ " nn.Conv2d(nb, nb, 3, padding=1),\n",
620
+ " NormActivate(nb),\n",
621
+ " nn.Conv2d(nb, n1, 1)\n",
622
+ " ),\n",
623
+ " )\n",
624
+ " ] * N\n",
625
+ " \n",
626
+ " ) \n",
627
+ "# Residual connections are a repeated pattern in the diagram. So, we are motivated to encapsulate them\n",
628
+ "# as a seperate module.\n",
629
+ "class ResidualConnection(nn.Module):\n",
630
+ " def __init__(self, mainline : nn.Module, connection : nn.Module | None = None) -> None:\n",
631
+ " super().__init__()\n",
632
+ " self.main = mainline\n",
633
+ " self.secondary = nn.Identity() if connection == None else connection\n",
634
+ " def forward(self, x):\n",
635
+ " return self.main(x) + self.secondary(x)"
636
+ ]
637
+ },
638
+ {
639
+ "cell_type": "code",
640
+ "execution_count": 33,
641
+ "metadata": {},
642
+ "outputs": [],
643
+ "source": [
644
+ "# A standard image processing algorithm has inputs shaped b c h w.\n",
645
+ "b, c, hw = [3], [3], [16, 16]\n",
646
+ "\n",
647
+ "idresnet = IdentityResNet()\n",
648
+ "Xbchw = torch.rand(b + c + hw)\n",
649
+ "\n",
650
+ "# And we see if the overall size is maintained,\n",
651
+ "assert list(idresnet.forward(Xbchw).size()) == b + [10]"
652
+ ]
653
+ },
654
+ {
655
+ "cell_type": "markdown",
656
+ "metadata": {},
657
+ "source": [
658
+ "The UNet is a more complicated algorithm than residual networks. The ``fenced off'' sections help keep our code organized. Diagrams streamline implementation, and helps keep code organized.\n",
659
+ "\n",
660
+ "## Figure 27: The UNet architecture\n",
661
+ "<img src=\"SVG/unet.svg\" width=\"700\">"
662
+ ]
663
+ },
664
+ {
665
+ "cell_type": "code",
666
+ "execution_count": 34,
667
+ "metadata": {},
668
+ "outputs": [],
669
+ "source": [
670
+ "# We notice that double convolution where the numbers of channels change is a repeated motif.\n",
671
+ "# We denote the input with c0 and output with c1. \n",
672
+ "# This can also be done for subsequent members of an iteration.\n",
673
+ "# When we go down an iteration eg. 5, 4, etc. we may have the input be c1 and the output c0.\n",
674
+ "class DoubleConvolution(nn.Sequential):\n",
675
+ " def __init__(self, c0, c1, Activation=nn.ReLU):\n",
676
+ " super().__init__(\n",
677
+ " nn.Conv2d(c0, c1, 3, padding=1),\n",
678
+ " Activation(),\n",
679
+ " nn.Conv2d(c0, c1, 3, padding=1),\n",
680
+ " Activation(),\n",
681
+ " )\n",
682
+ "\n",
683
+ "# The model is specified for a very specific number of layers,\n",
684
+ "# so we will not make it very flexible.\n",
685
+ "class UNet(nn.Module):\n",
686
+ " def __init__(self, y=2):\n",
687
+ " super().__init__()\n",
688
+ " # Set up the channel sizes;\n",
689
+ " c = [1 if i == 0 else 64 * 2 ** i for i in range(6)]\n",
690
+ "\n",
691
+ " # Saving and loading from memory means we can not use a single,\n",
692
+ " # sequential chain.\n",
693
+ "\n",
694
+ " # Set up and initialize the components;\n",
695
+ " self.DownScaleBlocks = [\n",
696
+ " DownScaleBlock(c[i],c[i+1])\n",
697
+ " for i in range(0,4)\n",
698
+ " ] # Note how this imitates the lambda operators in the diagram.\n",
699
+ " self.middleDoubleConvolution = DoubleConvolution(c[4], c[5])\n",
700
+ " self.middleUpscale = nn.ConvTranspose2d(c[5], c[4], 2, 2, 1)\n",
701
+ " self.upScaleBlocks = [\n",
702
+ " UpScaleBlock(c[5-i],c[4-i])\n",
703
+ " for i in range(1,4)\n",
704
+ " ]\n",
705
+ " self.finalConvolution = nn.Conv2d(c[1], y)\n",
706
+ "\n",
707
+ " def forward(self, x):\n",
708
+ " cLambdas = []\n",
709
+ " for dsb in self.DownScaleBlocks:\n",
710
+ " x, cLambda = dsb(x)\n",
711
+ " cLambdas.append(cLambda)\n",
712
+ " x = self.middleDoubleConvolution(x)\n",
713
+ " x = self.middleUpscale(x)\n",
714
+ " for usb in self.upScaleBlocks:\n",
715
+ " cLambda = cLambdas.pop()\n",
716
+ " x = usb(x, cLambda)\n",
717
+ " x = self.finalConvolution(x)\n",
718
+ "\n",
719
+ "class DownScaleBlock(nn.Module):\n",
720
+ " def __init__(self, c0, c1) -> None:\n",
721
+ " super().__init__()\n",
722
+ " self.doubleConvolution = DoubleConvolution(c0, c1)\n",
723
+ " self.downScaler = nn.MaxPool2d(2, 2, 1)\n",
724
+ " def forward(self, x):\n",
725
+ " cLambda = self.doubleConvolution(x)\n",
726
+ " x = self.downScaler(cLambda)\n",
727
+ " return x, cLambda\n",
728
+ "\n",
729
+ "class UpScaleBlock(nn.Module):\n",
730
+ " def __init__(self, c1, c0) -> None:\n",
731
+ " super().__init__()\n",
732
+ " self.doubleConvolution = DoubleConvolution(2*c1, c1)\n",
733
+ " self.upScaler = nn.ConvTranspose2d(c1,c0,2,2,1)\n",
734
+ " def forward(self, x, cLambda):\n",
735
+ " # Concatenation occurs over the C channel axis (dim=1)\n",
736
+ " x = torch.concat(x, cLambda, 1)\n",
737
+ " x = self.doubleConvolution(x)\n",
738
+ " x = self.upScaler(x)\n",
739
+ " return x"
740
+ ]
741
+ },
742
+ {
743
+ "cell_type": "markdown",
744
+ "metadata": {},
745
+ "source": [
746
+ "# 3.5 Vision Transformer\n",
747
+ "\n",
748
+ "We adapt our code for Multi-Head Attention to apply it to the vision case. This is a good exercise in how neural circuit diagrams allow code to be easily adapted for new modalities.\n",
749
+ "## Figure 28: Visual Attention\n",
750
+ "<img src=\"SVG/visual_attention.svg\" width=\"700\">"
751
+ ]
752
+ },
753
+ {
754
+ "cell_type": "code",
755
+ "execution_count": 35,
756
+ "metadata": {},
757
+ "outputs": [
758
+ {
759
+ "data": {
760
+ "text/plain": [
761
+ "torch.Size([1, 33, 15, 15])"
762
+ ]
763
+ },
764
+ "execution_count": 35,
765
+ "metadata": {},
766
+ "output_type": "execute_result"
767
+ }
768
+ ],
769
+ "source": [
770
+ "class VisualAttention(nn.Module):\n",
771
+ " def __init__(self, c, k, heads = 1, kernel = 1, stride = 1):\n",
772
+ " super().__init__()\n",
773
+ " \n",
774
+ " # w gives the kernel size, which we make adjustable.\n",
775
+ " self.c, self.k, self.h, self.w = c, k, heads, kernel\n",
776
+ " # Set up all the boldface, learned components\n",
777
+ " # Note how standard components may not have axes bound in \n",
778
+ " # the same way as diagrams. This requires us to rearrange\n",
779
+ " # using the einops package.\n",
780
+ "\n",
781
+ " # The learned layers form convolutions\n",
782
+ " self.Cq = nn.Conv2d(c, k * heads, kernel, stride)\n",
783
+ " self.Ck = nn.Conv2d(c, k * heads, kernel, stride)\n",
784
+ " self.Cv = nn.Conv2d(c, k * heads, kernel, stride)\n",
785
+ " self.Co = nn.ConvTranspose2d(\n",
786
+ " k * heads, c, kernel, stride)\n",
787
+ "\n",
788
+ " # Defined previously, closely follows the diagram.\n",
789
+ " def MultiHeadDotProductAttention(self, q: T, k: T, v: T) -> T:\n",
790
+ " ''' ykh, xkh, xkh -> ykh '''\n",
791
+ " klength = k.size()[-2]\n",
792
+ " x = einops.einsum(q, k, '... y k h, ... x k h -> ... y x h')\n",
793
+ " x = torch.nn.Softmax(-2)(x / math.sqrt(klength))\n",
794
+ " x = einops.einsum(x, v, '... y x h, ... x k h -> ... y k h')\n",
795
+ " return x\n",
796
+ "\n",
797
+ " # We have endogenous data (EYc) and external / injected data (XXc)\n",
798
+ " def forward(self, EcY, XcX):\n",
799
+ " \"\"\" cY, cX -> cY \n",
800
+ " The visual attention algorithm. Injects information from Xc into Yc. \"\"\"\n",
801
+ " # query, key, and value vectors.\n",
802
+ " # We unbind the k h axes which were produced by the convolutions, and feed them\n",
803
+ " # in the normal manner to MultiHeadDotProductAttention.\n",
804
+ " unbind = lambda x: einops.rearrange(x, 'N (k h) H W -> N (H W) k h', h=self.h)\n",
805
+ " # Save size to recover it later\n",
806
+ " q = self.Cq(EcY)\n",
807
+ " W = q.size()[-1]\n",
808
+ "\n",
809
+ " # By appropriately managing the axes, minimal changes to our previous code\n",
810
+ " # is necessary.\n",
811
+ " q = unbind(q)\n",
812
+ " k = unbind(self.Ck(XcX))\n",
813
+ " v = unbind(self.Cv(XcX))\n",
814
+ " o = self.MultiHeadDotProductAttention(q, k, v)\n",
815
+ "\n",
816
+ " # Rebind to feed to the transposed convolution layer.\n",
817
+ " o = einops.rearrange(o, 'N (H W) k h -> N (k h) H W', \n",
818
+ " h=self.h, W=W)\n",
819
+ " return self.Co(o)\n",
820
+ "\n",
821
+ "# Single batch element,\n",
822
+ "b = [1]\n",
823
+ "Y, X, c, k = [16, 16], [16, 16], [33], 8\n",
824
+ "# The additional configurations,\n",
825
+ "heads, kernel, stride = 4, 3, 3\n",
826
+ "\n",
827
+ "# Internal Data,\n",
828
+ "EYc = torch.rand(b + c + Y)\n",
829
+ "# External Data,\n",
830
+ "XXc = torch.rand(b + c + X)\n",
831
+ "\n",
832
+ "# We can now run the algorithm,\n",
833
+ "visualAttention = VisualAttention(c[0], k, heads, kernel, stride)\n",
834
+ "\n",
835
+ "# Interestingly, the height/width reduces by 1 for stride\n",
836
+ "# values above 1. Otherwise, it stays the same.\n",
837
+ "visualAttention.forward(EYc, XXc).size()"
838
+ ]
839
+ },
840
+ {
841
+ "cell_type": "markdown",
842
+ "metadata": {},
843
+ "source": [
844
+ "# Appendix"
845
+ ]
846
+ },
847
+ {
848
+ "cell_type": "code",
849
+ "execution_count": 36,
850
+ "metadata": {},
851
+ "outputs": [],
852
+ "source": [
853
+ "# A container to track the size of modules,\n",
854
+ "# Replace a module definition eg.\n",
855
+ "# > self.Cq = nn.Conv2d(c, k * heads, kernel, stride)\n",
856
+ "# With;\n",
857
+ "# > self.Cq = Tracker(nn.Conv2d(c, k * heads, kernel, stride), \"Query convolution\")\n",
858
+ "# And the input / output sizes (to check diagrams) will be printed.\n",
859
+ "class Tracker(nn.Module):\n",
860
+ " def __init__(self, module: nn.Module, name : str = \"\"):\n",
861
+ " super().__init__()\n",
862
+ " self.module = module\n",
863
+ " if name:\n",
864
+ " self.name = name\n",
865
+ " else:\n",
866
+ " self.name = self.module._get_name()\n",
867
+ " def forward(self, x):\n",
868
+ " x_size = size_to_string(x.size())\n",
869
+ " x = self.module.forward(x)\n",
870
+ " y_size = size_to_string(x.size())\n",
871
+ " print(f\"{self.name}: \\t {x_size} -> {y_size}\")\n",
872
+ " return x"
873
+ ]
874
+ }
875
+ ],
876
+ "metadata": {
877
+ "kernelspec": {
878
+ "display_name": "Python 3",
879
+ "language": "python",
880
+ "name": "python3"
881
+ },
882
+ "language_info": {
883
+ "codemirror_mode": {
884
+ "name": "ipython",
885
+ "version": 3
886
+ },
887
+ "file_extension": ".py",
888
+ "mimetype": "text/x-python",
889
+ "name": "python",
890
+ "nbconvert_exporter": "python",
891
+ "pygments_lexer": "ipython3",
892
+ "version": "3.10.11"
893
+ },
894
+ "orig_nbformat": 4
895
+ },
896
+ "nbformat": 4,
897
+ "nbformat_minor": 2
898
+ }