-
Notifications
You must be signed in to change notification settings - Fork 0
/
TAE.py
1572 lines (1449 loc) · 64 KB
/
TAE.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,torchvision
import torch.nn as nn
from torch.nn import functional as F
import functools as ft
import pytorch_lightning as pl
import torch.optim as optim
import numpy as np
import matplotlib.pylab as plt
from itertools import permutations
import random
# import faiss
from pytorch_metric_learning.distances import LpDistance
from torch.distributions import Bernoulli,Normal
import cv2
import io
from PIL import Image
from scipy.interpolate import splprep, splev
from sampler import UNetSampler
from SDE import ScoreNet,marginal_prob_std,diffusion_coeff,Encoder,Decoder,Upsample
import warnings
warnings.filterwarnings("ignore")
def printt(*args):
print('-'*30)
print(args)
print('-'*30)
# Clustering
def zca_whitening_matrix(X):
"""
Function to compute ZCA whitening matrix (aka Mahalanobis whitening).
INPUT: X: [M x N] matrix.
Rows: Variables
Columns: Observations
OUTPUT: ZCAMatrix: [M x M] matrix
"""
# Covariance matrix [column-wise variables]: Sigma = (X-mu)' * (X-mu) / N
sigma = torch.cov(X) # [M x M]
# Singular Value Decomposition. X = U * np.diag(S) * V
U,S,V = torch.svd(sigma)
# U: [M x M] eigenvectors of sigma.
# S: [M x 1] eigenvalues of sigma.
# V: [M x M] transpose of U
# Whitening constant: prevents division by zero
epsilon = 1e-5
# ZCA Whitening matrix: U * Lambda * U'
ZCAMatrix = torch.mm(U, torch.mm(torch.diag(1.0/torch.sqrt(S + epsilon)), U.T)) # [M x M]
return torch.mm(ZCAMatrix, X)
def KMeans(x, K=10, Niter=10, use_zca=False):
"""Implements Lloyd's algorithm for the Euclidean metric."""
N, D = x.shape # Number of samples, dimension of the ambient space
if use_zca: x=zca_whitening_matrix(x)
c = x[:K, :].clone() # Simplistic initialization for the centroids
# K-means loop:
# - x is the (N, D) point cloud,
# - cl is the (N,) vector of class labels
# - c is the (K, D) cloud of cluster centroids
for i in range(Niter):
# E step: assign points to the closest cluster -------------------------
D_ij = ((x.view(N, 1, D) - c.view(1, K, D)) ** 2).sum(-1) # (N, K) symbolic squared distances
cl = D_ij.argmin(dim=1).long().view(-1) # Points -> Nearest cluster
# M step: update the centroids to the normalized cluster average: ------
# Compute the sum of points per cluster:
c.zero_()
c.scatter_add_(0, cl[:, None].repeat(1, D), x)
# Divide by the number of points per cluster:
Ncl = torch.bincount(cl, minlength=K).type_as(c).view(K, 1)
c /= Ncl # in-place division to compute the average
return cl,c
class Kmeans(object):
def __init__(self, k, memlen=30000, emb_dim=256, Niter=10, use_zca=False):
self.k = k
self.memlen=memlen
self.emb_dim=emb_dim
self.KMeans=ft.partial(KMeans,K=k,Niter=Niter,use_zca=use_zca)
self.mem=torch.empty([0,emb_dim])
# self.mem=torch.rand(int(memlen*0.8),emb_dim)
def clustering(self, data, D):
self.mem=self.mem.to(data)
db=torch.cat([data,self.mem])
self.mem=db[:self.memlen]
if db.shape[0]<1000 or len(data)<self.k: return None
# cluster the data
# xb = preprocess_features(db)
# I, loss = run_kmeans(xb, self.k)
I,_=self.KMeans(db)
clusters = [[] for i in range(self.k)]
for i in range(len(data)):
clusters[I[i]].append(i)
# centroids
C=[]
for i in clusters:
if i!=[]: C.append(D[i].mean(0)) # mean code for this class
C=torch.stack(C)
assign=self.get_assignment(C)
S=torch.zeros(D.shape[0]).to(assign[0])
count=0
for i in clusters:
if i!=[]:
S[i]=assign[count]
count+=1
return S
def get_assignment(self,C):
tar=torch.arange(self.k)
tar=nn.functional.one_hot(tar,num_classes=self.k).to(C)
DW=LpDistance(p=1)(C,tar)
rows,cols=DW.shape
assign=[]
for _ in range(rows):
coord=DW.argmin()
row,col=coord//cols,coord%cols
assign.append(col)
DW[row,:]=100
DW[:,col]=100
return assign
class Predicates(nn.Module):
def __init__(self,NP,NK,embed_dim=256,metric='L2',gamma=1,lambda_P=2e-2):
super().__init__()
self.NP=NP
self.NK=NK
self.P=nn.Parameter(torch.randn(NP*NK, embed_dim))
nn.init.kaiming_normal_(self.P)
if metric=='L2': self.metric=LpDistance(p=2)
self.gamma=gamma
self.lambda_P=lambda_P
self.loss_fn=nn.CrossEntropyLoss()
def pred(self,q):
D=self.metric(q,self.P)
p=torch.exp(-self.gamma*D).reshape(-1,self.NP,self.NK)
pred=p.sum(2)
pred=pred/pred.sum(1,keepdim=True)
return pred,D,p
def loss(self,q,c,pred,D):
pnn=self.P[D.argmin(1)]
preg=torch.square(torch.norm(pnn-q,p=2,dim=1)).mean() # L2 dist
loss=self.loss_fn(pred,c)+self.lambda_P*preg
return loss,pred,D
class PAE(nn.Module):
def __init__(self, c_m, mid=128, use_samll=True, use_decoder=False,dropout=0.1):
super().__init__()
self.use_small=use_small
self.use_decoder=use_decoder
if use_small:
self.down=nn.Sequential(
nn.Conv2d(c_m, mid, 3, stride=2),
nn.GroupNorm(32,mid),
nn.SiLU(),
nn.Dropout(0.1),
nn.AdaptiveAvgPool2d(1),
)
else:
self.down1=nn.Sequential(
nn.Conv2d(c_m, mid, 3, stride=2),
nn.GroupNorm(32,mid),
nn.SiLU(),
nn.Dropout(dropout),
)
self.down2=nn.Sequential(
nn.Conv2d(mid, mid, 1, stride=1),
nn.GroupNorm(32,mid),
nn.SiLU(),
nn.Dropout(dropout),
)
self.down3=nn.Sequential(
nn.Conv2d(mid, mid, 3, stride=2),
nn.GroupNorm(32,mid),
nn.SiLU(),
nn.Dropout(dropout),
nn.AdaptiveAvgPool2d(1),
)
if use_decoder:
if use_small:
self.decoder=nn.Sequential(
Upsample(mid, mid, 3, bias=False, scale_factor=1),
nn.GroupNorm(32, mid),
nn.SiLU(),
nn.Dropout(dropout),
Upsample(mid, mid, 3, scale_factor=1),
) if use_small else nn.Sequential(
Upsample(mid, mid, 3, bias=False, scale_factor=2),
nn.GroupNorm(32,mid),
nn.SiLU(),
nn.Dropout(dropout),
Upsample(mid, mid, 1, bias=False, stride=1),
nn.GroupNorm(32,mid),
nn.SiLU(),
nn.Dropout(dropout),
Upsample(mid, mid, 3, scale_factor=1),
)
class PMapper(nn.Module): # m to predicate space
def __init__(self,c_m=1,mid=256,embed_dim=256,NP1=6,NP2=6,NH1=6,NH2=6,NK=2,
dropout=0.1,memlen=30000,threshold=(0.01,0.1),lambda_P=2e-2,
Niter=10, use_zca=False,use_small=True):
super().__init__()
self.mapper=nn.Sequential(
nn.Conv2d(c_m, mid, 3, stride=2),
nn.GroupNorm(32,mid),
nn.SiLU(),
nn.Dropout(0.1),
nn.AdaptiveAvgPool2d(1),
) if use_small else nn.Sequential(
nn.Conv2d(c_m, mid, 3, stride=2),
nn.GroupNorm(32,mid),
nn.SiLU(),
nn.Dropout(dropout),
nn.Conv2d(mid, mid, 1, stride=1),
nn.GroupNorm(32,mid),
nn.SiLU(),
nn.Dropout(dropout),
nn.Conv2d(mid, mid, 3, stride=2),
nn.GroupNorm(32,mid),
nn.SiLU(),
nn.Dropout(dropout),
nn.AdaptiveAvgPool2d(1),
)
self.NP1,self.NP2=NP1,NP2
self.NH1,self.NH2=NH1,NH2
self.Q1=nn.Linear(mid,embed_dim)
self.Q2=nn.Linear(mid,embed_dim)
self.P1=Predicates(NP1,NK,embed_dim,lambda_P=lambda_P)
self.P2=Predicates(NP2,NK,embed_dim,lambda_P=lambda_P)
self.K1=Kmeans(NP1,memlen,embed_dim,Niter,use_zca)
self.K2=Kmeans(NP2,memlen,embed_dim,Niter,use_zca)
if NH1>0 or NH2>0: # HOL predicates, on groups
self.QH1=nn.Linear(mid,embed_dim)
self.QH2=nn.Linear(mid,embed_dim)
self.PH1=Predicates(NH1,NK,embed_dim,lambda_P=lambda_P)
self.PH2=Predicates(NH2,NK,embed_dim,lambda_P=lambda_P)
self.KH1=Kmeans(NH1,memlen,embed_dim,Niter,use_zca)
self.KH2=Kmeans(NH2,memlen,embed_dim,Niter,use_zca)
# self.temperature=embed_dim ** 0.5
self.threshold=threshold
def embed(self,m):
b,N,c,h,w=m.shape
q1=self.Q1(self.mapper(m.reshape([-1,c,h,w]))[:,:,0,0])
mp=m.unsqueeze(1).repeat(1,N,1,1,1,1)+m.unsqueeze(2).repeat(1,1,N,1,1,1)
mp=(mp-nn.ReLU()(mp-1)).reshape(-1,c,h,w) # remove repeat
q2=self.Q2(self.mapper(mp)[:,:,0,0])
return q1,q2
def embedH(self,m):
b,N,c,h,w=m.shape
q1,q2=None,None
if self.NH1>0: q1=self.QH1(self.mapper(m.reshape([-1,c,h,w]))[:,:,0,0])
if self.NH2>0:
mp=m.unsqueeze(1).repeat(1,N,1,1,1,1)+m.unsqueeze(2).repeat(1,1,N,1,1,1)
mp=(mp-nn.ReLU()(mp-1)).reshape(-1,c,h,w) # remove repeat
q2=self.QH2(self.mapper(mp)[:,:,0,0])
return q1,q2
def rel_pred(self,m):
b,N,c,h,w=m.shape
mp=m.unsqueeze(1).repeat(1,N,1,1,1,1)+m.unsqueeze(2).repeat(1,1,N,1,1,1)
mp=(mp-nn.ReLU()(mp-1)).reshape(-1,c,h,w) # remove repeat
q2=self.Q2(self.mapper(mp)[:,:,0,0])
pred2,dist2,p2=self.P2.pred(q2)
return pred2
def forward(self,m,mx=None,loss=False):
b,N,c,h,w=m.shape
q1,q2=self.embed(m)
pred1,dist1,p1=self.P1.pred(q1)
pred2,dist2,p2=self.P2.pred(q2)
p1=p1.reshape(b,N,-1)
pr=p1.matmul(self.P1.P) # p representation
p2m,_=pred2.max(-1)
p2m=p2m.reshape(b,N,N)
# d2d=p2m*(1-torch.eye(N)).unsqueeze(0).to(m) # max as the prob, remvove self
# gr=torch.einsum('ijkpq,iwj->iwkpq',m,d2d) # group representation
gr=torch.einsum('ijkpq,iwj->iwkpq',m,p2m) #gr+m
h1,h2,phr,ghr=None,None,None,None
if self.NH1>0 or self.NH2>0:
gx=nn.Sigmoid()(gr)
h1,h2=self.embedH(gr) # groups
predH1,distH1,pH1=self.PH1.pred(h1)
predH2,distH2,pH2=self.PH2.pred(h2)
pH1=pH1.reshape(b,N,-1)
phr=pH1.matmul(self.PH1.P) # p representation
pH2m,_=predH2.max(-1)
pH2m=pH2m.reshape(b,N,N)
# d2dH=pH2m*(1-torch.eye(N)).unsqueeze(0).to(gm) # max as the prob
# ghr=torch.einsum('ijkpq,iwj->iwkpq',gm,d2dH) # group representation
ghr=torch.einsum('ijkpq,iwj->iwkpq',gr,pH2m) #gr+m
if loss:
with torch.no_grad():
ma=mx.reshape(b*N,-1,h,w).sum([1,2,3])
low,high=self.threshold[0]*h*w*c,self.threshold[1]*h*w*c
mb = torch.logical_and(ma>low,ma<high)
mb1=mb.reshape(b,N).unsqueeze(1).repeat(1,N,1)
mb2=mb.reshape(b,N).unsqueeze(2).repeat(1,1,N)
mbb=torch.logical_and(mb1,mb2).reshape(-1)
ind1 = mb.nonzero().squeeze(1).cpu().detach().tolist()
ind2 = mbb.nonzero().squeeze(1).cpu().detach().tolist()
C1=self.K1.clustering(q1[ind1],pred1[ind1]) # get clusters
if len(ind2)>int(pred2.shape[0]/np.sqrt(2*N)):
ind2=random.sample(ind2,int(pred2.shape[0]/np.sqrt(2*N)))
C2=self.K2.clustering(q2[ind2],pred2[ind2])
loss_cluster=0
if C1 is not None: loss_cluster+=self.P1.loss(q1[ind1],C1,pred1[ind1],dist1[ind1])[0]
if C2 is not None: loss_cluster+=self.P2.loss(q2[ind2],C2,pred2[ind2],dist2[ind2])[0]
if self.NH1>0 or self.NH2>0:
with torch.no_grad():
ga=gx.reshape(b*N,-1,h,w).sum([1,2,3])
low,high=self.threshold[0]*h*w*c,self.threshold[1]*h*w*c*N # higher high
gb = torch.logical_and(ga>low,ga<high)
gb1=mb.reshape(b,N).unsqueeze(1).repeat(1,N,1)
gb2=mb.reshape(b,N).unsqueeze(2).repeat(1,1,N)
gbb=torch.logical_and(gb1,gb2).reshape(-1)
ind1 = gb.nonzero().squeeze(1).cpu().detach().tolist()
ind2 = gbb.nonzero().squeeze(1).cpu().detach().tolist()
CH1,CH2=None,None
if h1 is not None:
CH1=self.KH1.clustering(h1[ind1],predH1[ind1]) # get clusters
if h2 is not None:
if len(ind2)>int(predH2.shape[0]/np.sqrt(2*N)):
ind2=random.sample(ind2,int(predH2.shape[0]/np.sqrt(2*N)))
CH2=self.KH2.clustering(h2[ind2],predH2[ind2])
if CH1 is not None: loss_cluster+=self.PH1.loss(h1[ind1],CH1,predH1[ind1],distH1[ind1])[0]
if CH2 is not None: loss_cluster+=self.PH2.loss(h2[ind2],CH2,predH2[ind2],distH2[ind2])[0]
return loss_cluster
else: return pr,gr,phr,ghr
class RolloutBuffer:
def __init__(self):
self.actions = []
self.states = []
self.next_states = []
self.gts = [] # env
self.ms = [] # env
self.m_in=[]
self.logprobs = []
self.advantages = []
self.is_terminals = []
self.v_targets=[]
def clear(self):
del self.actions[:]
del self.states[:]
del self.next_states[:]
del self.gts[:]
del self.ms[:]
del self.m_in[:]
del self.logprobs[:]
del self.advantages[:]
del self.is_terminals[:]
del self.v_targets[:]
class Sampler(nn.Module): # [x;z]->dz
def __init__(
#region Net arch params
self,
c_in,
c_m,
dim=32,
embed_dim=128,
sigma=5, # the larger the more spread out
K=6, # diffusion steps
eps=1e-5, # A tolerance value for numerical stability.
method='EM', # ODE VAE PC
snr=0.16,
t=500, # temprature of step size
mapper_mid=256, # mapper mid dim
NP1=6,
NP2=4,
NH1=4,
NH2=4,
NK=2,
lambda_P=2e-2,
dropout=0.1,
memlen=30000,
threshold=(0.01,0.1),
use_out_res=True,
use_small=True,
Niter=10,
use_zca=False,
use_ldm=False,
ldm_out=8,
ldm_ds=[1,2,1,1],
mapper_small=False,
# Attn
use_attn=False,
use_self_attn=False,
n_heads=8,
d_head=16,
context_dim=256,
share_mapper=False,
#endregion
# RL
use_rl=False,
critic_mid=128,
**kwargs,
):
super().__init__()
self.c_in=c_in
self.c_m=c_m
self.K=K
self.t=t
self.marginal_prob_std_fn = ft.partial(marginal_prob_std, sigma=sigma)
self.diffusion_coeff_fn = ft.partial(diffusion_coeff, sigma=sigma)
self.use_t=method not in ['VAE']
mapper_dim=ldm_out if use_ldm else c_m
self.mapper=PMapper(mapper_dim,mapper_mid,embed_dim,NP1,NP2,NH1,NH2,NK,dropout,memlen,threshold,lambda_P,Niter,use_zca,mapper_small) # share mapper for each layer
model=ScoreNet if use_small else UNetSampler
mapper=self.mapper.mapper if share_mapper else None
self.use_ldm=use_ldm
mul=4 if NH2>0 else 3
in_channels=c_in+c_m*mul
out_channels=c_m
if use_ldm:
self.ldm_out=ldm_out
self.encoder=Encoder(c_in=c_in,dim=dim,dropout=dropout,use_attn=use_attn,n_heads=n_heads,d_head=d_head,ds=ldm_ds)
self.decoder=Decoder(in_channels=ldm_out,c_out=out_channels,dim=dim,use_attn=use_attn,n_heads=n_heads,dropout=dropout,d_head=d_head,sf=ldm_ds[::-1])
in_channels,out_channels=dim+ldm_out*mul,ldm_out
self.net=model(self.marginal_prob_std_fn,in_channels,out_channels, dropout=dropout,use_t=self.use_t,
dim=dim,embed_dim=embed_dim,use_out_res=use_out_res,use_attn=use_attn,use_self_attn=use_self_attn,
n_heads=n_heads,d_head=d_head,context_dim=context_dim,mapper=mapper,use_ac=use_rl,mid=critic_mid) # Actor
self.use_rl=use_rl
if use_rl: self.buffer=RolloutBuffer()
self.eps=eps
self.snr=snr
self.method=method
def get_input(self,x,m,N,context):
b,c,h,w=x.shape
c_m=self.ldm_out if self.use_ldm else self.c_m
mcs=m.reshape(-1,1,N,c_m,h,w).repeat(1,N,1,1,1,1) # for each, we get its competetors representation, or only within the class
mask=1-torch.eye(N).unsqueeze(0).unsqueeze(3).repeat(1,1,1,c_m*h*w).to(x.device)
mcm=(mask*mcs.reshape(-1,N,N,c_m*h*w)).reshape(-1,N,c_m,h,w) # competetors
mc=mcm.reshape(b,N,-1).sum(1).reshape(-1,c_m,h,w) # compatitors map
pr,gr,phr,ghr=self.mapper(m.reshape(-1,N,c_m,h,w)) # d1 d2 clustering
mg=gr.reshape(-1,c_m,h,w)
context=context+pr.reshape(b,-1)
if phr is not None: context=context+phr.reshape(b,-1)
if ghr is not None:
mgh=ghr.reshape(-1,c_m,h,w)
inp=torch.cat([x,m,mc,mg,mgh],dim=1)
else: inp=torch.cat([x,m,mc,mg],dim=1)
return inp, context, mcm
def scoring(self,x,m,N,context,t=None,hs=None,m_=None):
inp, context, mcm = self.get_input(x,m,N,context) # use current state
hs=[h.detach() for h in hs] if hs is not None else None
state=[x.detach(), m.detach(), inp.detach(), context.detach(), mcm.detach(), t, hs]
return self.net(inp, context, t, mcm), state # current state
@torch.no_grad()
def get_state(self,x,m,N,context,t=None, hs=None):
inp, context, mcm = self.get_input(x,m,N,context)
return [x, m, inp, context, mcm,t, hs]
def sample_action(self, m):
mx=nn.Sigmoid()(m)
dist = Bernoulli(mx) # For c_m>1, categorical
action = dist.sample()
entropy=dist.entropy()
action_logprob = dist.log_prob(action)
return action,action_logprob,entropy
def actor(self,state, N):
x, m, inp, context, mcm, t, hs = state
m, state=self.scoring(x,m,N,context,t)
if self.use_ldm: m=self.decoder(m,hs[0],hs[1],hs[2])
return m
def critic(self,state):
x, m, inp, context, mcm, t, hs = state
return self.net.critic(inp,context,t,mcm)
def rel_pred(self,m):return self.mapper.rel_pred(m)
def forward(self,x,context,N,gt=None):
hs=None
if self.use_ldm:
x,h1,h2,h3=self.encoder(x)
hs=[h1,h2,h3]
if self.method in ['EM','ODE','PC','DDPM']: ms,ss,ts=self.sde(x,context,N,gt,hs)
elif self.method in ['VAE']: ms,ss,ts=self.vae(x,context,N,gt,hs)
else: raise
m_l=ms[-1]
m_d=self.decoder(m_l,h1,h2,h3) if self.use_ldm else m_l
return m_d,ss,ts,m_l
def vae(self,x,context,N,gt=None,hs=None):
b,c,h,w=x.shape
time_steps = torch.linspace(1., self.eps, 2).to(x.device)
c_m=self.ldm_out if self.use_ldm else self.c_m
m_init=torch.rand(b,c_m,h,w).to(x.device)*self.marginal_prob_std_fn(time_steps[0],x)#[:, None, None, None]
m, state=self.scoring(x,m_init,N,context,hs=hs)
if self.use_rl and self.training:
assert gt is not None
with torch.no_grad():
next_state=self.get_state(x,m,N,context,hs=hs)
self.buffer.states.append(state)
self.buffer.next_states.append(next_state)
self.buffer.gts.append(gt)
m_a=m
if self.use_ldm: m_a=self.decoder(m_a,hs[0],hs[1],hs[2])
m_in=torch.rand_like(m_a).to(x.device) * self.marginal_prob_std_fn(time_steps[0],x) if self.use_ldm else m_init
self.buffer.m_in.append(m_in)
self.buffer.ms.append(m_a)
action,action_logprob,entropy=self.sample_action(m_a)
self.buffer.actions.append(action)
self.buffer.logprobs.append(action_logprob)
self.buffer.is_terminals.append(1)
return [m], None, None
def sde(self,x,context,N,gt=None,hs=None):
b,c,h,w=x.shape
time_steps = torch.linspace(1., self.eps, self.K+2).to(x.device)
c_m=self.ldm_out if self.use_ldm else self.c_m
m=torch.rand(b,c_m,h,w).to(x.device) * self.marginal_prob_std_fn(time_steps[0],x)#[:, None, None, None]
m_init=m
m_in=None
step_size = (time_steps[0] - time_steps[1])*self.K/self.t
ms,ss,ts=[],[],[]
m_=None
for i, time_step in enumerate(time_steps[1:-1]):
batch_time_step = torch.ones(b).to(x.device) * time_step
ts.append(batch_time_step)
grad, state=self.scoring(x, m, N, context, batch_time_step, hs, m_=m_)
m_=state[1]
ss.append(grad)
if self.method=='DDPM':
mean_m=grad
m=mean_m
else:
g = self.diffusion_coeff_fn(batch_time_step, x)
if self.method=='PC':
# Corrector step (Langevin MCMC)
grad_norm = torch.norm(grad.reshape(grad.shape[0], -1), dim=-1).mean()
noise_norm = np.sqrt(np.prod(m.shape[1:]))
langevin_step_size = 2 * (self.snr * noise_norm / grad_norm)**2
m = m + langevin_step_size * grad + torch.sqrt(2 * langevin_step_size) * torch.randn_like(m)
mean_m = m + (g**2)[:, None, None, None] * grad * step_size
if self.method in ['EM','PC']:
m = mean_m + torch.sqrt(step_size) * g[:, None, None, None] * torch.randn_like(m)
elif self.method=='ODE': m = mean_m
ms.append(mean_m)
if self.use_rl and self.training:
assert gt is not None
with torch.no_grad():
next_time_step = torch.ones(b).to(x.device) * time_steps[1:][i+1]
next_state=self.get_state(x,mean_m,N,context,next_time_step,hs)
self.buffer.states.append(state)
self.buffer.next_states.append(next_state)
self.buffer.gts.append(gt)
m_a=mean_m
if self.use_ldm: m_a=self.decoder(m_a,hs[0],hs[1],hs[2])
self.buffer.ms.append(m_a)
if m_in is None: m_in=torch.rand_like(m_a).to(x.device) * self.marginal_prob_std_fn(time_steps[0],x) if self.use_ldm else m_init
self.buffer.m_in.append(m_in)
m_in=m_a
action,action_logprob,entropy=self.sample_action(m_a)
self.buffer.actions.append(action)
self.buffer.logprobs.append(action_logprob)
self.buffer.is_terminals.append(1 if i==len(time_steps[1:-1])-1 else 0)
return ms,torch.cat(ss),torch.cat(ts)
def loss_fn(self, ss, ts):
"""The loss function for training score-based generative models.
Args:
model: A PyTorch model instance that represents a
time-dependent score-based model.
x: A mini-batch of training data.
marginal_prob_std: A function that gives the standard deviation of
the perturbation kernel.
eps: A tolerance value for numerical stability.
"""
z = torch.rand_like(ss).to(ss)
std = self.marginal_prob_std_fn(ts,z)
loss = torch.mean(torch.sum((ss * std[:, None, None, None] + z)**2, dim=(1,2,3)))
return loss
def focal_loss(
inputs: torch.Tensor,
targets: torch.Tensor,
alpha: float = 0.25,
gamma: float = 2,
reduction: str = "none",
) -> torch.Tensor:
p = inputs
ce_loss = F.binary_cross_entropy(inputs, targets, reduction="none")
p_t = p * targets + (1 - p) * (1 - targets)
loss = ce_loss * ((1 - p_t) ** gamma)
if alpha >= 0:
alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
loss = alpha_t * loss
# Check reduction option and return loss accordingly
if reduction == "none":
pass
elif reduction == "mean":
loss = loss.mean()
elif reduction == "sum":
loss = loss.sum()
else:
raise ValueError(
f"Invalid Value for arg 'reduction': '{reduction} \n Supported reduction modes: 'none', 'mean', 'sum'"
)
return loss
class FocalLossCE(nn.Module):
""" Focal Loss, as described in https://arxiv.org/abs/1708.02002.
It is essentially an enhancement to cross entropy loss and is
useful for classification tasks when there is a large class imbalance.
x is expected to contain raw, unnormalized scores for each class.
y is expected to contain class labels.
Shape:
- x: (batch_size, C) or (batch_size, C, d1, d2, ..., dK), K > 0.
- y: (batch_size,) or (batch_size, d1, d2, ..., dK), K > 0.
"""
def __init__(self,
alpha = None,
gamma: float = 0.,
reduction: str = 'mean',
ignore_index: int = -100):
"""Constructor.
Args:
alpha (Tensor, optional): Weights for each class. Defaults to None.
gamma (float, optional): A constant, as described in the paper.
Defaults to 0.
reduction (str, optional): 'mean', 'sum' or 'none'.
Defaults to 'mean'.
ignore_index (int, optional): class label to ignore.
Defaults to -100.
"""
if reduction not in ('mean', 'sum', 'none'):
raise ValueError(
'Reduction must be one of: "mean", "sum", "none".')
super().__init__()
self.alpha = alpha
self.gamma = gamma
self.ignore_index = ignore_index
self.reduction = reduction
self.nll_loss = nn.NLLLoss(
weight=alpha, reduction='none', ignore_index=ignore_index)
def __repr__(self):
arg_keys = ['alpha', 'gamma', 'ignore_index', 'reduction']
arg_vals = [self.__dict__[k] for k in arg_keys]
arg_strs = [f'{k}={v!r}' for k, v in zip(arg_keys, arg_vals)]
arg_str = ', '.join(arg_strs)
return f'{type(self).__name__}({arg_str})'
def forward(self, x, y):
if x.ndim > 2:
# (N, C, d1, d2, ..., dK) --> (N * d1 * ... * dK, C)
c = x.shape[1]
x = x.permute(0, *range(2, x.ndim), 1).reshape(-1, c)
# (N, d1, d2, ..., dK) --> (N * d1 * ... * dK,)
y = y.view(-1)
unignored_mask = y != self.ignore_index
y = y[unignored_mask]
if len(y) == 0:
return torch.tensor(0.)
x = x[unignored_mask]
# compute weighted cross entropy term: -alpha * log(pt)
# (alpha is already part of self.nll_loss)
log_p = F.log_softmax(x, dim=-1)
ce = self.nll_loss(log_p, y)
# get true class column from each row
all_rows = torch.arange(len(x))
log_pt = log_p[all_rows, y]
# compute focal term: (1 - pt)^gamma
pt = log_pt.exp()
focal_term = (1 - pt)**self.gamma
# the full loss: -alpha * ((1 - pt)^gamma) * log(pt)
loss = focal_term * ce
if self.reduction == 'mean':
loss = loss.mean()
elif self.reduction == 'sum':
loss = loss.sum()
return loss
def focal_loss_ce(alpha = None,
gamma: float = 0.,
reduction: str = 'mean',
ignore_index: int = -100,
device='cpu',
dtype=torch.float32):
"""Factory function for FocalLoss.
Args:
alpha (Sequence, optional): Weights for each class. Will be converted
to a Tensor if not None. Defaults to None.
gamma (float, optional): A constant, as described in the paper.
Defaults to 0.
reduction (str, optional): 'mean', 'sum' or 'none'.
Defaults to 'mean'.
ignore_index (int, optional): class label to ignore.
Defaults to -100.
device (str, optional): Device to move alpha to. Defaults to 'cpu'.
dtype (torch.dtype, optional): dtype to cast alpha to.
Defaults to torch.float32.
Returns:
A FocalLoss object
"""
if alpha is not None:
if not isinstance(alpha, torch.Tensor):
alpha = torch.tensor(alpha)
alpha = alpha.to(device=device, dtype=dtype)
fl = FocalLossCE(
alpha=alpha,
gamma=gamma,
reduction=reduction,
ignore_index=ignore_index)
return fl
class SoftDiceLoss(nn.Module):
'''
soft-dice loss, useful in binary segmentation
'''
def __init__(self,
p=1,
smooth=1):
super(SoftDiceLoss, self).__init__()
self.p = p
self.smooth = smooth
def forward(self, logits, labels):
'''
inputs:
logits: tensor of shape (N, H, W, ...)
label: tensor of shape(N, H, W, ...)
output:
loss: tensor of shape(N, )
'''
N=logits.shape[0]
probs = torch.sigmoid(logits)
numer = (probs * labels).reshape(N,-1).sum(1)
denor = (probs.pow(self.p) + labels.pow(self.p)).reshape(N,-1).sum(1)
loss = 1. - (2 * numer + self.smooth) / (denor + self.smooth)
return loss
def blur(x,sigma=2):
if sigma==0: return x
GB=torchvision.transforms.GaussianBlur(3,sigma)
x=GB(x)*9
return x-nn.ReLU()(x-1)
def masking(x,ds=4,p=0.8):
b,c,h,w=x.shape
m=(torch.FloatTensor(b,1,h//ds, w//ds).uniform_() > p).to(x)
return m.unsqueeze(3).unsqueeze(5).repeat(1,1,1,ds,1,ds).reshape(b,1,h,w)
def softjump(x,alpha=25,shift=0.2,smooth=False): # scale up penalty above threshold
if smooth:
x_=alpha*nn.ReLU()(x-shift)
xi=-100*nn.ReLU()(0.1-x_)
x_=x_+xi
xj=torch.exp(x_)/(1+torch.exp(x_))
xnj=nn.ReLU()(shift-x)
xnj=nn.ReLU()(shift-xnj)
return xj*(1-shift)+xnj
else:
x=alpha*(x-shift)
return torch.exp(x)/(1+torch.exp(x))
class TAE(nn.Module):
def __init__(
self,
sampler,
N=8,
embed_dim=256,
c_m=1, # channel of mask
alpha_overlap=0.1, # overlap
alpha_l2=0.2, # l2 to control m scale
alpha_resources=0.1, # resources for sparse m
focal_alpha=0.75, # focal loss alpha
jump_alpha=None, # alpha for soft jump
jump_shift=0.2, # shift of jump
jump_smooth=False,
blur_sigma=2, # sigma for blurring overlap
quota=8, # quota for each player
beta=1.0, # sde overall
gamma_cluster=1.0, # clustering overall
lambda_r=0.1, # lambda for rel pred
mask_p=0.8, # rand mask ratio
mask_ds=4, # mask downsample ratio, i.e. chunk size 28/ds
cluster_start_epoch=20,
PE_mode='rand', # rand fix none
loss_option='focal_1.0-dice_1.0', # e.g. focal_1.0-dice_1.0-bce_0.1-smoothl1_1.0:b mse
use_ldm=False,
# rl settings
use_rl=False,
rl_start_epoch=50,
ppo_gamma=0.95,
ppo_lamda=0.95,
ppo_epsilon=1.0,
ppo_entropy_coef=0.2,
ppo_K_epochs=3,
ppo_use_grad_clip=True,
ppo_use_lr_decay=False,
ppo_reward_norm=True,
ppo_inc_reward=True,
ppo_human_tune=False,
ppo_sparse_reward=False,
ppo_prefer_last=False,
ppo_max_train_steps=1e6,
ppo_update_every=5,
reward_option='loss_1.0-prefer_1.0', # e.g. loss_1.0-preference_1.0, predict minus loss and human preference
prefer_option='ct_1.0-cp_1.0-sm_1.0-z_0.0:spl', # continous, compactness, smoothness, base score
lr_a=1e-3,
lr_c=1e-3,
**kwargs
):
super().__init__()
self.sampler=sampler
self.alpha_overlap=alpha_overlap
self.alpha_l2=alpha_l2
self.lambda_r=lambda_r
self.alpha_resources=alpha_resources
self.focal_alpha=focal_alpha
self.softjump=None if jump_alpha is None else ft.partial(softjump,alpha=jump_alpha,shift=jump_shift,smooth=jump_smooth)
self.blur=ft.partial(blur,sigma=blur_sigma) if blur_sigma>0 else None
self.quota=quota
self.beta=beta
self.gamma_cluster=gamma_cluster
self.c_m=c_m
self.c_in=sampler.c_in
self.N=N
self.embed_dim=embed_dim
self.act=nn.Softmax(1) if c_m>1 else nn.Sigmoid()
self.mask_p=mask_p
self.mask_ds=mask_ds
self.cluster_start_epoch=cluster_start_epoch
self.PE_mode=PE_mode
self.loss_option=loss_option
loss_option=self.loss_option.split(':')[0].split('-')
self.loss_dict={}
for i in loss_option: self.loss_dict[i.split('_')[0]]=float(i.split('_')[1])
if PE_mode!='none': self.posemb=nn.Embedding(256,embed_dim) # ids, should be far enough
self.use_ldm=use_ldm
self.use_rl=use_rl
self.rl_start_epoch=rl_start_epoch
if use_rl:
self.ppo_gamma=ppo_gamma
self.ppo_lamda=ppo_lamda
self.ppo_epsilon=ppo_epsilon
self.ppo_entropy_coef=ppo_entropy_coef
self.ppo_K_epochs=ppo_K_epochs
self.ppo_use_grad_clip=ppo_use_grad_clip
self.ppo_reward_norm=ppo_reward_norm
self.ppo_inc_reward=ppo_inc_reward
self.ppo_use_lr_decay=ppo_use_lr_decay
self.ppo_max_train_steps=ppo_max_train_steps
self.ppo_update_every=ppo_update_every
self.ppo_sparse_reward=ppo_sparse_reward
self.ppo_human_tune=ppo_human_tune
self.ppo_prefer_last=ppo_prefer_last
actor_params=get_params_exclude(self.sampler,self.sampler.net.critic_head)
critic_params=get_params_exclude(self.sampler,self.sampler.net.actor_head)
self.optimizer_actor = torch.optim.Adam(actor_params, lr=lr_a, eps=1e-5)
self.optimizer_critic = torch.optim.Adam(critic_params, lr=lr_c, eps=1e-5)
self.reward_option=reward_option
reward_option=self.reward_option.split(':')[0].split('-')
self.reward_dict={}
for i in reward_option: self.reward_dict[i.split('_')[0]]=float(i.split('_')[1])
self.prefer_option=prefer_option
self.prefer_dict=[float(i.split('_')[1]) for i in prefer_option.split(':')[0].split('-')]
def forward(self,x,gt=None,ret_all=False): # x is image BCHW
x=x.to(device=x.device, dtype=torch.float)
x=x[:,:self.c_in]
b,c,h,w=x.shape
if self.PE_mode=='none': PE=0
else:
if self.PE_mode=='fix':
pos=torch.range(0,self.N-1).reshape(1,-1).repeat(b,1).reshape(-1,1)
elif self.PE_mode=='rand':
pos=torch.randint(0,256,[b*self.N,1]) # randomly assign player id
PE=self.posemb(pos.long().to(x.device)).squeeze(1)
X=x.unsqueeze(1).repeat(1,self.N,1,1,1).reshape(-1,c,h,w) # each batch copy x
if self.mask_p>0: X=X*masking(X,p=self.mask_p,ds=self.mask_ds)
if gt is not None:
if len(gt.shape)==4: GT=gt.unsqueeze(1).repeat(1,self.N,1,1,1).reshape(-1,c,h,w)
else: GT=gt.unsqueeze(1).repeat(1,self.N,1,1).reshape(-1,h,w)
else: GT=None
m,ss,ts,m_l=self.sampler(X,PE,self.N,GT)
if ret_all: return m,ss,ts,m_l
return m
def relpred(self,m): return self.sampler.rel_pred(m)
def loss_tae(self,m,gt,log=None):
B,c_m,h,w=m.shape
b=B//self.N
mx=self.act(m)
if self.c_m>1: # TODO: need a lot update
rx=mx.reshape(b,-1,self.c_m,h,w).sum([1]) # each one has independent prediction, together make good, allow empty
loss_fn=nn.CrossEntropyLoss(weight=torch.tensor([0.1]+[0.7]*(self.c_m-1)).to(x.device))
r=(self.act(rx)).argmax(1).to(x.device)
bm=self.blur(m) if self.blur is not None else m
bmstack=nn.Softmax(2)(bm.reshape(b,-1,self.c_m,h,w))[:,:,1:].sum([1,2]) # sum of non-zero parts
mxs=nn.ReLU()(mx[:,1:].reshape(b,-1,h,w).sum([2,3])-self.quota).sum(1).mean()
loss_reconstruct=loss_fn(rx,gt)
else:
mstack=mx.reshape(b,-1,1,h,w).sum([1]).squeeze(1)
bmx=self.softjump(mx) if self.softjump is not None else mx
bmx=self.blur(bmx) if self.blur is not None else bmx
bmstack=bmx.reshape(b,-1,1,h,w).sum([1]).squeeze(1)
rx=mstack-nn.ReLU()(mstack-1); r=rx # all agreed parts to 1
mxs=nn.ReLU()(mx.reshape(b,-1,h,w).sum([2,3])-self.quota).sum(1).mean() # exceed resources used for each
loss_reconstruct=0
for i in self.loss_dict:
if i=='focal': loss_i=focal_loss(rx,gt,alpha=self.focal_alpha).mean()*self.loss_dict[i]
elif i=='smoothl1': loss_i=nn.SmoothL1Loss()(rx,gt).mean()*self.loss_dict[i]
elif i=='dice': loss_i=SoftDiceLoss()(rx,gt).mean()*self.loss_dict[i]
elif i=='bce': loss_i=nn.BCELoss()(rx,gt).mean()*self.loss_dict[i]
elif i=='mse': loss_i=nn.MSELoss()(rx,gt).mean()*self.loss_dict[i]
log.update({i:loss_i})
loss_reconstruct+=loss_i
loss_overlap=self.alpha_overlap*nn.ReLU()(bmstack-1).sum([1,2]).mean() # minimize blured overlap predicate-wise, avoid repeating
loss_tae_l2=self.alpha_l2*(m**2).mean() if self.alpha_l2!=0 else 0
loss_tae_resources=self.alpha_resources*mxs.mean() if self.alpha_resources!=0 else 0
loss_tae=loss_reconstruct+loss_overlap+loss_tae_l2+loss_tae_resources
if log is not None: log.update({'loss_reconstruct':loss_reconstruct,'loss_overlap':loss_overlap,
'loss_tae_resources':loss_tae_resources,'loss_tae_l2':loss_tae_l2})
return loss_tae,log,r,rx
def loss(self,x,y,epoch=None): # step*batchsize
x,y=x[:,:self.c_in],y[:,:self.c_in]
if self.c_in>1: #TODO need update
gt=(y.argmax(1)>0).float().to(x.device) if self.c_m==1 else y.argmax(1)
else:
if 'b' in self.loss_option.split(':'): gt=(y>0).squeeze(1).float().to(x.device)
else: gt=y.squeeze(1).float().to(x.device)
m,ss,ts,m_l=self(x,gt=gt,ret_all=True)
mx=self.act(m)
log={}
loss=0
#--- reconstruct ---
loss_tae,log,r,rx=self.loss_tae(m,gt,log)
loss+=loss_tae
#--- clustering ---
if self.gamma_cluster>0 and epoch is not None and epoch>=self.cluster_start_epoch:
B,c_m,h_m,w_m=m_l.shape
loss_cluster=self.sampler.mapper(m_l.reshape(-1,self.N,c_m,h_m,w_m),mx,loss=True)*self.gamma_cluster
loss+=loss_cluster
log.update({'loss_cluster':loss_cluster})
# loss SDE
if self.beta>0 and self.sampler.use_t:
loss_sde=self.sampler.loss_fn(ss,ts)*self.beta
loss+=loss_sde
log.update({'loss_sde':loss_sde})
union=r+gt
union=torch.where(union>1,1,union)
iou=(r*gt).sum()/union.sum()
mae=nn.L1Loss()(rx,gt).mean()
log.update({'loss':loss,'iou':iou,'mae':mae})
return loss,log,[mx,rx,gt]
def parse(self,x,gt,o_only=False):
o,_,_,o_l=self(x,gt=gt,ret_all=True)
r=None
if not o_only:
if self.use_ldm:
B,c,h,w=o_l.shape
r=self.relpred(o_l.reshape(-1,self.N,c,h,w))
else:
B,c,h,w=o.shape