-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsolution.py
More file actions
3010 lines (2527 loc) · 114 KB
/
Copy pathsolution.py
File metadata and controls
3010 lines (2527 loc) · 114 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# cell_metadata_filter: tags,title,-all
# custom_cell_magics: kql
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.11.2
# kernelspec:
# display_name: 07_xai
# language: python
# name: python3
# ---
# %% [markdown] tags=[]
# # Exercise 7: Representation learning and XAI
#
# Representation learning has been gaining significant attention over the past years,
# driven by the rise of new architectures and the growing need in biology to extract meaningful structured information
# from increasingly high-dimensional and complex data. Yet as these models become more capable, understanding what they are actually learning becomes
# just as important as their predictive performance, and that is precisely the role of explainable AI.
#
# ### Goal of the exercises
#
# The goal of this exercise is to first build an understanding of what representation learning is,
# what we mean by a "representation" in that context, and what makes a representation good or useful.
# From there, we will explore what architectures can be used to obtain these representations, and how we can evaluate
# the quality of the obtained representations. The second half of the exercise shifts focus to Explainable AI (XAI),
# where the goal is to learn how to probe what a pre-trained classifier has learned about the data it was trained on.
#
# **In part A** we will be building models for representation learning
#
# We will:
# 1. Build and train a variational autoencoder (VAE)
# 2. Visualize and compare the latent space learned under different model parameters
# 3. Evaluate representation quality
# 4. Explore the generative properties of VAEs.
#
# **In part B** we will be working with a simple example which is a fun derivation on the MNIST dataset that you will have seen in previous exercises in this course.
# Unlike regular MNIST, our dataset is classified not by number, but by color!
#
# We will:
# 1. Load a pre-trained classifier and try applying conventional attribution methods
# 2. Train a GAN to create counterfactual images - translating images from one class to another
# 3. Evaluate the GAN - see how good it is at fooling the classifier
# 4. Create attributions from the counterfactual, and learn the differences between the classes.
#
# If time permits, we will try to apply this all over again as a bonus exercise to a much more complex and more biologically relevant problem.
#
# ### Acknowledgments
#
# This notebook was written by Diane Adjavon, Maria Theiss and Anna Foix-Romero with input from
# Alex Hillsley, Ed Hirata, Larissa Heinrich, Morgan Schwartz, Anna Foix-Romero, Ben Salmon, Albert Dominguez, Talley Lambert and Eva de la Serna.
# Part B was inspired by a previous version written by Jan Funke and modified by Tri Nguyen, using code from Nils Eckstein.
# Part A has been inspired by multiple discussions between Virginie Uhlhmann, Alex Krull, Martin Weigert,
# Albert Dominguez, Ed Hirata and Anna Foix-Romero.
#
# ### AI Statement
#
# Portions of this notebook were developed with the assistance of **Claude 4.6** (Anthropic),
# accessed via the **Harvard AI Sandbox**. Prompts and responses are not used to train external models and data does not leave the
# university's controlled infrastructure.
#
# Specifically, Claude was used for:
# - **Inspiration and structure** of explanatory markdown text
# - **Debugging and refinement** of plotting and training code
# - **Drafting** of reusable helper functions
#
# All AI-assisted content was reviewed, edited, and validated by the notebook authors.
#
# ***
# %% [markdown]
# <div class="alert alert-danger">
# Set your python kernel to <code>07_xai</code>
# </div>
#
# %% [markdown]
# # PART A: Representation learning
# ## Part A.0: Conceptual introduction
# ### What is a representation and why is that useful?
# A representation is a mapping from raw data to a structured, typically lower-dimensional space, called latent space, that ideally captures meaningful features of the data.
#
# Representations
# - Can compress the data
# - Ideally learn meaningful features and discard noise and redundancy
# - Enable classification, clustering, and data generation
# - Aid interpretability
#
# ### What is a good representation?
# In many cases, good representations are...
#
# **Compact**
# Later, we will see example images of MNIST – 28 x 28 images of hand-written digits on dark background.
# Each image provides 28 x 28 = 784 pixel values. However, most of these values carry irrelevant information.
# For instance, most pixels belong to the dark background that does not contain infromation about the imaged digit.
# By keeping a representation compact (but not too compact!), we force the model to discard irrelevant information.
#
# **Smooth and continuous**
# Small changes in the input should lead to small changes in the representation. Ideally, there should be no "gaps" in the representation (this is the case for probabilistic models like Variational AutoEncoders).
# This property makes it possible to generate new data from the representation, as each location in the latent space contains meaningful information.
#
# **Structured**
# Similar inputs should be mapped to close-by locations in latent space, whereas dissimilar inputs should be distant to each other in latent space.
# This means that clusters present in the input, should also appear in latent space.
#
# **Disentangled**
# Ideally, each dimension of the latent space should capture a different feature of the input-image. For example, one dimension could capture the tilt (left-right) of handwritten digits,
# another the identity of the digits, yet another the boldness of the text.
#
# ### Unsupervised learning
# The Variational Autoencoder (VAE) trained in part A is an example of representation learning and unsupervised learning. We do not provide labels – i.e. the model trains on images of hand-written digits, but does not know the true identity (labels 0 - 9) of each image.
# This means the model is learning structural information that is intrinsic to the data. It does so by fulfilling two training objectives:
# - Reconstruction: Reconstruction-loss incentivises the model to generate a reconstructed version of an input-image from the latent space. This means that the latent space needs to ideally carry information to allow for a close reconstruction.
# - Constraints on the latent space: We can impose structural constraints on the latent space, ensuring previously discussed smoothness and continuity.
#
# Unsupervised learning is valuable in applications where labels are costly to generate or entirely unknown.
#
# ---
# %% [markdown]
#
# ## Part A.1: General set-up
# In this part of the notebook, we will load the same dataset as in the previous exercise.
#
# ### Background - the MNIST dataset
# MNIST is a machine learning benchmark dataset:
# * **70,000** grayscale images of handwritten digits **0 - 9**.
# * Of which are **60,000** training images and **10,000** testing images.
# * Each image has a resolution of **28x28** pixels.
#
# It is a great dataset to introduce representation learning because it is simple enough to train quickly,
# but still structured enough that we can visually inspect and intuitively evaluate the quality of the learned representations
# and reconstructions.
#
# Documentation for this pytorch dataset is available at https://pytorch.org/vision/main/generated/torchvision.datasets.MNIST.html
#
# Let's get started and load our dataset, transforming the images into torch tensors and normalising them.
# %% [markdown]
# ### Load MNIST
# %%
import torchvision
transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()])
train_mnist = torchvision.datasets.MNIST("./mnist", train=True, download=True, transform=transform)
test_mnist = torchvision.datasets.MNIST("./mnist", train=False, download=True, transform=transform)
# %% [markdown]
# <div class="alert alert-info">
# <b>Note:</b> set the <code>download</code> argument of <code>torchvision.datasets.MNIST</code> to <code>True</code> or <code>False</code> as required when re-running the notebook. <br>
# When <code>./mnist</code> does not yet exist (on first run), make sure the first call to <code>torchvision.datasets.MNIST</code> has <code>download</code> set to <code>True</code>.
# </div>
# %% [markdown]
# #### Inspect the train data
# Let's take a look at a few loaded samples:
# %%
import matplotlib.pyplot as plt
# Show some examples
fig, axs = plt.subplots(4, 4, figsize=(8, 8))
# Load the first 16 images and labels
xs = [train_mnist[i][0] for i in range(16)] # images
ys = [train_mnist[i][1] for i in range(16)] # labels
for i, ax in enumerate(axs.flatten()):
x = xs[i]
y = ys[i]
x = x.permute((1, 2, 0)) # make channels last
im = ax.imshow(x, cmap = "gray")
ax.set_title(f"Class {y}")
ax.axis("off")
fig.colorbar(im, ax=axs, orientation='vertical', label="gray value", shrink = 0.9)
# %% [markdown]
# #### Dataloaders
# Now, from the loaded datasets (both the train and test splits), we derive the dataloaders. We use dataloaders as they provide additional load-time features.
# Specifically, a dataloader enables **iterating** over the dataset in batches. It provides **shuffling** if desired.
# Here, we set the `batch_size` for both the train and test loader, and set `shuffle` for training only.
# %%
from torch.utils.data import DataLoader
batch_size = 8
train_loader = DataLoader(train_mnist, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_mnist, batch_size=batch_size, shuffle=False)
# %% [markdown]
# The dataset iterator and the dataloader iterator differ in shape:
# %%
# Dataset iterator
smpl, lbl = next(iter(train_mnist))
print(f"dataset element shape: {smpl.shape} (class: {lbl})")
# Dataloader iterator
smpl, lbl = next(iter(train_loader))
print(f"dataloader element shape: {smpl.shape} (class: {lbl})")
# %% [markdown]
# Dataloader elements come in **8** at a time, which is the `batch_size` we set above. Hence, the first tensor dimension is the "batch" dimension and has size **8**.
# The labels are in a tensor of size **8** as opposed to a single value like in the dataset case.
# Note that, both in the dataset and in the dataloader, the data is not presented as a 2d `28x28` image, but rather as `1x28x28` 3d piece of data.
# This is useful when using multichannel data, but in our case, this extra dimension is superfluous. We will therefore drop the channel dimension for training.
#
# In Summary:
# | | Dataset | DataLoader |
# |---|---|---|
# | Image shape | `(1, 28, 28)` | `(8, 1, 28, 28)` |
# | Dimensions | Channel, Height (Y), Width (X) | Batch, Channel, Height (Y), Width (X) |
# | Label | scalar `int` | `tensor` of `batch_size` (8) `int` |
# | Batch dimension | ❌ | ✅ (size = `batch_size`) |
# %% [markdown]
# <div class="alert alert-info">
# <b>Note:</b> the term <em>dimension</em> is used throughout this exercise in roughly 2 ways. One is engineering-centric and pertains to the structure of tensor objects, specifying how the data is laid out (<em>e.g. dataloader iterator, 4-dimensional tensors with a batch dimension, a channel dimension, a height dimension and a width dimension</em>). The other use refers to the mathematical spaces that the data exists in (<em>e.g. 2-d images of 28x28=784 pixels are viewed as vectors in 784 dimensions, latent vectors from a latent space may have only 256 feature dimensions</em>).<br>
# Mind the context to avoid miss understandings.
# </div>
# %% [markdown]
# ## Part A.2: Variational Autoencoders (VAE)
# A Variational Autoencoder (VAE) is a machine learning architecture capable of learning a compressed representation of data by pushing it through a low-dimensional "bottleneck" and then expanding it back into its original size.
# The model is forced to rebuild with limited information, and must therefore learn to capture only the most important features, performing non-linear dimensionality reduction.
# <p align="center"><img src="assets/vae.png" width="100%"></p>
# In our case, we convert `28 * 28 = 784` pixel images into a **few** core features via the encoder part of the model. The decoder part then turns these few features back into `28 * 28` pixel images.
#
# ### Part A.2.1: The architecture of our VAE
# #### A shared backbone for encoder and decoder
# We choose a **Multilayer Perceptron (MLP)** as the architecture to back both the **encoder** and the **decoder**.
# MLPs consist of linear transformations (weights and biases) followed by non-linear activation functions (ReLU).
# %%
import torch.nn as nn
class MLP(nn.Module):
def __init__(self, input_dim, output_dim
, hidden_dims=[], activation=nn.ReLU(), final_activation=None ):
super().__init__()
dims = [input_dim] + hidden_dims
layers = []
for i in range(len(dims) - 1):
layers.append(nn.Linear(dims[i], dims[i + 1]))
if activation is not None: layers.append(activation)
layers.append(nn.Linear(dims[-1], output_dim))
if final_activation is not None:
layers.append(final_activation)
self.net = nn.Sequential(*layers)
def forward(self, x):
return self.net(x)
# %% [markdown]
# #### Building the `VariationalAutoEncoder` class
#
# Here we provide a `VariationalAutoEncoder` class that uses the previously defined **MLP** class for the **encoder** and **decoder**.
#
# **The encode function**:
# * Reshapes the input by dropping the unused channel dimension.
# * Reduces width and height (28 x 28) to a single dimension (28 * 28 = 784).
# * Outputs `mu` and `logvar`; single-dimensional tensors that represent the center and logvariance for a given input in the latent space.
#
# **The reparametrization trick**:
# * Allows to sample the latent variable `z` as it if came from a Normal distribution with `mu` and $std = e^{logvar/2}$
# * However, sampling `z` directly from `mu` and $std$(`logvar`) does not allow for backpropagation (random sampling is not differentiable)
# * To allow for backpropagation, we isolate the non-differentiable random sampling node and sample $\epsilon$ from a Normal distritubion with mean 0 and standard deviation 1
# * We then use this $\epsilon$ to produce `z`: `z` $=$ `mu` $+ \epsilon * e^{logvar/2}$ (here, gradient can flow through `mu` and `logvar`)
#
# 
# Source: [Wikipedia](https://en.wikipedia.org/wiki/Reparameterization_trick#).
#
#
# **The decode function**:
# * Takes in a latent vector `z` and uses an MLP to reconstruct the original sample, reshaping as appropriate.
# %% [markdown]
# <div class="alert alert-block alert-info"><h2>Task – Fill in the gaps</h2>
#
# There are gaps marked as `...`
# Fill them in:
#
# **Missing in `def __init__`**
#
# The encoder and decoder instance of the MLP are missing. Replace `...` with:
# `self.encoder`
# `self.decoder`
#
# How can you tell which is which?
#
#
# **Missing in `def reparameterize`**
#
# `epsilon` (missing twice)
# `std`
#
# Tip:
# $std = e^{logvar/2}$
# $z = mu + \epsilon * std$
#
#
# **Missing in `def forward`**
# `mu`
# `logvar`
# `z`
# `self.decode`
# `self.encode`
# `self.reparameterize`
# `xx` (this is the reconstructed image)
#
# </div>
#
#
# %% tags=["task"]
import torch
class VariationalAutoEncoder(nn.Module):
def __init__( self, w, h, latent_dim
, enc_hidden_dims=[256, 128, 64], enc_activation=nn.ReLU()
, dec_hidden_dims=[64, 128, 256], dec_activation=nn.ReLU()
):
super().__init__()
self.w = w
self.h = h
data_dim = w * h
# TODO
... = MLP( data_dim, latent_dim * 2 # latent_dim * 2, because it will be split into mu and logvar
, hidden_dims=enc_hidden_dims
, activation=enc_activation)
# TODO
... = MLP( latent_dim, data_dim
, hidden_dims=dec_hidden_dims
, activation=dec_activation
, final_activation=nn.Sigmoid())
def encode(self, x):
b = x.shape[0] # batchsize
x_flat = x.reshape(b, -1) # (8, 1, 28, 28) → (8, 784)
out = self.encoder(x_flat)
mu, logvar = torch.chunk(out, 2, dim = 1)
return mu, logvar
@staticmethod
def reparameterize(mu, logvar):
... = torch.exp(logvar / 2) # TODO
... = torch.randn_like(std) # TODO
return ... * std + mu # TODO
def decode(self, z):
out = self.decoder(z)
xx = out.reshape(-1, 1, self.w, self.h) # (8, 784) → (8, 1, 28, 28)
return xx
def forward(self, x):
..., ... = ...(x) # TODO
... = ...(mu, logvar) # TODO
... = ...(z) # TODO
return xx, z, mu, logvar
# %% tags=["solution"]
import torch
class VariationalAutoEncoder(nn.Module):
def __init__( self, w, h, latent_dim
, enc_hidden_dims=[256, 128, 64], enc_activation=nn.ReLU()
, dec_hidden_dims=[64, 128, 256], dec_activation=nn.ReLU()
):
super().__init__()
self.w = w
self.h = h
data_dim = w * h
self.encoder = MLP( data_dim, latent_dim * 2 # latent_dim * 2, because it will be split into mu and logvar
, hidden_dims=enc_hidden_dims
, activation=enc_activation)
self.decoder = MLP( latent_dim, data_dim
, hidden_dims=dec_hidden_dims
, activation=dec_activation
, final_activation=nn.Sigmoid())
def encode(self, x):
b = x.shape[0] # batchsize
x_flat = x.reshape(b, -1) # (8, 1, 28, 28) → (8, 784)
out = self.encoder(x_flat)
mu, logvar = torch.chunk(out, 2, dim = 1)
return mu, logvar
@staticmethod
def reparameterize(mu, logvar):
std = torch.exp(logvar / 2)
epsilon = torch.randn_like(std)
return epsilon * std + mu
def decode(self, z):
out = self.decoder(z)
xx = out.reshape(-1, 1, self.w, self.h) # (8, 784) → (8, 1, 28, 28)
return xx
def forward(self, x):
mu, logvar = self.encode(x)
z = self.reparameterize(mu, logvar)
xx = self.decode(z)
return xx, z, mu, logvar
# %% [markdown]
# Run the following tests to confirm:
# %%
import inspect
import re
def normalize(s):
return re.sub(r'\s+', '', s)
def test_vae(w=28, h=28, latent_dim=16, batch_size=8):
vae = VariationalAutoEncoder(w, h, latent_dim)
data_dim = w * h
x = torch.randn(batch_size, 1, w, h)
# __init__: self.encoder
assert hasattr(vae, 'encoder'), \
"❌ 'self.encoder' missing or misspelled — correct it in __init__"
try:
enc_out = vae.encoder(torch.randn(batch_size, data_dim))
except RuntimeError:
raise AssertionError(
f"❌ self.encoder crashed on input shape ({batch_size}, {data_dim}) "
f"— did you swap self.encoder and self.decoder?"
)
assert enc_out.shape == (batch_size, latent_dim * 2), \
f"❌ encoder output {enc_out.shape} ≠ ({batch_size}, {latent_dim*2}) — did you swap encoder/decoder?"
print("✅ self.encoder: correct")
# __init__: self.decoder
assert hasattr(vae, 'decoder'), \
"❌ 'self.decoder' missing or misspelled — correct it in __init__"
try:
dec_out = vae.decoder(torch.randn(batch_size, latent_dim))
except RuntimeError:
raise AssertionError(
f"❌ self.decoder crashed on input shape ({batch_size}, {latent_dim}) "
f"— did you swap self.encoder and self.decoder?"
)
assert dec_out.shape == (batch_size, data_dim), \
f"❌ decoder output {dec_out.shape} ≠ ({batch_size}, {data_dim}) — did you swap encoder/decoder?"
print("✅ self.decoder: correct")
# reparameterize: check variable names
norm_reparam = normalize(inspect.getsource(VariationalAutoEncoder.reparameterize))
assert normalize('std = torch.exp(logvar / 2)') in norm_reparam, \
"❌ reparameterize: first blank wrong"
print("✅ reparameterize: 'std' correct")
assert normalize('epsilon = torch.randn_like(std)') in norm_reparam, \
"❌ reparameterize: second blank wrong"
print("✅ reparameterize: 'epsilon' correct")
assert normalize('return epsilon * std + mu') in norm_reparam or \
normalize('return std * epsilon + mu') in norm_reparam or \
normalize('return mu + epsilon * std') in norm_reparam or \
normalize('return mu + std * epsilon') in norm_reparam, \
"❌ reparameterize: third blank wrong"
print("✅ reparameterize: return statement correct")
# forward: check variable names
xx, z, mu, logvar = vae(x)
assert xx.shape == (batch_size, 1, w, h), "❌ forward failed at runtime"
norm_forward = normalize(inspect.getsource(VariationalAutoEncoder.forward))
assert normalize('mu, logvar = self.encode(x)') in norm_forward, \
"❌ forward: check line 1"
assert normalize('z = self.reparameterize(mu, logvar)') in norm_forward, \
"❌ forward: check line 2"
assert normalize('xx = self.decode(z)') in norm_forward, \
"❌ forward: check line 3"
print("✅ forward: all blanks correct")
print("\n All tests passed!")
test_vae()
# %% [markdown]
# ### Part A.2.2: The loss functions
# Training a VAE balances two competing objectives:
#
# #### Reconstruction
# The reconstruction loss measures how well the decoder reconstructs an input image from the latent space.
# The **Binary Cross Entropy** reconstruction loss (**BCE loss**) is appropriate here, as we scale input images to gray values of [0, 1].
# The decoder's final activation is a Sigmoid function, mapping to the same scale of [0, 1].
#
# #### Latent space regularization
# The **Kullback-Leibler divergence** loss (**KL loss**)
# $$D_{KL}=\frac{1}{2}\sum_{j=1}^{J}(\sigma_{j}^{2}+\mu_{j}^{2}-1-log(\sigma_{j}^{2}))$$
# measures how much a learned distribution of images in the latent space diverges from a standard normal distribution, i.e. a Normal distribution with mean 0 and std 1.
# The KL-loss penalizes the latent space distribution for being different from a standard normal.
# %% [markdown]
#
#
# The reconstruction loss
# %%
# The reconstruction loss
_bce_per_pixel = nn.BCELoss(reduction="none")
def rec_loss(xx, x):
# sum over pixel dims, mean over batch — matches the kl_loss reduction
per_image = _bce_per_pixel(xx, x).flatten(start_dim=1).sum(dim=1)
return per_image.mean()
# %% [markdown]
#
#
# The KL loss
# %%
# The KL loss
def kl_loss(mu, logvar):
# sum over latent dimensions, mean over batch
return torch.mean(-0.5 * torch.sum(1 + logvar - mu**2 - logvar.exp(), dim=1))
# %% [markdown]
# #### Combined loss with beta weighting
# We combine the reconstruction loss and KL loss into an overall loss. The overall loss is what we backpropagate on.
# Parameter `beta` adds a weighting to the KL loss.
# `beta = 0` means only the reconstruction-loss influences training.
# %% [markdown]
# <div class="alert alert-block alert-info"><h2>Task – Overall loss</h2>
# Write code that weights the kl loss by beta and adds it to the reconstruction loss
# </div>
# %% tags=["task"]
def loss(rec, kl, beta):
return ...
# %% tags=["solution"]
def loss(rec, kl, beta):
return rec + beta * kl
# %% [markdown]
# <div class="alert alert-block alert-success"><h2>Checkpoint 1</h2>
# Let us know when you've reached this point!
#
# At this point we have:
#
# - Refreshed our acquaintance with MNIST
# - Explained how the dataset and dataloaders are used to iterate through large amounts of data in a structured manner
# - Familiarised ourselves with the MLP
# - Familiarised ourselves with the VAE model we are going to train
# - Prepared a composite loss, with a reconstruction term and a KLD term
#
# Next we will train our model.
# </div>
# %% [markdown]
# ### Part A.2.3: Training infrastructure
# Now we get to create and train our model on the MNIST dataset.
#
# #### A.2.3.1 Set the device
# As our model and dataset is small, on many machines, CPUs are likely to outperform GPUs:
# The overhead of transferring the data to GPU might make the model slower than running it on CPU.
# However, on our virtual machines, running it on GPU is faster:
# %%
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# %% [markdown]
# #### Part A.2.3.2: Model instance and optimizer
# **Model instance**
# We first create an instance of our `VariationalAutoEncoder` class. On construction, it needs to know the size of the data it will receive and the desired latent space size.
# We grab a sample from the dataset to derive the appropriate input size.
# We set the latent dimensions to **2**. A word of warning on this:
# %% [markdown]
# <div class="alert alert-info">
# <b> Attention: </b><code>latent_dim = 2 </code> is likely underparametrizing the latent space. We will lose a lot of relevant information when compressing a 28 x 28 image down to 2 dimensions. <br>
# However, we will roll with this for now as it helps us build an intution for the latent space. <br>
# Later, we will retrain with a higher-dimensional latent space.
# </div>
# %%
data_sample, _ = next(iter(train_mnist))
_, w, h = data_sample.shape
model = VariationalAutoEncoder(w, h, latent_dim=2).to(device)
# %% [markdown]
# **Optimizer**
# We then create an optimizer for the model's parameters. During training, gradients will be computed from the backpropagation pass.
# The optimizer will read those gradients and update the model's parameters.
# %%
from torch.optim import Adam
optimizer = Adam(model.parameters(), lr=0.0001)
# %% [markdown]
# #### Part A.2.3.3: The training "loop"
# To train a model, the general idea is to iterate through the dataset, passing each element through the model to produce a reconstruction and embed it into the latent space.
# We observe how close to the original data the reconstruction is using the reconstruction loss function, and use that observation to inform the model optimisation.
# We penalize the latent space for not following a standard normal distribution using the KL-loss.
# Performing these steps going once through all the training data is what is referred to as a training **epoch**.
# We then loop this process over for a desired arbitrary number of training epochs.
#
# Below are three functions:
# `train_epoch`: Captures training for a single epoch and returns the average epoch loss.
# `train_epochs`: Calls `train_epoch` for the desired number of epochs and returns the losses per epoch.
# `plot_losses_live`: Plots losses during training and live-updates every few epochs.
# %%
from tqdm.auto import tqdm
from itertools import islice
from IPython.display import clear_output
import matplotlib.pyplot as plt
def train_epoch(model, loader, optimizer, loss, beta):
model.train()
running_rec_loss = 0.0
running_kl_loss = 0.0
running_loss = 0.0
for x, _ in loader:
x = x.to(device)
xx, _, mu, logvar = model(x)
rec_l = rec_loss(xx, x)
kl_l = kl_loss(mu, logvar)
l = loss(rec_l, kl_l, beta = beta)
optimizer.zero_grad()
l.backward()
optimizer.step()
# Stats
running_rec_loss += rec_l.item()
running_kl_loss += kl_l.item()
running_loss += l.item()
avg_rec_loss = running_rec_loss / len(loader)
avg_kl_loss = running_kl_loss / len(loader)
avg_loss = running_loss / len(loader)
return avg_rec_loss, avg_kl_loss, avg_loss
def plot_losses_live(epoch_losses, epoch_rec_losses, epoch_kl_losses):
_, axes = plt.subplots(1, 3, figsize=(15, 3))
for ax, values, title in zip(
axes,
[epoch_losses, epoch_rec_losses, epoch_kl_losses],
["Total Loss", "Reconstruction Loss", "KL Loss"]
):
ax.plot(values, c = "k")
ax.set_title(f"{title}: {values[-1]:.4f}")
ax.set_xlabel("Epoch")
ax.grid(True, linestyle="--", alpha=0.6)
plt.tight_layout()
plt.show()
def train_epochs(n, model, loader, optimizer, loss, beta, plot_every=10):
epoch_rec_losses = []
epoch_kl_losses = []
epoch_losses = []
for epoch in range(n):
fresh_loader_iter = iter(loader)
sliced_loader = tqdm(islice(fresh_loader_iter, 100), total=100, disable=True)
avg_rec_loss, avg_kl_loss, avg_loss = train_epoch(
model, sliced_loader, optimizer, loss, beta=beta
)
epoch_rec_losses.append(avg_rec_loss)
epoch_kl_losses.append(avg_kl_loss)
epoch_losses.append(avg_loss)
if (epoch + 1) % plot_every == 0:
clear_output(wait=True)
print(f"Epoch {epoch+1}/{n} | loss={avg_loss:.4f} | rec={avg_rec_loss:.4f} | kl={avg_kl_loss:.4f}")
plot_losses_live(epoch_losses, epoch_rec_losses, epoch_kl_losses)
return {"loss": epoch_losses, "rec": epoch_rec_losses, "kl": epoch_kl_losses}
# %% [markdown]
# ### Part A.2.4: Train a model for 100 epochs
# %% [markdown]
# We can now train `model`.
# In this part, we want to understand the model rather than analyze its results.
# Therefore, we sacrifice quality for time by only training 100 epochs.
# %%
epochs = 100
train_epochs(epochs, model, train_loader, optimizer, loss, beta = 1)
# %% [markdown]
# ### Part A.2.5: Inspect the trained model
# #### Get a test image
# Let's inspect what each part of the model does.
# We will probe the model with **one** image.
# Let's get it from the `test_loader`:
# %%
x, _ = test_loader.dataset[5] # reminder: test_loader is the dataloader for the test data
print(f"Image shape : {x.shape} --- C, Y, X") # Just one image!
plt.figure(figsize=(1,1))
plt.imshow(x.squeeze(), cmap="Grays");
# %% [markdown]
# #### The encoder
# Next, we pass the loaded image to the encoder, which returns `mu` and `logvar`.
# We previously set the latent space to two dimensions. Therefore, each `mu` and `logvar` have two entries.
#
# Let's have a look at `mu` and `logvar`
# %%
model.eval()
with torch.no_grad():
mu, logvar = model.encode(x.unsqueeze(0).to(device))
print(f"mu : {mu}. Dimensions: {len(mu[0])}")
print(f"logvar: {logvar}. Dimensions: {len(logvar[0])}")
# %% [markdown]
# <div class="alert alert-block alert-info"><h3>Task: Compare size of an input image to the latent space</h3>
# The function <code>.nbytes</code> allows you to see the size of an array or tensor in bytes. <br>
# Print the size of <code>x</code>. <br>
# Compute the size of <code>mu</code> and the size of <code>logvar</code>. Print their sum. <br>
# Which is bigger: the input image, or its latent space embedding?
# %% tags=["task"]
#Example:
example_tensor = torch.zeros(1)
print(example_tensor.nbytes)
# TODO:
...
# %% tags=["solution"]
example_tensor = torch.zeros(1)
print(example_tensor.nbytes)
print(f"Input image: {x.nbytes} bytes")
print(f"mu + logvar: {mu.nbytes + logvar.nbytes} bytes")
# %% [markdown]
# #### Sample
# Values `z` are sampled from a Normal distribution with mean `mu` and standard deviation $\sigma = e^{\,\text{logvar}/2}$
# The `reparametrize` function allows for this sampling without blocking backpropagation.
# Note how `z` is different for each draw. Here, we draw twice and call the result `z_1` and `z_2`.
# %%
with torch.no_grad():
z_1 = model.reparameterize(mu, logvar)
z_2 = model.reparameterize(mu, logvar) # same mu, same logvar
print(f"z_1: {z_1}, Dimensions: {len(z_1[0])}")
print(f"z_2: {z_2}, Dimensions: {len(z_2[0])}")
print("Are the two samples the same?", z_1 == z_2 )
# %% [markdown]
# #### The decoder
# Next, we can decode `z_1` and `z_2`.
# The decoder reconstructs image `rec_1` from `z_1`, and image `rec_2` from `z_2`
# %%
with torch.no_grad():
rec_1 = model.decode(z_1).cpu().numpy().squeeze()
rec_2 = model.decode(z_2).cpu().numpy().squeeze()
# %% [markdown]
# Are the two reconstructed images the same?
# %%
fig, ax = plt.subplots(1, 4)
im0 = ax[0].imshow(x.squeeze(), cmap= "Grays")
ax[0].set_title("original")
plt.colorbar(im0, shrink = 0.2)
im0 = ax[1].imshow(rec_1, cmap= "Grays")
ax[1].set_title("rec 1")
plt.colorbar(im0, shrink = 0.2)
im1 = ax[2].imshow(rec_2, cmap= "Grays")
ax[2].set_title("rec 2")
plt.colorbar(im1, shrink = 0.2)
im2 = ax[3].imshow(rec_1 - rec_2, cmap= "RdBu")
ax[3].set_title("rec 1 - rec 2")
plt.colorbar(im2, shrink = 0.2)
plt.tight_layout()
# %% [markdown]
# Clearly not! VAEs are *probabilistic* models.
# %% [markdown]
# #### Display multiple reconstructions
# Now let's look at what reconstructions look like for multiple images.
# Below are a couple simple visualisation function to display original and reconstructed images together, and to query the model for a batch of reconstructions and display them using the first function.
# %%
def show_recon(og, recon):
"""
og and recon: Tensors of shape (B, 1, 28, 28) or (B, 784)
"""
b, c, h, w = og.shape
og = og.view(-1, h, w).detach().cpu()
recon = recon.view(-1, h, w).detach().cpu()
fig, axes = plt.subplots(nrows=2, ncols=b, figsize=(b * 1.5, 3))
for i in range(b):
# Top row: Original
axes[0, i].imshow(og[i], cmap='gray')
axes[0, i].axis('off')
if i == 0: axes[0, i].set_title("Original")
# Bottom row: Reconstruction
axes[1, i].imshow(recon[i], cmap='gray')
axes[1, i].axis('off')
if i == 0: axes[1, i].set_title("Recon")
plt.show()
#import torch
def view_test_sample(model, loader):
model.eval()
with torch.no_grad():
images, _ = next(iter(loader))
images = images.to(device)
recon, _, _, _ = model(images)
show_recon(images, recon)
# %% [markdown]
# Let's call this on our model as it currently stands.
# %%
view_test_sample(model, test_loader)
# %% [markdown]
# Not great, not terrible... After the checkpoint, we will instantiate new models and train them for longer.
# %% [markdown]
# <div class="alert alert-block alert-success"><h2>Checkpoint 2</h2>
# Let us know when you've reached this point!
#
# At this point we have:
#
# - Instanciated our model and an optimizer
# - Provided a training loop which goes through the data samples, run the model, and steps the optimizer to update the model's parameters
# - Trained the model for a few "epochs" through all the training samples and observed the loss values
# - Inspected mu and logvar produced by the encoder
# - Inspected the reconstructions produced by the decoder
#
# Next we will train our model for a larger number of epochs.
# </div>
# %% [markdown]
# ### Part A.2.6: Train two models for 500 epochs
# %% [markdown]
# #### A.2.6.1: Train a model without regularized latent space
# %% [markdown]
# <div class="alert alert-block alert-info"><h2>Task</h2>
# We will now train two models, `model0` without regularization and `model1` with regularization.
# To achieve this, we set the `beta` parameter for the loss used with `model0` to `0`.
#
# Let's train our first "serious" model.
# * Instantiate a new variational autoencoder model and name it `model0`
# * Keep `latent_dim = 2`. This is not ideal, but helps us better understand the latent space.
# * Instantiate a new optimizer
# * Pass `beta = 0`
#
# </div>
#
# %% [markdown]
# <div class="alert alert-info">
# <b> Note: </b> We set epochs to 500, which should take about 3 - 4 min per model.
# We train <b>two</b> models with this value, so 6 - 8 min in total.
# You can increase this value to 750 or 1000 if you have the time and want to improve training.
# </div>
# %%
# Increase if you have the time
n_epochs = 500
# %% tags=["task"]
model0 = VariationalAutoEncoder(...).to(device) # TODO
optimizer = Adam(model0.parameters(), lr=0.0001) # fresh optimizer
...
...
epochs = n_epochs
losses0 = train_epochs(epochs, model0, train_loader, optimizer, loss, beta = beta)
# %% tags=["solution"]
model0 = VariationalAutoEncoder(w, h, latent_dim = 2).to(device) # fresh weights
optimizer = Adam(model0.parameters(), lr=0.0001) # fresh optimizer
epochs = n_epochs
beta = 0
losses0 = train_epochs(epochs, model0, train_loader, optimizer, loss, beta = beta)
# %% [markdown]
# Let's have a look at the results. Reconstructed images should now look better.
# %%
view_test_sample(model0, test_loader)
# %% [markdown]
# <div class="alert alert-block alert-warning"><h4> Questions </h4>
#
# * Which loss is decreasing more? Why?
#
# </div>
# %% [markdown]
# <div class="alert alert-block alert-success"><h2>Checkpoint 3</h2>
# Let us know when you've reached this point!
#
# At this point we have:
#
# - Trained the model for a large number of epochs
# - Observed several reconstructions, comparing we previously obtained results
#
# Next we will attempt to regularize the model's latent space.
# </div>
# %% [markdown]
# #### A.2.6.2: Train a model with regularized latent sapce
# We are now training another model called `model1`
# %% [markdown]
# <div class="alert alert-block alert-info"><h2>Task</h2>
#
# Change one variable in the code below to train a new model with better-behaved KL loss.
# In this case, the KL loss doesn't have to decrease – we just want it to increase less.
#
# Tips:
# * Have a look at the overall loss function definitions
# * Look at the order of magnitude of the reconstruction loss and KL loss, for instance at epoch 500, to decide on a value
# * You can train for fewer epochs if you want to try multiple values. Train for `n_epochs` epochs once you decided.
# </div>
# %% tags=["task"]
model1 = VariationalAutoEncoder(w, h, latent_dim=2).to(device)
optimizer = Adam(model1.parameters(), lr=0.0001) # fresh optimizer
epochs = n_epochs
beta = # TODO
losses1 = train_epochs(epochs, model1, train_loader, optimizer, loss, beta = beta)
# %% tags=["solution"]
# beta 1
model1 = VariationalAutoEncoder(w, h, latent_dim=2).to(device)
optimizer = Adam(model1.parameters(), lr=0.0001) # fresh optimizer
epochs = n_epochs
beta = 1
losses1 = train_epochs(epochs, model1, train_loader, optimizer, loss, beta = beta)
# %% [markdown]
# Let's have a look at reconstructions for model1:
# %%
view_test_sample(model1, test_loader)