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 | import matplotlib.pyplot as plt
import numpy as np
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from pykan.kan.KANLayer import KANLayer
import sys
def initialize_seed(seed=0):
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
class ConvMLP(nn.Module):
def __init__(self, fc_layers: list[int], device):
super().__init__()
self.conv1 = nn.Conv2d(1, 8, kernel_size=5, stride=2, device=device)
self.conv2 = nn.Conv2d(8, 16, kernel_size=5, stride=2, device=device)
n_in = 16
fcs = []
for fc in fc_layers:
fcs.append(nn.Linear(n_in, fc, device=device))
n_in = fc
self.fcs = nn.ModuleList(fcs)
def forward(self, x):
x = self.conv2(F.relu(F.max_pool2d(self.conv1(x), 2)))
x = x.reshape(x.shape[0], -1)
for fc in self.fcs:
x = fc(F.relu(x))
return x
def update_grid_from_samples(self, x):
pass
def regularize(self, lambda_l1, lambda_entropy, lambda_coef, lambda_coefdiff, small_mag_threshold=1e-16, small_reg_factor=1.0):
return 0.0
# Modified version of KAN in pykan/kan/KAN.py
class ConvKAN(nn.Module):
def __init__(self,
width: list[int],
grid=5,
k=3,
noise_scale=0.1,
noise_scale_base=0.1,
base_fun=torch.nn.SiLU(),
bias_trainable=True,
grid_eps=1.0,
grid_range=[-1, 1],
sp_trainable=True,
sb_trainable=True,
device="cpu"):
super().__init__()
### Initialize feature extraction layers
self.conv1 = nn.Conv2d(1, 8, kernel_size=5, stride=2, device=device)
self.conv2 = nn.Conv2d(8, 16, kernel_size=5, stride=2, device=device)
width.insert(0, 16)
### Initialize KAN layers
self.biases = []
self.act_fun = []
self.depth = len(width) - 1
self.width = width
for l in range(self.depth):
# splines
scale_base = 1 / np.sqrt(width[l]) + (torch.randn(width[l] * width[l + 1], ) * 2 - 1) * noise_scale_base
sp_batch = KANLayer(in_dim=width[l],
out_dim=width[l + 1],
num=grid,
k=k,
noise_scale=noise_scale,
scale_base=scale_base,
scale_sp=1.0,
base_fun=base_fun,
grid_eps=grid_eps,
grid_range=grid_range,
sp_trainable=sp_trainable,
sb_trainable=sb_trainable,
device=device)
self.act_fun.append(sp_batch)
# bias
bias = nn.Linear(width[l + 1], 1, bias=False, device=device).requires_grad_(bias_trainable)
bias.weight.data *= 0.0
self.biases.append(bias)
self.biases = nn.ModuleList(self.biases)
self.act_fun = nn.ModuleList(self.act_fun)
def forward(self, x):
# Extract features by conv
x = self.conv2(F.relu(F.max_pool2d(self.conv1(x), 2)))
x = x.reshape(x.shape[0], -1)
# Run KAN layers
self.acts = [x] # acts shape: (batch, width[l])
self.acts_scale = []
for l in range(self.depth):
x, preacts, postacts, postspline = self.act_fun[l](x)
grid_reshape = self.act_fun[l].grid.reshape(self.width[l + 1], self.width[l], -1)
input_range = grid_reshape[:, :, -1] - grid_reshape[:, :, 0] + 1e-4
output_range = torch.mean(torch.abs(postacts), dim=0)
self.acts_scale.append(output_range / input_range)
x = x + self.biases[l].weight
self.acts.append(x)
return x
def update_grid_from_samples(self, x):
for l in range(self.depth):
self.forward(x)
self.act_fun[l].update_grid_from_samples(self.acts[l])
def regularize(self, lambda_l1, lambda_entropy, lambda_coef, lambda_coefdiff, small_mag_threshold=1e-16, small_reg_factor=1.0):
def nonlinear(x, th, factor):
return (x < th) * x * factor + (x > th) * (x + (factor - 1) * th)
reg_ = 0.
for i in range(len(self.acts_scale)):
vec = self.acts_scale[i].reshape(-1, )
vec_sum = torch.sum(vec)
if vec_sum == 0.0:
continue
p = vec / vec_sum
l1 = torch.sum(nonlinear(vec, th=small_mag_threshold, factor=small_reg_factor))
entropy = - torch.sum(p * torch.log2(p + 1e-4))
reg_ += lambda_l1 * l1 + lambda_entropy * entropy # both l1 and entropy
# regularize coefficient to encourage spline to be zero
for i in range(len(self.act_fun)):
coeff_l1 = torch.sum(torch.mean(torch.abs(self.act_fun[i].coef), dim=1))
coeff_diff_l1 = torch.sum(torch.mean(torch.abs(torch.diff(self.act_fun[i].coef)), dim=1))
reg_ += lambda_coef * coeff_l1 + lambda_coefdiff * coeff_diff_l1
return reg_
def calc_accuracy(ys):
rs = []
for y, label in ys:
rs.append((torch.argmax(y, dim=1) == label).float())
r = torch.cat(rs, dim=0)
return torch.mean(r)*100.0
def train(model,
train_loader,
test_loader,
max_epoch,
lamb=0.0,
lambda_l1=1.0,
lambda_entropy=2.0,
lambda_coef=0.0,
lambda_coefdiff=0.0,
update_grid=True,
grid_update_freq=10,
loss_fn=torch.nn.CrossEntropyLoss(),
lr=0.002,
device="cpu"):
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
for epoch in range(max_epoch):
model.train()
n_samples = 0
max_samples = len(train_loader.dataset)
ys = []
for iter, (x, label) in enumerate(train_loader):
x = x.to(device)
label = label.to(device)
if iter % grid_update_freq == 0 and update_grid:
model.update_grid_from_samples(x)
y = model(x)
ys.append((y, label))
loss = loss_fn(y, label)
reg_ = model.regularize(lambda_l1, lambda_entropy, lambda_coef, lambda_coefdiff)
loss = loss + lamb * reg_
optimizer.zero_grad()
loss.backward()
optimizer.step()
n_samples += len(x)
if iter % 100 == 0:
print(f"Epoch: {epoch} [{n_samples}/{max_samples}] Loss: {loss.item():.6f}")
# Calc train accuracy
train_acc = calc_accuracy(ys)
# Calc test accuracy
model.eval()
ys = []
with torch.no_grad():
for iter, (x, label) in enumerate(test_loader):
x = x.to(device)
label = label.to(device)
y = model(x)
ys.append((y, label))
test_acc = calc_accuracy(ys)
print(f"Epoch: {epoch} [{n_samples}/{max_samples}] Loss: {loss.item():.6f} Acc(Train): {train_acc} Acc(Test): {test_acc}")
return
def main(mode):
initialize_seed(123)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
reg_lambda = 0.0
update_grid = True,
if mode == "kan":
model = ConvKAN(width=[20, 10], device=device)
elif mode == "kan-no-update-grid":
model = ConvKAN(width=[20, 10], device=device)
update_grid = False
elif mode == "kan-reg":
model = ConvKAN(width=[20, 10], device=device)
reg_lambda = 0.003
elif mode == "mlp":
model = ConvMLP(fc_layers=[20, 10], device=device)
else:
return
train_loader = DataLoader(datasets.MNIST("./data", train=True, download=True, transform=transforms.ToTensor()), batch_size=128, shuffle=True)
test_loader = DataLoader(datasets.MNIST("./data", train=False, download=True, transform=transforms.ToTensor()), batch_size=128, shuffle=False)
train(model, train_loader, test_loader, max_epoch=5, lamb=reg_lambda, update_grid=update_grid, device=device)
if __name__ == "__main__":
main(sys.argv[1])
|