forked from KindXiaoming/pykan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMultKAN.py
2785 lines (2315 loc) · 107 KB
/
MultKAN.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
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
import torch
import torch.nn as nn
import numpy as np
from .KANLayer import KANLayer
#from .Symbolic_MultKANLayer import *
from .Symbolic_KANLayer import Symbolic_KANLayer
from .LBFGS import *
import os
import glob
import matplotlib.pyplot as plt
from tqdm import tqdm
import random
import copy
#from .MultKANLayer import MultKANLayer
import pandas as pd
from sympy.printing import latex
from sympy import *
import sympy
import yaml
from .spline import curve2coef
from .utils import SYMBOLIC_LIB
from .hypothesis import plot_tree
class MultKAN(nn.Module):
'''
KAN class
Attributes:
-----------
grid : int
the number of grid intervals
k : int
spline order
act_fun : a list of KANLayers
symbolic_fun: a list of Symbolic_KANLayer
depth : int
depth of KAN
width : list
number of neurons in each layer.
Without multiplication nodes, [2,5,5,3] means 2D inputs, 3D outputs, with 2 layers of 5 hidden neurons.
With multiplication nodes, [2,[5,3],[5,1],3] means besides the [2,5,53] KAN, there are 3 (1) mul nodes in layer 1 (2).
mult_arity : int, or list of int lists
multiplication arity for each multiplication node (the number of numbers to be multiplied)
grid : int
the number of grid intervals
k : int
the order of piecewise polynomial
base_fun : fun
residual function b(x). an activation function phi(x) = sb_scale * b(x) + sp_scale * spline(x)
symbolic_fun : a list of Symbolic_KANLayer
Symbolic_KANLayers
symbolic_enabled : bool
If False, the symbolic front is not computed (to save time). Default: True.
width_in : list
The number of input neurons for each layer
width_out : list
The number of output neurons for each layer
base_fun_name : str
The base function b(x)
grip_eps : float
The parameter that interpolates between uniform grid and adaptive grid (based on sample quantile)
node_bias : a list of 1D torch.float
node_scale : a list of 1D torch.float
subnode_bias : a list of 1D torch.float
subnode_scale : a list of 1D torch.float
symbolic_enabled : bool
when symbolic_enabled = False, the symbolic branch (symbolic_fun) will be ignored in computation (set to zero)
affine_trainable : bool
indicate whether affine parameters are trainable (node_bias, node_scale, subnode_bias, subnode_scale)
sp_trainable : bool
indicate whether the overall magnitude of splines is trainable
sb_trainable : bool
indicate whether the overall magnitude of base function is trainable
save_act : bool
indicate whether intermediate activations are saved in forward pass
node_scores : None or list of 1D torch.float
node attribution score
edge_scores : None or list of 2D torch.float
edge attribution score
subnode_scores : None or list of 1D torch.float
subnode attribution score
cache_data : None or 2D torch.float
cached input data
acts : None or a list of 2D torch.float
activations on nodes
auto_save : bool
indicate whether to automatically save a checkpoint once the model is modified
state_id : int
the state of the model (used to save checkpoint)
ckpt_path : str
the folder to store checkpoints
round : int
the number of times rewind() has been called
device : str
'''
def __init__(self, width=None, grid=3, k=3, mult_arity = 2, noise_scale=0.3, scale_base_mu=0.0, scale_base_sigma=1.0, base_fun='silu', symbolic_enabled=True, affine_trainable=False, grid_eps=0.02, grid_range=[-1, 1], sp_trainable=True, sb_trainable=True, seed=1, save_act=True, sparse_init=False, auto_save=True, first_init=True, ckpt_path='./model', state_id=0, round=0, device='cpu'):
'''
initalize a KAN model
Args:
-----
width : list of int
Without multiplication nodes: :math:`[n_0, n_1, .., n_{L-1}]` specify the number of neurons in each layer (including inputs/outputs)
With multiplication nodes: :math:`[[n_0,m_0=0], [n_1,m_1], .., [n_{L-1},m_{L-1}]]` specify the number of addition/multiplication nodes in each layer (including inputs/outputs)
grid : int
number of grid intervals. Default: 3.
k : int
order of piecewise polynomial. Default: 3.
mult_arity : int, or list of int lists
multiplication arity for each multiplication node (the number of numbers to be multiplied)
noise_scale : float
initial injected noise to spline.
base_fun : str
the residual function b(x). Default: 'silu'
symbolic_enabled : bool
compute (True) or skip (False) symbolic computations (for efficiency). By default: True.
affine_trainable : bool
affine parameters are updated or not. Affine parameters include node_scale, node_bias, subnode_scale, subnode_bias
grid_eps : float
When grid_eps = 1, the grid is uniform; when grid_eps = 0, the grid is partitioned using percentiles of samples. 0 < grid_eps < 1 interpolates between the two extremes.
grid_range : list/np.array of shape (2,))
setting the range of grids. Default: [-1,1]. This argument is not important if fit(update_grid=True) (by default updata_grid=True)
sp_trainable : bool
If true, scale_sp is trainable. Default: True.
sb_trainable : bool
If true, scale_base is trainable. Default: True.
device : str
device
seed : int
random seed
save_act : bool
indicate whether intermediate activations are saved in forward pass
sparse_init : bool
sparse initialization (True) or normal dense initialization. Default: False.
auto_save : bool
indicate whether to automatically save a checkpoint once the model is modified
state_id : int
the state of the model (used to save checkpoint)
ckpt_path : str
the folder to store checkpoints. Default: './model'
round : int
the number of times rewind() has been called
device : str
Returns:
--------
self
Example
-------
>>> from kan import *
>>> model = KAN(width=[2,5,1], grid=5, k=3, seed=0)
checkpoint directory created: ./model
saving model version 0.0
'''
super(MultKAN, self).__init__()
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
### initializeing the numerical front ###
self.act_fun = []
self.depth = len(width) - 1
for i in range(len(width)):
if type(width[i]) == int:
width[i] = [width[i],0]
self.width = width
# if mult_arity is just a scalar, we extend it to a list of lists
# e.g, mult_arity = [[2,3],[4]] means that in the first hidden layer, 2 mult ops have arity 2 and 3, respectively;
# in the second hidden layer, 1 mult op has arity 4.
if isinstance(mult_arity, int):
self.mult_homo = True # when homo is True, parallelization is possible
else:
self.mult_homo = False # when home if False, for loop is required.
self.mult_arity = mult_arity
width_in = self.width_in
width_out = self.width_out
self.base_fun_name = base_fun
if base_fun == 'silu':
base_fun = torch.nn.SiLU()
elif base_fun == 'identity':
base_fun = torch.nn.Identity()
elif base_fun == 'zero':
base_fun = lambda x: x*0.
self.grid_eps = grid_eps
self.grid_range = grid_range
for l in range(self.depth):
# splines
sp_batch = KANLayer(in_dim=width_in[l], out_dim=width_out[l+1], num=grid, k=k, noise_scale=noise_scale, scale_base_mu=scale_base_mu, scale_base_sigma=scale_base_sigma, scale_sp=1., base_fun=base_fun, grid_eps=grid_eps, grid_range=grid_range, sp_trainable=sp_trainable, sb_trainable=sb_trainable, sparse_init=sparse_init)
self.act_fun.append(sp_batch)
self.node_bias = []
self.node_scale = []
self.subnode_bias = []
self.subnode_scale = []
globals()['self.node_bias_0'] = torch.nn.Parameter(torch.zeros(3,1)).requires_grad_(False)
exec('self.node_bias_0' + " = torch.nn.Parameter(torch.zeros(3,1)).requires_grad_(False)")
for l in range(self.depth):
exec(f'self.node_bias_{l} = torch.nn.Parameter(torch.zeros(width_in[l+1])).requires_grad_(affine_trainable)')
exec(f'self.node_scale_{l} = torch.nn.Parameter(torch.ones(width_in[l+1])).requires_grad_(affine_trainable)')
exec(f'self.subnode_bias_{l} = torch.nn.Parameter(torch.zeros(width_out[l+1])).requires_grad_(affine_trainable)')
exec(f'self.subnode_scale_{l} = torch.nn.Parameter(torch.ones(width_out[l+1])).requires_grad_(affine_trainable)')
exec(f'self.node_bias.append(self.node_bias_{l})')
exec(f'self.node_scale.append(self.node_scale_{l})')
exec(f'self.subnode_bias.append(self.subnode_bias_{l})')
exec(f'self.subnode_scale.append(self.subnode_scale_{l})')
self.act_fun = nn.ModuleList(self.act_fun)
self.grid = grid
self.k = k
self.base_fun = base_fun
### initializing the symbolic front ###
self.symbolic_fun = []
for l in range(self.depth):
sb_batch = Symbolic_KANLayer(in_dim=width_in[l], out_dim=width_out[l+1])
self.symbolic_fun.append(sb_batch)
self.symbolic_fun = nn.ModuleList(self.symbolic_fun)
self.symbolic_enabled = symbolic_enabled
self.affine_trainable = affine_trainable
self.sp_trainable = sp_trainable
self.sb_trainable = sb_trainable
self.save_act = save_act
self.node_scores = None
self.edge_scores = None
self.subnode_scores = None
self.cache_data = None
self.acts = None
self.auto_save = auto_save
self.state_id = 0
self.ckpt_path = ckpt_path
self.round = round
self.device = device
self.to(device)
if auto_save:
if first_init:
if not os.path.exists(ckpt_path):
# Create the directory
os.makedirs(ckpt_path)
print(f"checkpoint directory created: {ckpt_path}")
print('saving model version 0.0')
history_path = self.ckpt_path+'/history.txt'
with open(history_path, 'w') as file:
file.write(f'### Round {self.round} ###' + '\n')
file.write('init => 0.0' + '\n')
self.saveckpt(path=self.ckpt_path+'/'+'0.0')
else:
self.state_id = state_id
self.input_id = torch.arange(self.width_in[0],)
def to(self, device):
'''
move the model to device
Args:
-----
device : str or device
Returns:
--------
self
Example
-------
>>> from kan import *
>>> device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
>>> model = KAN(width=[2,5,1], grid=5, k=3, seed=0)
>>> model.to(device)
'''
super(MultKAN, self).to(device)
self.device = device
for kanlayer in self.act_fun:
kanlayer.to(device)
for symbolic_kanlayer in self.symbolic_fun:
symbolic_kanlayer.to(device)
return self
@property
def width_in(self):
'''
The number of input nodes for each layer
'''
width = self.width
width_in = [width[l][0]+width[l][1] for l in range(len(width))]
return width_in
@property
def width_out(self):
'''
The number of output subnodes for each layer
'''
width = self.width
if self.mult_homo == True:
width_out = [width[l][0]+self.mult_arity*width[l][1] for l in range(len(width))]
else:
width_out = [width[l][0]+int(np.sum(self.mult_arity[l])) for l in range(len(width))]
return width_out
@property
def n_sum(self):
'''
The number of addition nodes for each layer
'''
width = self.width
n_sum = [width[l][0] for l in range(1,len(width)-1)]
return n_sum
@property
def n_mult(self):
'''
The number of multiplication nodes for each layer
'''
width = self.width
n_mult = [width[l][1] for l in range(1,len(width)-1)]
return n_mult
@property
def feature_score(self):
'''
attribution scores for inputs
'''
self.attribute()
if self.node_scores == None:
return None
else:
return self.node_scores[0]
def initialize_from_another_model(self, another_model, x):
'''
initialize from another model of the same width, but their 'grid' parameter can be different.
Note this is equivalent to refine() when we don't want to keep another_model
Args:
-----
another_model : MultKAN
x : 2D torch.float
Returns:
--------
self
Example
-------
>>> from kan import *
>>> model1 = KAN(width=[2,5,1], grid=3)
>>> model2 = KAN(width=[2,5,1], grid=10)
>>> x = torch.rand(100,2)
>>> model2.initialize_from_another_model(model1, x)
'''
another_model(x) # get activations
batch = x.shape[0]
self.initialize_grid_from_another_model(another_model, x)
for l in range(self.depth):
spb = self.act_fun[l]
#spb_parent = another_model.act_fun[l]
# spb = spb_parent
preacts = another_model.spline_preacts[l]
postsplines = another_model.spline_postsplines[l]
self.act_fun[l].coef.data = curve2coef(preacts[:,0,:], postsplines.permute(0,2,1), spb.grid, k=spb.k)
self.act_fun[l].scale_base.data = another_model.act_fun[l].scale_base.data
self.act_fun[l].scale_sp.data = another_model.act_fun[l].scale_sp.data
self.act_fun[l].mask.data = another_model.act_fun[l].mask.data
for l in range(self.depth):
self.node_bias[l].data = another_model.node_bias[l].data
self.node_scale[l].data = another_model.node_scale[l].data
self.subnode_bias[l].data = another_model.subnode_bias[l].data
self.subnode_scale[l].data = another_model.subnode_scale[l].data
for l in range(self.depth):
self.symbolic_fun[l] = another_model.symbolic_fun[l]
return self.to(self.device)
def log_history(self, method_name):
if self.auto_save:
# save to log file
#print(func.__name__)
with open(self.ckpt_path+'/history.txt', 'a') as file:
file.write(str(self.round)+'.'+str(self.state_id)+' => '+ method_name + ' => ' + str(self.round)+'.'+str(self.state_id+1) + '\n')
# update state_id
self.state_id += 1
# save to ckpt
self.saveckpt(path=self.ckpt_path+'/'+str(self.round)+'.'+str(self.state_id))
print('saving model version '+str(self.round)+'.'+str(self.state_id))
def refine(self, new_grid):
'''
grid refinement
Args:
-----
new_grid : init
the number of grid intervals after refinement
Returns:
--------
a refined model : MultKAN
Example
-------
>>> from kan import *
>>> device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
>>> model = KAN(width=[2,5,1], grid=5, k=3, seed=0)
>>> print(model.grid)
>>> x = torch.rand(100,2)
>>> model.get_act(x)
>>> model = model.refine(10)
>>> print(model.grid)
checkpoint directory created: ./model
saving model version 0.0
5
saving model version 0.1
10
'''
model_new = MultKAN(width=self.width,
grid=new_grid,
k=self.k,
mult_arity=self.mult_arity,
base_fun=self.base_fun_name,
symbolic_enabled=self.symbolic_enabled,
affine_trainable=self.affine_trainable,
grid_eps=self.grid_eps,
grid_range=self.grid_range,
sp_trainable=self.sp_trainable,
sb_trainable=self.sb_trainable,
ckpt_path=self.ckpt_path,
auto_save=True,
first_init=False,
state_id=self.state_id,
round=self.round,
device=self.device)
model_new.initialize_from_another_model(self, self.cache_data)
model_new.cache_data = self.cache_data
model_new.grid = new_grid
self.log_history('refine')
model_new.state_id += 1
return model_new.to(self.device)
def saveckpt(self, path='model'):
'''
save the current model to files (configuration file and state file)
Args:
-----
path : str
the path where checkpoints are saved
Returns:
--------
None
Example
-------
>>> from kan import *
>>> device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
>>> model = KAN(width=[2,5,1], grid=5, k=3, seed=0)
>>> model.saveckpt('./mark')
# There will be three files appearing in the current folder: mark_cache_data, mark_config.yml, mark_state
'''
model = self
dic = dict(
width = model.width,
grid = model.grid,
k = model.k,
mult_arity = model.mult_arity,
base_fun_name = model.base_fun_name,
symbolic_enabled = model.symbolic_enabled,
affine_trainable = model.affine_trainable,
grid_eps = model.grid_eps,
grid_range = model.grid_range,
sp_trainable = model.sp_trainable,
sb_trainable = model.sb_trainable,
state_id = model.state_id,
auto_save = model.auto_save,
ckpt_path = model.ckpt_path,
round = model.round,
device = str(model.device)
)
for i in range (model.depth):
dic[f'symbolic.funs_name.{i}'] = model.symbolic_fun[i].funs_name
with open(f'{path}_config.yml', 'w') as outfile:
yaml.dump(dic, outfile, default_flow_style=False)
torch.save(model.state_dict(), f'{path}_state')
torch.save(model.cache_data, f'{path}_cache_data')
@staticmethod
def loadckpt(path='model'):
'''
load checkpoint from path
Args:
-----
path : str
the path where checkpoints are saved
Returns:
--------
MultKAN
Example
-------
>>> from kan import *
>>> model = KAN(width=[2,5,1], grid=5, k=3, seed=0)
>>> model.saveckpt('./mark')
>>> KAN.loadckpt('./mark')
'''
with open(f'{path}_config.yml', 'r') as stream:
config = yaml.safe_load(stream)
state = torch.load(f'{path}_state')
model_load = MultKAN(width=config['width'],
grid=config['grid'],
k=config['k'],
mult_arity = config['mult_arity'],
base_fun=config['base_fun_name'],
symbolic_enabled=config['symbolic_enabled'],
affine_trainable=config['affine_trainable'],
grid_eps=config['grid_eps'],
grid_range=config['grid_range'],
sp_trainable=config['sp_trainable'],
sb_trainable=config['sb_trainable'],
state_id=config['state_id'],
auto_save=config['auto_save'],
first_init=False,
ckpt_path=config['ckpt_path'],
round = config['round']+1,
device = config['device'])
model_load.load_state_dict(state)
model_load.cache_data = torch.load(f'{path}_cache_data')
depth = len(model_load.width) - 1
for l in range(depth):
out_dim = model_load.symbolic_fun[l].out_dim
in_dim = model_load.symbolic_fun[l].in_dim
funs_name = config[f'symbolic.funs_name.{l}']
for j in range(out_dim):
for i in range(in_dim):
fun_name = funs_name[j][i]
model_load.symbolic_fun[l].funs_name[j][i] = fun_name
model_load.symbolic_fun[l].funs[j][i] = SYMBOLIC_LIB[fun_name][0]
model_load.symbolic_fun[l].funs_sympy[j][i] = SYMBOLIC_LIB[fun_name][1]
model_load.symbolic_fun[l].funs_avoid_singularity[j][i] = SYMBOLIC_LIB[fun_name][3]
return model_load
def copy(self):
'''
deepcopy
Args:
-----
path : str
the path where checkpoints are saved
Returns:
--------
MultKAN
Example
-------
>>> from kan import *
>>> model = KAN(width=[1,1], grid=5, k=3, seed=0)
>>> model2 = model.copy()
>>> model2.act_fun[0].coef.data *= 2
>>> print(model2.act_fun[0].coef.data)
>>> print(model.act_fun[0].coef.data)
'''
path='copy_temp'
self.saveckpt(path)
return KAN.loadckpt(path)
def rewind(self, model_id):
'''
rewind to an old version
Args:
-----
model_id : str
in format '{a}.{b}' where a is the round number, b is the version number in that round
Returns:
--------
MultKAN
Example
-------
Please refer to tutorials. API 12: Checkpoint, save & load model
'''
self.round += 1
self.state_id = model_id.split('.')[-1]
history_path = self.ckpt_path+'/history.txt'
with open(history_path, 'a') as file:
file.write(f'### Round {self.round} ###' + '\n')
self.saveckpt(path=self.ckpt_path+'/'+f'{self.round}.{self.state_id}')
print('rewind to model version '+f'{self.round-1}.{self.state_id}'+', renamed as '+f'{self.round}.{self.state_id}')
return MultKAN.loadckpt(path=self.ckpt_path+'/'+str(model_id))
def checkout(self, model_id):
'''
check out an old version
Args:
-----
model_id : str
in format '{a}.{b}' where a is the round number, b is the version number in that round
Returns:
--------
MultKAN
Example
-------
Same use as rewind, although checkout doesn't change states
'''
return MultKAN.loadckpt(path=self.ckpt_path+'/'+str(model_id))
def update_grid_from_samples(self, x):
'''
update grid from samples
Args:
-----
x : 2D torch.tensor
inputs
Returns:
--------
None
Example
-------
>>> from kan import *
>>> model = KAN(width=[1,1], grid=5, k=3, seed=0)
>>> print(model.act_fun[0].grid)
>>> x = torch.linspace(-10,10,steps=101)[:,None]
>>> model.update_grid_from_samples(x)
>>> print(model.act_fun[0].grid)
'''
for l in range(self.depth):
self.get_act(x)
self.act_fun[l].update_grid_from_samples(self.acts[l])
def update_grid(self, x):
'''
call update_grid_from_samples. This seems unnecessary but we retain it for the sake of classes that might inherit from MultKAN
'''
self.update_grid_from_samples(x)
def initialize_grid_from_another_model(self, model, x):
'''
initialize grid from another model
Args:
-----
model : MultKAN
parent model
x : 2D torch.tensor
inputs
Returns:
--------
None
Example
-------
>>> from kan import *
>>> model = KAN(width=[1,1], grid=5, k=3, seed=0)
>>> print(model.act_fun[0].grid)
>>> x = torch.linspace(-10,10,steps=101)[:,None]
>>> model2 = KAN(width=[1,1], grid=10, k=3, seed=0)
>>> model2.initialize_grid_from_another_model(model, x)
>>> print(model2.act_fun[0].grid)
'''
model(x)
for l in range(self.depth):
self.act_fun[l].initialize_grid_from_parent(model.act_fun[l], model.acts[l])
def forward(self, x, singularity_avoiding=False, y_th=10.):
'''
forward pass
Args:
-----
x : 2D torch.tensor
inputs
singularity_avoiding : bool
whether to avoid singularity for the symbolic branch
y_th : float
the threshold for singularity
Returns:
--------
None
Example1
--------
>>> from kan import *
>>> model = KAN(width=[2,5,1], grid=5, k=3, seed=0)
>>> x = torch.rand(100,2)
>>> model(x).shape
Example2
--------
>>> from kan import *
>>> model = KAN(width=[1,1], grid=5, k=3, seed=0)
>>> x = torch.tensor([[1],[-0.01]])
>>> model.fix_symbolic(0,0,0,'log',fit_params_bool=False)
>>> print(model(x))
>>> print(model(x, singularity_avoiding=True))
>>> print(model(x, singularity_avoiding=True, y_th=1.))
'''
x = x[:,self.input_id.long()]
assert x.shape[1] == self.width_in[0]
# cache data
self.cache_data = x
self.acts = [] # shape ([batch, n0], [batch, n1], ..., [batch, n_L])
self.acts_premult = []
self.spline_preacts = []
self.spline_postsplines = []
self.spline_postacts = []
self.acts_scale = []
self.acts_scale_spline = []
self.subnode_actscale = []
self.edge_actscale = []
# self.neurons_scale = []
self.acts.append(x) # acts shape: (batch, width[l])
for l in range(self.depth):
x_numerical, preacts, postacts_numerical, postspline = self.act_fun[l](x)
#print(preacts, postacts_numerical, postspline)
if self.symbolic_enabled == True:
x_symbolic, postacts_symbolic = self.symbolic_fun[l](x, singularity_avoiding=singularity_avoiding, y_th=y_th)
else:
x_symbolic = 0.
postacts_symbolic = 0.
x = x_numerical + x_symbolic
if self.save_act:
# save subnode_scale
self.subnode_actscale.append(torch.std(x, dim=0).detach())
# subnode affine transform
x = self.subnode_scale[l][None,:] * x + self.subnode_bias[l][None,:]
if self.save_act:
postacts = postacts_numerical + postacts_symbolic
# self.neurons_scale.append(torch.mean(torch.abs(x), dim=0))
#grid_reshape = self.act_fun[l].grid.reshape(self.width_out[l + 1], self.width_in[l], -1)
input_range = torch.std(preacts, dim=0) + 0.1
output_range_spline = torch.std(postacts_numerical, dim=0) # for training, only penalize the spline part
output_range = torch.std(postacts, dim=0) # for visualization, include the contribution from both spline + symbolic
# save edge_scale
self.edge_actscale.append(output_range)
self.acts_scale.append((output_range / input_range).detach())
self.acts_scale_spline.append(output_range_spline / input_range)
self.spline_preacts.append(preacts.detach())
self.spline_postacts.append(postacts.detach())
self.spline_postsplines.append(postspline.detach())
self.acts_premult.append(x.detach())
# multiplication
dim_sum = self.width[l+1][0]
dim_mult = self.width[l+1][1]
if self.mult_homo == True:
for i in range(self.mult_arity-1):
if i == 0:
x_mult = x[:,dim_sum::self.mult_arity] * x[:,dim_sum+1::self.mult_arity]
else:
x_mult = x_mult * x[:,dim_sum+i+1::self.mult_arity]
else:
for j in range(dim_mult):
acml_id = dim_sum + np.sum(self.mult_arity[l+1][:j])
for i in range(self.mult_arity[l+1][j]-1):
if i == 0:
x_mult_j = x[:,[acml_id]] * x[:,[acml_id+1]]
else:
x_mult_j = x_mult_j * x[:,[acml_id+i+1]]
if j == 0:
x_mult = x_mult_j
else:
x_mult = torch.cat([x_mult, x_mult_j], dim=1)
if self.width[l+1][1] > 0:
x = torch.cat([x[:,:dim_sum], x_mult], dim=1)
# x = x + self.biases[l].weight
# node affine transform
x = self.node_scale[l][None,:] * x + self.node_bias[l][None,:]
self.acts.append(x.detach())
return x
def set_mode(self, l, i, j, mode, mask_n=None):
if mode == "s":
mask_n = 0.;
mask_s = 1.
elif mode == "n":
mask_n = 1.;
mask_s = 0.
elif mode == "sn" or mode == "ns":
if mask_n == None:
mask_n = 1.
else:
mask_n = mask_n
mask_s = 1.
else:
mask_n = 0.;
mask_s = 0.
self.act_fun[l].mask.data[i][j] = mask_n
self.symbolic_fun[l].mask.data[j,i] = mask_s
def fix_symbolic(self, l, i, j, fun_name, fit_params_bool=True, a_range=(-10, 10), b_range=(-10, 10), verbose=True, random=False, log_history=True):
'''
set (l,i,j) activation to be symbolic (specified by fun_name)
Args:
-----
l : int
layer index
i : int
input neuron index
j : int
output neuron index
fun_name : str
function name
fit_params_bool : bool
obtaining affine parameters through fitting (True) or setting default values (False)
a_range : tuple
sweeping range of a
b_range : tuple
sweeping range of b
verbose : bool
If True, more information is printed.
random : bool
initialize affine parameteres randomly or as [1,0,1,0]
log_history : bool
indicate whether to log history when the function is called
Returns:
--------
None or r2 (coefficient of determination)
Example 1
---------
>>> # when fit_params_bool = False
>>> model = KAN(width=[2,5,1], grid=5, k=3)
>>> model.fix_symbolic(0,1,3,'sin',fit_params_bool=False)
>>> print(model.act_fun[0].mask.reshape(2,5))
>>> print(model.symbolic_fun[0].mask.reshape(2,5))
Example 2
---------
>>> # when fit_params_bool = True
>>> model = KAN(width=[2,5,1], grid=5, k=3, noise_scale=1.)
>>> x = torch.normal(0,1,size=(100,2))
>>> model(x) # obtain activations (otherwise model does not have attributes acts)
>>> model.fix_symbolic(0,1,3,'sin',fit_params_bool=True)
>>> print(model.act_fun[0].mask.reshape(2,5))
>>> print(model.symbolic_fun[0].mask.reshape(2,5))
'''
if not fit_params_bool:
self.symbolic_fun[l].fix_symbolic(i, j, fun_name, verbose=verbose, random=random)
r2 = None
else:
x = self.acts[l][:, i]
mask = self.act_fun[l].mask
y = self.spline_postacts[l][:, j, i]
#y = self.postacts[l][:, j, i]
r2 = self.symbolic_fun[l].fix_symbolic(i, j, fun_name, x, y, a_range=a_range, b_range=b_range, verbose=verbose)
if mask[i,j] == 0:
r2 = - 1e8
self.set_mode(l, i, j, mode="s")
if log_history:
self.log_history('fix_symbolic')
return r2
def unfix_symbolic(self, l, i, j, log_history=True):
'''
unfix the (l,i,j) activation function.
'''
self.set_mode(l, i, j, mode="n")
self.symbolic_fun[l].funs_name[j][i] = "0"
if log_history:
self.log_history('unfix_symbolic')
def unfix_symbolic_all(self, log_history=True):
'''
unfix all activation functions.
'''
for l in range(len(self.width) - 1):
for i in range(self.width_in[l]):
for j in range(self.width_out[l + 1]):
self.unfix_symbolic(l, i, j, log_history)
def get_range(self, l, i, j, verbose=True):
'''
Get the input range and output range of the (l,i,j) activation
Args:
-----
l : int
layer index
i : int
input neuron index
j : int
output neuron index
Returns:
--------
x_min : float
minimum of input
x_max : float
maximum of input
y_min : float
minimum of output
y_max : float
maximum of output
Example
-------
>>> model = KAN(width=[2,3,1], grid=5, k=3, noise_scale=1.)
>>> x = torch.normal(0,1,size=(100,2))
>>> model(x) # do a forward pass to obtain model.acts
>>> model.get_range(0,0,0)
'''
x = self.spline_preacts[l][:, j, i]
y = self.spline_postacts[l][:, j, i]
x_min = torch.min(x).cpu().detach().numpy()
x_max = torch.max(x).cpu().detach().numpy()
y_min = torch.min(y).cpu().detach().numpy()
y_max = torch.max(y).cpu().detach().numpy()
if verbose: