src/baselines/lri_bern.py SHA256 43afe5a02234f63e7e8314d5af99328ceafaca495eec23d80528845f4e1ca82d
1: import torch
2: import torch.nn as nn
3: from torch_scatter import scatter
4: import numpy as np
5: 
6: from torchPHext.torchex_PHext import pershom as pershom_ext
7: # ph_extended_link_tree = pershom_ext.pershom_backend.__C.VertExtendedFiltCompCuda_link_cut_tree__extended_persistence_batch
8: ph_extended_link_tree_cyclereps= pershom_ext.pershom_backend.__C.VertExtendedFiltCompCuda_link_cut_tree_cyclereps__extended_persistence_batch
9: 
10: from utils import PershomReadout, GaussianMixtureModel
11: 
12: 
13: class LRIBern(nn.Module):
14: 
15:     def __init__(self, clf, extractor, criterion, config):
16:         super().__init__()
17:         self.clf = clf
18:         self.extractor = extractor
19:         self.criterion = criterion
20:         self.device = next(self.parameters()).device
21: 
22:         self.pred_loss_coef = config['pred_loss_coef']
23:         self.info_loss_coef = config['info_loss_coef']
24:         self.temperature = config['temperature']
25: 
26:         # self.final_r = config['final_r']
27:         self.decay_interval = config['decay_interval']
28:         self.decay_r = config['decay_r']
29:         self.init_r = config['init_r']
30: 
31:         self.attn_constraint = config['attn_constraint']
32: 
33:         ## for gaus
34:         self.gaus = GaussianMixtureModel()
35: 
36:         ## for ph
37:         self.readout = PershomReadout(
38:             # dataset,
39:             num_struct_elements=16,
40:             # cls_hidden_dimension=cls_hidden_dimension,
41:             # drop_out=drop_out
42:         ).to(self.device)
43:  
44:     def compute_extended_ph_link_tree_wcyclereps(self,node_filt, batch, device):
45:         ph_input= []
46:         for idx, (i, j, e) in enumerate(zip(batch.sample_pos[:-1], batch.sample_pos[1:], batch.boundary_up)):
47:             v = node_filt[i:j]# extract vertex values
48:             v = v.squeeze()
49:             v = v.cpu()
50:             v = 1 - v   ## Upper Filtration || Lower Filtration
51:             e = e.cpu()
52:             ph_input.append((v, [e]))
53:         # ph_input needs to be: (v,[e])
54:         out= ph_extended_link_tree_cyclereps(ph_input)
55:         pers= [per[0] for per in out]
56:         cycle_reps = [cycles[1] for cycles in out]
57: 
58:         h_0_up= [torch.stack([x.to(device) for x in g[0]]) for g in pers]
59:         h_0_down= [torch.stack([x.to(device) for x in g[1]]) for g in pers]
60:         h_0_extplus= [torch.stack([x.to(device) for x in g[2]]) for g in pers]
61:         h_1_extminus= [torch.stack([x.to(device) for x in g[3]]) for g in pers]
62:         cycle_reps= [[torch.stack([x.to(device).unsqueeze(0) for x in c]) for c in cycle] for cycle in cycle_reps]  
63: 
64:         return h_0_up, h_0_down, h_0_extplus, h_1_extminus, cycle_reps
65: 
66:     def __loss__(self, ver_attn, edge_attn, cell_attn, clf_logits, clf_labels, epoch, warmup, tpl, gas):
67:         pred_loss = self.criterion(clf_logits, clf_labels.float().view(clf_logits.shape))          
68:         if warmup:
69:             return pred_loss, {'loss': pred_loss.item(), 'pred': pred_loss.item()}
70: 
71:         # r_0 = self.get_r(epoch, 0.7)
72:         # r_1 = self.get_r(epoch, 0.7)
73:         # r_2 = self.get_r(epoch, 0.7)
74:         # v_info_loss = (ver_attn * torch.log(ver_attn/r_0 + 1e-6) + (1 - ver_attn) * torch.log((1 - ver_attn)/(1 - r_0 + 1e-6) + 1e-6)).mean()
75: 
76:         pred_loss = self.pred_loss_coef * pred_loss
77:         info_loss =  0#self.info_loss_coef * e_info_loss + self.info_loss_coef * c_info_loss + self.info_loss_coef * v_info_loss
78: 
79:         loss = pred_loss + info_loss + 0.01*tpl + 0.1*gas
80:         loss_dict = {'loss': loss.item(), 'pred': pred_loss.item(), 'v_info': 0, 'gas': gas.item(),'c_info': 0, 'tpl':tpl}
81:         return loss, loss_dict
82: 
83:     def forward_pass(self, data, epoch, warmup, do_sampling):
84:         if warmup:
85:             clf_logits = self.clf(data)
86:             loss, loss_dict = self.__loss__(None, None, None, clf_logits, data.y, epoch, warmup, None)
87:             return loss, loss_dict, clf_logits, None, None, None, None
88: 
89:         emb, graph_x = self.clf.get_emb(data)
90:         cell_attn_log_logits = self.extractor(emb)
91: 
92:         ## obtain all the adjacency matrices
93:         params = data.get_all_cochain_params(max_dim=2, include_down_features=True)
94:         v_index = [None, params[0].up_index, None]        
95:         e_index = [params[1].boundary_index, params[1].up_index, params[1].down_index]
96:         c_index = [params[2].boundary_index, None, params[2].down_index]
97: 
98:         # if self.attn_constraint == 'smooth_min':
99:         #     node_attn_log_logits = scatter(node_attn_log_logits[edge_index[1]].reshape(-1), edge_index[0], reduce='min').reshape(-1, 1)
100:         #     node_attn_log_logits = scatter(node_attn_log_logits[edge_index[1]].reshape(-1), edge_index[0], reduce='min').reshape(-1, 1)
101:         # else:
102:         #     assert self.attn_constraint == 'none'
103: 
104:         ver_attn = self.sampling(cell_attn_log_logits[0], do_sampling)
105:         edge_attn = self.sampling(cell_attn_log_logits[1], do_sampling)
106:         cell_attn = self.sampling(cell_attn_log_logits[2], do_sampling)
107: 
108:         ## norm
109:         ver_attn = self.min_max_normalize(ver_attn)
110:         edge_attn = self.min_max_normalize(edge_attn)
111:         cell_attn = torch.ones_like(cell_attn, dtype=torch.float32)
112:         
113:         ## gaus
114:         gas = self.gaus(edge_attn)
115: 
116:         ## ph
117:         beta_0_up, beta_0_down, beta0_ext, beta1_ext, cyl = self.compute_extended_ph_link_tree_wcyclereps(ver_attn, data, self.device)
118:         ph_x, tpl = self.readout(beta_0_up, beta_0_down, beta0_ext, beta1_ext, graph_x, cyl)# [ver,ver] [ver, edge] [edge, edge] H0, H1 
119: 
120:         ## control experiment
121:         original_clf_logits = self.clf(data, up_attn = [None,None,None], down_attn = [None,None,None], bon_attn = [None,None,None], ph_x = ph_x)
122:         
123:         bon_attn = [None, self.node_attn_to_edge_attn(ver_attn,edge_attn, e_index[0]), self.node_attn_to_edge_attn(edge_attn, cell_attn, c_index[0])]
124:         up_attn = [self.node_attn_to_edge_attn(ver_attn,ver_attn, v_index[1]), self.node_attn_to_edge_attn(edge_attn,edge_attn, e_index[1]), None]
125:         down_attn = [None, self.node_attn_to_edge_attn(edge_attn,edge_attn, e_index[2]), self.node_attn_to_edge_attn(cell_attn,cell_attn, c_index[2])]
126:         
127:         masked_clf_logits = self.clf(data, up_attn = up_attn, down_attn = down_attn, bon_attn = bon_attn, ph_x = ph_x)
128: 
129:         loss, loss_dict = self.__loss__(cell_attn_log_logits[0].sigmoid(), cell_attn_log_logits[1].sigmoid(), cell_attn_log_logits[2].sigmoid(), masked_clf_logits, data.y, epoch, warmup, tpl, gas)
130:         return loss, loss_dict, original_clf_logits, masked_clf_logits, ver_attn.reshape(-1), edge_attn.reshape(-1), cell_attn.reshape(-1)
131: 
132:     def get_r(self, current_epoch, final_r):
133:         r = self.init_r - current_epoch // self.decay_interval * self.decay_r
134:         if r < final_r:
135:             r = final_r
136:         return r
137: 
138:     def sampling(self, attn_log_logits, do_sampling):
139:         if do_sampling:
140:             random_noise = torch.empty_like(attn_log_logits).uniform_(1e-10, 1 - 1e-10)
141:             random_noise = torch.log(random_noise) - torch.log(1.0 - random_noise)
142:             attn_bern = ((attn_log_logits + random_noise) / self.temperature).sigmoid()
143:         else:
144:             attn_bern = (attn_log_logits).sigmoid()
145:         return attn_bern
146: 
147:     @staticmethod
148:     def node_attn_to_edge_attn(src_attn, dst_attn, edge_index):
149:         if edge_index is None:
150:             return None
151:         src_attn = src_attn[edge_index[0]]
152:         dst_attn = dst_attn[edge_index[1]]
153:         edge_attn = src_attn * dst_attn
154:         return edge_attn
155:     
156:     @staticmethod
157:     def min_max_normalize(attn):
158:         attn_min = attn.min()
159:         attn_max = attn.max()
160:         epsilon = 1e-8
161:         attn_normalized = (attn - attn_min) / (attn_max - attn_min + epsilon)
162:         return attn_normalized
163:     
164:     def read_ph(self,data):
165:         emb, graph_x = self.clf.get_emb(data)
166:         cell_attn_log_logits = self.extractor(emb)
167:         ver_attn = self.sampling(cell_attn_log_logits[0], False)
168:         edge_attn = self.sampling(cell_attn_log_logits[1], False)
169:         cell_attn = self.sampling(cell_attn_log_logits[2], False)
170:         beta_0_up, beta_0_down, beta0_ext, beta1_ext, cyl= self.compute_extended_ph_link_tree_wcyclereps(ver_attn, data, self.device)
171:         print('beta0_ext',beta0_ext[0])
172:         # print('beta_0_down',beta_0_down[0])
173:         # print('beta_0_up',beta_0_up[0])
174:         print('beta1_ext',beta1_ext[0])
175:         print('cyl', cyl[0])
src/utils/model_utils.py SHA256 16e10d0261090ec6a5b72ab3c7b214d47b794f06ddb640a4d9436f3378216303
130:         return algo([{'params': clf_base_params}], lr=wp_lr, weight_decay=wp_wd)
131:     else:
132:         return algo([{'params': extractor.parameters(), 'lr': attn_lr, 'weight_decay': attn_wd}, {'params': clf_base_params},
133:                      {'params':slayer.parameters(),'lr': emb_lr, 'weight_decay': emb_wd}, {'params':gaus.parameters(),'lr': 0.001},
134:                      {'params': clf_emb_model_params, 'lr': emb_lr, 'weight_decay': emb_wd}], lr=pred_lr, weight_decay=pred_wd)
135:     
136: 
137: class PhAttn(nn.Module):
138:     def __init__(self, hidden_size, num_heads=2, input_dim=4):
139:         super(PhAttn, self).__init__()
140:         assert hidden_size % num_heads == 0, "hidden_size must be divisible by num_heads"
141: 
142:         self.hidden_size = hidden_size
143:         self.num_heads = num_heads
144:         self.head_dim = hidden_size // num_heads
145: 
146:         # define mutihead linear
147:         self.ph_emb = nn.Linear(input_dim, hidden_size, bias=False)
148:         self.graph_emb = nn.Linear(hidden_size, hidden_size, bias=False)
149: 
150:     def forward(self, graph_x, ph_x):
151:         """
152:         param:
153:             graph_x: [batch_size, hidden_size]
154:             ph_x: [batch_size, num_structure, input_dim]
155:         
156:         return:
157:             output: [batch_size, num_structure, input_dim]
158:         """
159:         batch_size, num_structure, input_dim = ph_x.size()
160:         # muti-head Linear projection
161:         ph_x_proj = self.ph_emb(ph_x)  # [batch_size, num_structure, hidden_size]
162:         graph_x_proj = self.graph_emb(graph_x)  # [batch_size, hidden_size]
163:         # reshape to muti-head format
164:         ph_x_proj = ph_x_proj.view(batch_size, num_structure, self.num_heads, self.head_dim) # [batch_size, num_structure, num_heads, head_dim]
165:         graph_x_proj = graph_x_proj.view(batch_size, self.num_heads, self.head_dim) # [batch_size, num_heads, head_dim]
166:         # permute dimensions for matrix operations
167:         ph_x_proj = ph_x_proj.permute(0, 2, 1, 3) # [batch_size, num_heads, num_structure, head_dim]
168:         graph_x_proj = graph_x_proj.unsqueeze(-1) # [batch_size, num_heads, head_dim, 1]
169:         # calculate attention score: head_dim*head_dim
170:         attn_logits = torch.matmul(ph_x_proj, graph_x_proj).squeeze(-1) # [batch_size, num_heads, num_structure]
171:         # softmax
172:         attn = F.softmax(attn_logits, dim=-1)  # [batch_size, num_heads, num_structure]
173:         # weighted sum, broadcast on num_heads
174:         attn = attn.unsqueeze(-1) # [batch_size, num_heads, num_structure, 1]
175:         weighted_x = attn * ph_x.unsqueeze(1)  # [batch_size, num_heads, num_structure, input_dim]
176:         weighted_x = weighted_x.view(batch_size, self.num_heads, num_structure, input_dim) # [batch_size, num_heads, num_structure, input_dim]
177:         # combine head
178:         output = weighted_x.mean(dim=1) 
179:         return output
180: 
181:     # def orthogonal_loss(self, attn1, attn2):
182:     #     # Compute orthogonal loss
183:     #     dot_product = torch.sum(attn1 * attn2, dim=1)
184:     #     orthogonal_loss = (dot_product ** 2).mean()
185:     #     return orthogonal_loss
186: 
187: 
188: 
189: class PershomReadout(nn.Module):
190:     def __init__(self,
191:                 #  dataset,
192:                  num_struct_elements=None,
193:                 #  cls_hidden_dimension=None,
194:                 #  drop_out=None,
195:                  ):
196:         super().__init__()
197:         assert isinstance(num_struct_elements, int)
198: 
199:         # self.ldgm_0_up = SLayerRationalHat(num_struct_elements, 2, radius_init=0.1)
200:         # self.ldgm_0_down = SLayerRationalHat(num_struct_elements, 2, radius_init=0.1)
201:         # self.ldgm_cc = SLayerRationalHat(num_struct_elements, 2,
202:         #                                  radius_init=0.1)
203:         self.ldgm_h1 = SLayerRationalHat(num_struct_elements, 2,
204:                                          radius_init=0.1)
205:         self.ldgm_h2 = SLayerRationalHat(num_struct_elements, 2,
206:                                          radius_init=0.1)
207:         self.num_struct_elements = num_struct_elements
208:         
209:         self.ph_attn_1 = PhAttn(128) # 2*graph_x.shape[1]
210: 
211:         self.ph_attn_2 = PhAttn(128) # 2*graph_x.shape[1]
212:         
213:     def do_ph_attn(self, ph, ldgm, graph_x, ph_attn):
214:         ph_out, centers, radius = ldgm(ph) # [bs,num_struct], [num_struct,2], [num_struct]
215:         ph_out = ph_out.unsqueeze(-1)
216:         centers = centers.unsqueeze(0).expand(ph_out.size(0),self.num_struct_elements,2)
217:         radius = radius.unsqueeze(0).unsqueeze(-1).expand(ph_out.size(0),self.num_struct_elements,1)
218:         to_attn = torch.cat((ph_out,centers, radius), dim=-1)
219:         return ph_attn(graph_x, to_attn)
220: 
221:     def forward(self, beta_0_up, beta_0_down, beta0_ext, beta1_ext, graph_x, cyl):
222:         
223:         input_device = beta_0_up[0].device
224:         # transform coordinates
225:         # x_0_ex = [beta[:,0] for beta in beta0_ext]
226:         # y_0_ex = [beta[:,1] for beta in beta0_ext]
227:         # beta0_ext_1sthalf = [torch.stack([x_0, 1-x_0], dim=1) for x_0 in x_0_ex]
228:         # beta0_ext_2sthalf = [torch.stack([y_0, 1-y_0], dim=1) for y_0 in y_0_ex]
229: 
230:         x_1_ex = [beta[:,0] for beta in beta1_ext]
231:         y_1_ex = [beta[:,1] for beta in beta1_ext]
232:         beta1_ext_1sthalf = [torch.stack([x_1, torch.ones_like(x_1)], dim=1) for x_1 in x_1_ex]
233:         beta1_ext_2sthalf = [torch.stack([1.0-y_1, torch.ones_like(y_1)], dim=1) for y_1 in y_1_ex]
234: 
235:         # define beta2 => ([x_1, 1+cyl_len], [y_1, 1+cyl_len])
236:         cyl_len = [torch.stack([torch.tensor(c.size(0)+1, device=input_device) for c in g]) for g in cyl]
237:         ## norm
238:         cyl_len_tensor = torch.cat(cyl_len)
239:         max_value = torch.max(cyl_len_tensor)
240:         min_value = torch.min(cyl_len_tensor)
241:         norm_cyl_len = []
242:         for g in cyl_len:
243:             normalized_g = (g - min_value + 1e-6) / (max_value - min_value + 1e-5)
244:             normalized_g = normalized_g + 1
245:             norm_cyl_len.append(normalized_g)
246:         ## combine
247:         beta2_1sthalf = []
248:         for idx in range(len(x_1_ex)):
249:             b21 = torch.stack([x_1_ex[idx], norm_cyl_len[idx]], dim=1)
250:             beta2_1sthalf.append(b21)
251:         beta2_2sthalf = []
252:         for idx in range(len(x_1_ex)):
253:             b22 = torch.stack([1-y_1_ex[idx], norm_cyl_len[idx]], dim=1)
254:             beta2_2sthalf.append(b22)
255: 
256:         # combine
257:         # ph_down = beta_0_down || beta0_ext_2sthalf || beta1_ext_2sthalf || beta2_2sthalf
258:         # ph_up = beta_0_up || beta0_ext_1sthalf || beta1_ext_1sthalf || beta2_1sthalf
259:         ph_up = [torch.cat((beta1_ext_1sthalf[i], beta2_1sthalf[i]), dim=0) for i in range(len(beta_0_up))]
260:         ph_down = [torch.cat((beta1_ext_2sthalf[i], beta2_2sthalf[i]), dim=0) for i in range(len(beta_0_up))]
261: 
262:         # ph_up_out, up_centers, up_r = self.ldgm_h1(ph_up) # [bs,num_struct], [num_struct,2], [num_struct]
263:         # ph_up_out = ph_up_out.unsqueeze(-1)
264:         # up_centers = up_centers.unsqueeze(0).expand(ph_up_out.size(0),self.num_struct_elements,2)
265:         # up_r = up_r.unsqueeze(0).unsqueeze(-1).expand(ph_up_out.size(0),self.num_struct_elements,1)
266:         # up_to_attn = torch.cat((ph_up_out,up_centers,up_r), dim=-1)
267:         # ph_up_out = self.ph_attn(graph_x,up_to_attn)
268: 
269:         ph_up_out_1 = self.do_ph_attn(ph_up, self.ldgm_h1, graph_x, self.ph_attn_1)
270:     
271:         # ph_down_out, down_centers, down_r = self.ldgm_h1(ph_down)
272:         # ph_down_out = ph_down_out.unsqueeze(-1)
273:         # down_centers = down_centers.unsqueeze(0).expand(ph_down_out.size(0),self.num_struct_elements,2)
274:         # down_r = down_r.unsqueeze(0).unsqueeze(-1).expand(ph_down_out.size(0),self.num_struct_elements,1)
275:         # down_to_attn = torch.cat((ph_down_out, down_centers, down_r), dim=-1)
276:         # ph_down_out = self.ph_attn(graph_x,down_to_attn)
277: 
278:         ph_down_out_1 = self.do_ph_attn(ph_down, self.ldgm_h1, graph_x, self.ph_attn_1)
279: 
280:         ph_up_out_2 = self.do_ph_attn(beta_0_up, self.ldgm_h2, graph_x, self.ph_attn_2)
281: 
282:         ph_down_out_2 = self.do_ph_attn(beta_0_down, self.ldgm_h2, graph_x, self.ph_attn_2)
283: 
284:         # MSE
285:         tpl = -((ph_up_out_1 - ph_down_out_1)**2).sum() - ((ph_up_out_2 - ph_down_out_2)**2).sum()
286: 
287:         ph_up_out_1 = ph_up_out_1[:,:,0]
288:         ph_down_out_1 = ph_down_out_1[:,:,0]
289:         ph_up_out_2 = ph_up_out_2[:,:,0]
290:         ph_down_out_2 = ph_down_out_2[:,:,0]
291: 
292:         x = torch.cat([ph_up_out_1, ph_down_out_1, ph_up_out_2, ph_down_out_2], dim=1)
293:         return x,tpl
294:     
295: 
296:     
297: class GaussianMixtureModel(nn.Module):
298:     def __init__(self, mu1=0.75, mu2=0.25, variance_penalty=1e-3):
299:         super().__init__()
300:         self.mu1 = mu1
301:         self.mu2 = mu2
302: 
303:         self.s1 = nn.Parameter(torch.log(torch.tensor(0.25)))  # r1 = 0.25
304:         self.s2 = nn.Parameter(torch.log(torch.tensor(0.25)))  # r2 = 0.25
305: 
306:         self.b = nn.Parameter(torch.tensor(0.0))  # a = sigmoid(0) = 0.5
307: 
308:         self.variance_penalty = variance_penalty
309: 
310:     def forward(self, x):
311: 
312:         r1 = torch.exp(self.s1)  
313:         r2 = torch.exp(self.s2)  
314:         a = 0.5  # torch.sigmoid(self.b)
315: 
316:         # PDF
317:         N1 = (1 / torch.sqrt(2 * torch.pi * r1)) * torch.exp(-0.5 * ((x - self.mu1) ** 2) / r1)
318:         N2 = (1 / torch.sqrt(2 * torch.pi * r2)) * torch.exp(-0.5 * ((x - self.mu2) ** 2) / r2)
319: 
320:         # mix PDF
321:         p = a * N1 + (1 - a) * N2
322: 
323:         nll = -torch.sum(torch.log(p + 1e-10), dim=1)  
324: 
325:         variance_control = 1.0 / (r1 + 1e-6) + 1.0 / (r2 + 1e-6) 
326: 
327:         loss = torch.mean(nll) + self.variance_penalty * torch.mean(variance_control)
328: 
329:         return loss
330: 
src/torchPHext/torchex_PHext/nn/slayer.py SHA256 6c4884fd6368acbe2a5ef665da435a01867de44901c511f58a9a8c24d9d6f883
417: class SLayerRationalHat(Module):
418:     """
419:     """
420:     def __init__(self, n_elements: int,
421:                  point_dimension: int=2,
422:                  centers_init: Tensor=None,
423:                  radius_init: float=1,
424:                  exponent: int=1
425:                  ):
426:         """
427:         Args:
428:             n_elements:
429:                 Number of structure elements used.
430: 
431:             point_dimension:
432:                 Dimensionality of the points of which the input multi
433:                 set consists of.
434: 
435:             centers_init:
436:                 The initialization for the centers of the structure elements.
437: 
438:             radius_init:
439:                 Initialization for radius of zero level-set of the hat.
440: 
441:             exponent:
442:                 Exponent of the rationals forming the hat.
443: 
444:         """
445:         super().__init__()
446: 
447:         self.n_elements = int(n_elements)
448:         self.point_dimension = int(point_dimension)
449:         self.exponent = int(exponent)
450: 
451:         centers_init = parameter_init_from_arg(arg=centers_init,
452:                                                size=(self.n_elements, self.point_dimension),
453:                                                default=torch.rand)
454: 
455:         radius_init = parameter_init_from_arg(arg=radius_init,
456:                                               size=(self.n_elements,),
457:                                               default=torch.ones,
458:                                               scalar_is_valid=True)
459: 
460:         self.centers = Parameter(centers_init)
461:         self.radius = Parameter(radius_init)
462:         self.norm_p = 1
463: 
464:     def forward(self, input)->Tensor:
465:         batch, not_dummy_points, max_points, batch_size = prepare_batch_if_necessary(
466:             input,
467:             point_dimension=self.point_dimension)
468: 
469:         batch = batch.unsqueeze(1).expand(
470:             batch_size,
471:             self.n_elements,
472:             max_points,
473:             self.point_dimension)
474: 
475:         not_dummy_points = not_dummy_points.unsqueeze(1).expand(-1, self.n_elements, -1)
476: 
477:         centers = self.centers.unsqueeze(1).expand(
478:             self.n_elements,
479:             max_points,
480:             self.point_dimension)
481:         centers = centers.unsqueeze(0).expand(batch_size, *centers.size())
482: 
483:         radius = self.radius
484:         radius = radius.unsqueeze(1).expand(-1, max_points)
485:         radius = radius.unsqueeze(0).expand(batch_size, *radius.size())
486:         radius = radius.abs()
487: 
488:         norm_to_center = centers - batch
489:         norm_to_center = torch.norm(norm_to_center, p=self.norm_p, dim=3)
490: 
491:         positive_part = 1/(1+norm_to_center).pow_(self.exponent)
492: 
493:         negative_part = 1/(1 + (radius - norm_to_center).abs_()).pow_(self.exponent)
494: 
495:         x = positive_part - negative_part
496: 
497:         x = torch.mul(x, not_dummy_points)
498:         x = torch.sum(x, 2)
499: 
500:         return x, self.centers, self.radius
501: 
502:     def __repr__(self):
503:         return 'SLayerRationalHat (... -> {} )'.format(self.n_elements)
504: 
505: 
src/trainer.py SHA256 4e751d02f3e0ae3c4902c6145139cc727e33cfd6baaf38fbe4ee5bdba06e2b2b
35: from backbones.cinpp import OGBEmbedCINpp
36: 
37: 
38: def eval_one_batch(baseline, optimizer, data, epoch, warmup, phase, method_name):
39:     with torch.set_grad_enabled(method_name in ['gradcam', 'gradgeo', 'bernmask']):
40:         assert optimizer is None
41:         baseline.extractor.eval() if hasattr(baseline, 'extractor') else None
42:         baseline.clf.eval()
43:         baseline.readout.eval()##
44:         baseline.gaus.eval() ##
45: 
46:         # baseline.read_ph(data) ##
47:         # exit(1)
48: 
49:         # BernMaskP
50:         do_sampling = False
51:         # do_sampling = True if phase == 'valid' and method_name == 'bernmask_p' else False # we find this is better for BernMaskP
52:         loss, loss_dict, org_clf_logits, masked_clf_logits, node_attn, edge_attn, cell_attn = baseline.forward_pass(data, epoch, warmup=warmup, do_sampling=do_sampling)
53:         return loss_dict, to_cpu(org_clf_logits), to_cpu(masked_clf_logits), to_cpu(node_attn), to_cpu(edge_attn), to_cpu(cell_attn)
54: 
55: 
56: def train_one_batch(baseline, optimizer, data, epoch, warmup, phase, method_name):
57:     baseline.extractor.train() if hasattr(baseline, 'extractor') else None
58:     baseline.clf.train() if (method_name != 'bernmask_p' or warmup) else baseline.clf.eval()
59:     baseline.readout.train()##
60:     baseline.gaus.train()##
61: 
62:     loss, loss_dict, org_clf_logits, masked_clf_logits, node_attn, edge_attn, cell_attn = baseline.forward_pass(data, epoch, warmup=warmup, do_sampling=True)
63:     optimizer.zero_grad()
64:     loss.backward()
65:     optimizer.step()
66:     return loss_dict, to_cpu(org_clf_logits), to_cpu(masked_clf_logits), to_cpu(node_attn), to_cpu(edge_attn), to_cpu(cell_attn)
67: 
68: 
69: def run_one_epoch(baseline, optimizer, data_loader, epoch, phase, warmup, seed, device, writer, method_name):
70:     loader_len = len(data_loader)
71:     run_one_batch = train_one_batch if phase == 'train' else eval_one_batch
72:     phase = 'test ' if phase == 'test' else phase  # align tqdm desc bar
73:     log_dict = {k: [] for k in ['attn0', 'attn1', 'attn2', 'clf_labels', 'org_clf_logits', 'masked_clf_logits', 'exp_labels']}
74:     all_loss_dict = {}
75: 
76:     num_skips = 0
77: 
78:     pbar = tqdm(data_loader)
79:     for idx, data in enumerate(pbar):
80:         data = process_data(data)   
81:         data = data.to(device)
82:         if isinstance(data, ComplexBatch):
83:             num_samples = data.cochains[0].x.size(0)
84:             for dim in range(1, data.dimension+1):
85:                 num_samples = min(num_samples, data.cochains[dim].num_cells)
86:         else:
87:             num_samples = data.x.size(0)
88:         
89:         if num_samples <= 1:
90:             # Skip batch if it only comprises one sample (could cause problems with BN)
91:             num_skips += 1
92:             if float(num_skips) / loader_len >= 0.25:
93:                 logging.warning("Warning! 25% of the batches were skipped this epoch")
94:             continue
95: 
96:         loss_dict, org_clf_logits, masked_clf_logits, attn0, attn1, attn2= run_one_batch(baseline, optimizer, data, epoch, warmup, phase, method_name)
97:         clf_labels = to_cpu(data.y)
98:         exp_labels = to_cpu(data.edge_label)
99:         # precision_at_k = self.get_precision_at_k(att, exp_labels, self.k, data.batch, data.edge_index)
100:         # avg_auroc = []
101: 
102:         # if not warmup:
103:         #     attn0, attn1, attn2 = get_relevant_nodes(attn0, attn1, attn2, data.cochains, data.y, signal_class)
104:             # prec_at_k, prec_at_2k, prec_at_3k, avg_auroc, angles,  _, eigen_ratio, _ = get_precision_at_k_and_avgauroc_and_angles(exp_labels, attn, covar_mat, node_dir, topk, attn_graph_id)
105:             # avg_auroc = []
106:             # avg_auroc.append(0.0)
107:             # avg_auroc = torch.tensor(avg_auroc)
108: 
109: 
110:         for key in log_dict.keys():
src/utils/logger.py SHA256 71125726927fb32ce27bb383b854ec3603e39c5793acfa0e374ef7dc06aa8dc2
180: def update_and_save_best_epoch_res(baseline, train_res, valid_res, test_res, metric_dict, epoch, model_dir, seed, topk, warmup, writer):
181:     # assert len(train_res) == 11 ##这里不是11了
182:     main_metric_idx = 3 if not warmup else 1 # {1, 3} for AUC; {0, 2} for acc
183: 
184:     better_val_auc = valid_res[main_metric_idx] > metric_dict['metric/best_clf_valid']
185:     same_val_auc_but_better_val_loss = (valid_res[main_metric_idx] == metric_dict['metric/best_clf_valid']) and (valid_res[-1] < metric_dict['metric/best_clf_valid_loss'])
186: 
187:     # calc angle
188:     # if (better_val_auc or same_val_auc_but_better_val_loss) and (epoch > 300 or warmup):
189: 
190:     if better_val_auc or same_val_auc_but_better_val_loss:
191:         metric_dict = {'metric/best_clf_epoch': epoch, 'metric/best_clf_valid_loss': valid_res[-1],
192:                        'metric/best_clf_train': train_res[main_metric_idx], 'metric/best_clf_valid': valid_res[main_metric_idx], 'metric/best_clf_test': test_res[main_metric_idx],
193:                        'metric/best_x_roc_train': train_res[4], 'metric/best_x_roc_valid': valid_res[4], 'metric/best_x_roc_test': test_res[4],}
194:                     #    'metric/best_x_prec@k_train': train_res[5], 'metric/best_x_prec@k_valid': valid_res[5], 'metric/best_x_prec@k_test': test_res[5],
195:                     #    'metric/best_x_prec@2k_train': train_res[6], 'metric/best_x_prec@2k_valid': valid_res[6], 'metric/best_x_prec@2k_test': test_res[6],
196:                     #    'metric/best_x_prec@3k_train': train_res[7], 'metric/best_x_prec@3k_valid': valid_res[7], 'metric/best_x_prec@3k_test': test_res[7],
197: 
198:         if model_dir is not None:
199:             os.makedirs(model_dir, exist_ok=True)
200:             save_checkpoint(baseline, model_dir, model_name='model' )
201: 
202:     if model_dir is not None:
203:         os.makedirs(model_dir, exist_ok=True)
204:         save_checkpoint(baseline, model_dir, model_name=f'model_{epoch}')
205: 
206:     if writer is not None and not warmup:
207:         for metric, value in metric_dict.items():
208:             metric = metric.split('/')[-1]
209:             writer.add_scalar(f'best/{metric}', value, epoch)
210: 
211:     print(f'[Seed {seed}, Epoch: {epoch}]: Best Epoch: {metric_dict["metric/best_clf_epoch"]}, Best Val Pred Loss: {metric_dict["metric/best_clf_valid_loss"]:.3f}, '
212:             f'Best Val Pred AUROC: {metric_dict["metric/best_clf_valid"]:.3f}, Best Test Pred AUROC: {metric_dict["metric/best_clf_test"]:.3f}, '
213:             f'Best Test X AUROC: {metric_dict["metric/best_x_roc_test"]:.3f}, ')#Best Test X Prec@{topk[0]}: {metric_dict["metric/best_x_prec@k_test"]:.3f},
214:             # f'Best Test X Prec@{topk[1]}: {metric_dict["metric/best_x_prec@2k_test"]:.3f}, Best Test X Prec@{topk[2]}: {metric_dict["metric/best_x_prec@3k_test"]:.3f}, '
215:             # f'Best Test Angle: {metric_dict["metric/best_angle_test"]:.3f}, Best Test Eigen Ratio: {metric_dict["metric/best_eigen_test"]:.3f}')
src/torchPHext/torchex_PHext/pershom/pershom_cpp_src/vertex_filtration_comp_cuda_wcyclereps.cpp SHA256 45298af3a3801713586c3f3148032595d27d0d135252eb609420854bd6a0b14f
1: #include <torch/extension.h>
2: //#include "ATen/core/function_schema.h"
3: // #include <ATen/cuda/CUDAApplyUtils.cuh>
4: 
5: // #include <cuda.h>
6: // #include <cuda_runtime.h>
7: // #include <thrust/sort.h>
8: // #include <thrust/unique.h>
9: // #include <thrust/device_ptr.h>
10: 
11: //#include <phat/compute_persistence_pairs.h>
12: //#include <phat/representations/bit_tree_pivot_column.h>
13: //#include <phat/algorithms/twist_reduction.h>
14: //#include <phat/algorithms/standard_reduction.h>
15: //#include <phat/persistence_pairs.h>
16: #include <vector>
17: #include <limits>
18: #include <future>
19: 
20: #include "vertex_filtration_comp_cuda.h"
21: 
22: //link cut tree:
23: #include <data_structure/link_cut_tree.hpp>
24: #include <monoids/max_index.hpp>
25: #include <monoids/plus.hpp>
26: #include <utils/macros.hpp>
27: 
28: using namespace torch;
29: 
30: namespace VertExtendedFiltCompCuda_link_cut_tree_cyclereps{
31:     auto EPS= 1e-20;
32:     class union_find {
33:     public:
34:         union_find(int64_t n) {
35:             this->count = n;
36:             this->parent.resize(n);
37:             for (auto i = 0; i < n; i++) {
38:                 this->parent[i] = i;
39:             }
40:             this->rank.resize(n, 0);
41:         }
42: 
43:         int64_t uf_depth(int64_t x) {
44:             return rank[x];
45:         }
46: 
47:         int64_t find(int64_t x) {
48:             int64_t tmp = x;
49:             while (parent[tmp] != tmp) {
50:                 parent[tmp] = parent[parent[tmp]];
51:                 tmp = parent[tmp];
52:             }
53:             return tmp;
54:         }
55: 
56:         void link(int64_t x, int64_t y) {
57:             x = find(x);
58:             y = find(y);
59:             if (x == y) {
60:                 return;
61:             }
62:             if (rank[x] < rank[y]) {
63:                 parent[x] = y;
64:             } else if (rank[x] > rank[y]) {
65:                 parent[y] = x;
66:             } else {
67:                 parent[y] = x;
68:                 rank[x] = rank[x] + 1;
69:             }
70:             count--;
71:         }
72: 
73:         int64_t num_connected_component() const {
74:             return this->count;
75:         }
76: 
77: 
78:     private:
79:         int64_t count;
80:         std::vector <int64_t> parent;
81:         std::vector <int64_t> rank;
82:     };
83: 
84:     std::vector <Tensor> compute_pd0(const Tensor &vertex_filtration,
85:                                 const std::vector <Tensor> &boundary_info) {
86:         auto num_nodes = vertex_filtration.size(0);
87:         union_find uf = union_find(num_nodes);
88:         Tensor tensor_edges = boundary_info[0];
89:         Tensor edge_val = std::get<0>(torch::max(vertex_filtration.index({tensor_edges}), 1));
90:         Tensor sorted_edge_indices = edge_val.argsort(-1, false);
91:         const Tensor sorted_edges = tensor_edges.index({sorted_edge_indices});
92:         edge_val = edge_val.index({sorted_edge_indices});
93:         auto num_edges = sorted_edges.size(0);
94:         std::vector <Tensor> pd_0;
95: 
96:         for (auto i = 0; i < num_edges; i++) {
97:             auto e = sorted_edges[i];
98:             auto e_val = edge_val[i];
99:             int64_t u = e[0].item<int64_t>();
100:             int64_t v = e[1].item<int64_t>();
101:             int64_t root_u = uf.find(u);
102:             int64_t root_v = uf.find(v);
103:             if (root_u == root_v) {
104:                 continue;
105:             }
106:             int64_t root = root_u;
107:             int64_t merged = root_v;
108:             if (vertex_filtration[root].item<double>() > vertex_filtration[merged].item<double>())
109:                 std::swap(root, merged);
110:             else if (std::abs(vertex_filtration[root].item<double>() - vertex_filtration[merged].item<double>()) <
111:                      EPS) {
112:                 if (root > merged)
113:                     std::swap(root, merged);
114:             }
115:             auto merged_val = vertex_filtration[merged];
116: //        std::cout << "M: " << merged_val.item<double>() << " E: " << e_val.item<double>()<< std::endl;
117:             Tensor pd_pair = torch::stack({merged_val, e_val});
118:             pd_0.emplace_back(pd_pair);
119:             uf.link(root, merged);
120:         }
121:         return pd_0;
122: 
123:     }
124: 
125:     std::vector<std::vector <std::vector<Tensor>>> extended_filt_persistence_single(const Tensor &vertex_filtration,
126:                                                              const std::vector <Tensor> &boundary_info) {
127: 
128:         std::vector <std::vector<Tensor>> pd;
129:         auto num_nodes = vertex_filtration.size(0);
130:         union_find uf = union_find(num_nodes);
131:         link_cut_tree<max_index_monoid<double> > lct(num_nodes);
132:         for (auto i = 0; i < num_nodes; i++) {
133:             lct.vertex_set(i, {vertex_filtration[i].item<double>(), i});
134:         }
135:         std::vector <size_t> pos_edge_index;
136:         std::vector <Tensor> pd_0_up = compute_pd0(vertex_filtration, boundary_info);
137:         std::vector <Tensor> pd_0_down, pd_0_ext_plus, pd_1_ext;
138:         std::vector<std::vector<Tensor>> cycle_reps;
139:         Tensor tensor_edges = boundary_info[0];
140:         Tensor edge_val = std::get<0>(torch::min(vertex_filtration.index({tensor_edges}), 1));
141:         Tensor sorted_edge_indices = edge_val.argsort(-1, true);
142:         const Tensor sorted_edges = tensor_edges.index({sorted_edge_indices});
143:         edge_val = edge_val.index({sorted_edge_indices});
144:         auto num_edges = sorted_edges.size(0);
145:         for (auto i = 0; i < num_edges; i++) {
146:             auto e = sorted_edges[i];
147:             auto e_val = edge_val[i];
148:             int64_t u = e[0].item<int64_t>();
149:             int64_t v = e[1].item<int64_t>();
150:             int64_t root_u = uf.find(u);
151:             int64_t root_v = uf.find(v);
152:             if (root_u == root_v) {
153:                 pos_edge_index.push_back(i);
154:                 continue;
155:             }
156:             auto u_rank = uf.uf_depth(u);//depth of union find connected component is in the union find data structure
157:             auto v_rank = uf.uf_depth(v);//depth of union find connected component is in the union find data structure
158: 
159:             if (u_rank < v_rank) {
160:                 lct.evert(u);
161:                 lct.link(u, v);
162:             } else {
163:                 lct.evert(v);
164:                 lct.link(v, u);
165:             }
166: 
167:             int64_t root = root_u;
168:             int64_t merged = root_v;
169:             if (vertex_filtration[root].item<double>() < vertex_filtration[merged].item<double>())
170:                 std::swap(root, merged);
171:             else if (std::abs(vertex_filtration[root].item<double>() - vertex_filtration[merged].item<double>()) <