/
activations.py
130 lines (111 loc) · 5.06 KB
/
activations.py
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
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/03_activations.ipynb.
# %% auto 0
__all__ = ['set_seed', 'Hook', 'ActivationStatsS', 'init_weights', 'NormalizationS', 'conv_block', 'cnn_layers']
# %% ../nbs/03_activations.ipynb 2
import torchvision.transforms.functional as TF
import torch
import torch.nn as nn
import torch.nn.functional as F
from operator import attrgetter
from functools import partial
import fastcore.all as fc
import math
import torcheval.metrics as tem
import matplotlib.pyplot as plt
import random
import numpy as np
from .learner import Subscriber
# %% ../nbs/03_activations.ipynb 3
def set_seed(seed, deterministic=False):
torch.use_deterministic_algorithms(deterministic)
torch.manual_seed(seed)
random.seed(seed)
np.random.seed(seed)
# %% ../nbs/03_activations.ipynb 4
class Hook():
def __init__(self, nr, layer, func):
wrapped_func = partial(func, self) # pass the Hook object into the function
self.hook = layer.register_forward_hook(wrapped_func)
self.layer_name = f'{nr}_{layer.__class__.__name__}'
def remove(self):
self.hook.remove()
# %% ../nbs/03_activations.ipynb 5
class ActivationStatsS(Subscriber):
def __init__(self, modules):
self.modules = modules
def before_fit(self, learn):
self.hooks = [Hook(i, module, partial(self.record_stats, learn)) for i, module in enumerate(self.modules)]
def record_stats(self, learn, hook, layer, inp, outp):
if learn.model.training:
if not hasattr(hook, 'stats'): hook.stats = ([], [], [], [])
acts = outp.detach().cpu()
hook.stats[0].append(acts.mean()) # get the means over all activations
hook.stats[1].append(acts.std()) # get the stds over all activations
hook.stats[2].append(acts.histc(20,-10,10)) # get the histogram counts with 20 bins (-10,10)
# computation of the not_firing_rate_per_activation
N = acts.shape[0]
flat = acts.view(N, -1) # flatten the activations: matrix of [samples, activations]
nf_rate_p_act = (flat == 0.0).sum(dim=0) / N # compute not firing rate per activations (so across the samples)
hook.stats[3].append(nf_rate_p_act)
def after_fit(self, learn):
for h in self.hooks: h.remove()
def plot(self, figsize=(15,4), average_firing_rate=False):
plots = 3 if average_firing_rate else 2
fig,axs = plt.subplots(1,plots, figsize=figsize)
legend = []
for h in self.hooks:
axs[0].plot(h.stats[0])
axs[0].set_title('mean')
axs[1].plot(h.stats[1])
axs[1].set_title('std')
if average_firing_rate:
axs[2].plot(1-torch.stack(h.stats[3]).T.mean(dim=0))
axs[2].set_title('average firing rate')
axs[2].set_ylim(0,1)
legend.append(h.layer_name)
plt.legend(legend);
def plot_hist(self, figsize=None, log=True):
if figsize is None: figsize = (15, len(self.hooks))
fig,axs = plt.subplots(math.ceil(len(self.hooks)/2), 2, figsize=figsize)
axs = axs.flat
for i, hook in enumerate(self.hooks):
d = torch.stack(hook.stats[2]).T
if log: d = d.log1p()
axs[i].imshow(d, cmap='Blues', origin='lower', aspect='auto')
axs[i].set_title(hook.layer_name)
axs[i].set_yticks(np.arange(0, 20, 2), np.arange(-10, 10, 2))
def plot_dead(self, binary=False, figsize=None):
if figsize is None: figsize = (15, len(self.hooks))
fig,axs = plt.subplots(math.ceil(len(self.hooks)/2), 2, figsize=figsize)
axs = axs.flat
for i, hook in enumerate(self.hooks):
d = torch.stack(hook.stats[3]).T
if binary: d = d == 1.0
axs[i].imshow(d, cmap='Greys', origin='lower', aspect='auto')
axs[i].set_title(hook.layer_name)
# %% ../nbs/03_activations.ipynb 6
def init_weights(m):
if isinstance(m, nn.Conv2d): torch.nn.init.kaiming_normal_(m.weight)
# %% ../nbs/03_activations.ipynb 7
class NormalizationS(Subscriber):
def __init__(self, mean, std):
self.mean = mean
self.std = std
def before_batch(self, learn):
learn.batch = [(learn.batch[0] - self.mean) / self.std, learn.batch[1]]
# %% ../nbs/03_activations.ipynb 8
def conv_block(in_c, out_c, kernel_size=3, stride=2, act=True, norm=True):
padding = kernel_size // 2
layers = [torch.nn.Conv2d(in_c, out_c, kernel_size, stride, padding, bias=not norm)]
if norm: layers.append(torch.nn.BatchNorm2d(out_c))
if act: layers.append(torch.nn.ReLU())
return nn.Sequential(*layers) if len(layers)>1 else layers[0]
# %% ../nbs/03_activations.ipynb 9
def cnn_layers(act=True):
return nn.Sequential(
conv_block(1 , 8, kernel_size=5),
conv_block(8 ,16),
conv_block(16,32),
conv_block(32,64),
conv_block(64,10, norm=False, act=False),
nn.Flatten())