maskgen.py SHA256 e2ef30ad57ac44f2600d09ead5ca5327a8f9d19369d0420a8e52d19a8c43af35
1: import torch
2: import math
3: from torch import nn
4: import torch.nn.functional as F
5: import warnings
6: warnings.filterwarnings("ignore", category=UserWarning)
7: 
8: from txai.models.encoders.transformer_simple import TransformerMVTS
9: from txai.smoother import smoother, exponential_smoother
10: from txai.utils.functional import transform_to_attn_mask
11: from txai.models.encoders.positional_enc import PositionalEncodingTF
12: from tint.models import MLP, RNN
13: 
14: trans_decoder_default_args = {
15:     "nhead": 1, 
16:     "dim_feedforward": 32, 
17: }
18: 
19: MAX = 10000.0
20: 
21: import torch
22: from torch import Tensor
23: import warnings
24: 
25: 
26: def decoupled_gumbel_softmax(
27:         logits: Tensor,
28:         tau_forward: float = 1.0,
29:         tau_backward: float = 1.0,
30:         adapt_lr: float = 0.1,
31:         eps: float = 1e-10,
32:         dim: int = -1,
33:         adapt_tau: bool = True,
34:         tau_min: float = 0.1,
35:         tau_max: float = 10.0,
36: 
37: ) -> Tensor:
38:     """
39:     Sample from the Decoupled Gumbel-Softmax distribution with separate forward and backward temperatures.
40:     The forward pass uses tau_forward for prediction, and the backward pass uses tau_backward for gradient computation.
41: 
42:     Args:
43:         logits: `[..., num_features]` unnormalized log probabilities.
44:         tau_forward: initial forward temperature for prediction.
45:         tau_backward: initial backward temperature for gradient computation.
46:         hard: if ``True``, the returned samples will be discretized as one-hot vectors,
47:               but will be differentiated as if it is the soft sample in autograd.
48:         dim: A dimension along which softmax will be computed. Default: -1.
49:         adapt_tau: if ``True``, adaptively adjust temperatures during training.
50:         tau_min: minimum allowable temperature during adaptation.
51:         tau_max: maximum allowable temperature during adaptation.
52:         adapt_lr: learning rate for temperature adjustment.
53: 
54:     Returns:
55:         Sampled tensor of same shape as `logits` from the Decoupled Gumbel-Softmax distribution.
56:         If ``hard=True``, the returned samples will be one-hot, otherwise they will
57:         be probability distributions that sum to 1 across `dim`.
58: 
59:     Notes:
60:         This function implements the Decoupled Straight-Through Gumbel-Softmax method, allowing for independent
61:         control of forward and backward relaxation smoothness, with optional adaptive temperature adjustment.
62:     """
63: 
64:     if eps != 1e-10:
65:         warnings.warn("`eps` parameter is deprecated and has no effect.")
66: 
67:     # Initialize temperature gates
68:     tau_forward_gate = tau_forward
69:     tau_backward_gate = tau_backward
70: 
71:     # Adaptive adjustment logic (example heuristic based on logits variance)
72:     logits_std = torch.flatten(logits).std(dim=dim, unbiased=False)
73:     tau_forward_gate = tau_forward - adapt_lr * logits_std.clamp(min=0, max=1000)
74:     tau_backward_gate = tau_backward + adapt_lr * logits_std.clamp(min=0, max=1000)
75: 
76:     # Ensure temperatures stay within bounds
77:     tau_forward_gate = tau_forward_gate.clamp(min=tau_min, max=tau_max)
78:     tau_backward_gate = tau_backward_gate.clamp(min=tau_min, max=tau_max)
79: 
80:     # Forward pass with tau_forward_gate for prediction
81:     gumbels = (
82:         -torch.empty_like(logits, memory_format=torch.legacy_contiguous_format).exponential_().log()
83:     )  # ~Gumbel(0,1)
84:     gumbels_forward = (logits + gumbels) / tau_forward_gate  # Forward Gumbel(logits, tau_forward_gate)
85:     y_soft_forward = gumbels_forward.softmax(dim)
86: 
87:     # Straight-through for forward pass
88:     index = y_soft_forward.max(dim, keepdim=True)[1]
89:     y_hard = torch.zeros_like(logits, memory_format=torch.legacy_contiguous_format).scatter_(dim, index, 1.0)
90:     y_forward = y_hard - y_soft_forward.detach() + y_soft_forward
91: 
92:     # # Backward pass with tau_backward_gate for gradient computation
93:     # gumbels_backward = (logits + gumbels) / tau_backward_gate  # Backward Gumbel(logits, tau_backward_gate)
94:     # y_soft_backward = gumbels_backward.softmax(dim)
95: 
96:     # Use y_soft_backward in gradient computation
97:     if gumbels_forward.requires_grad:
98:         gumbels_forward.register_hook(lambda grad: grad * (tau_forward_gate / tau_backward_gate))
99: 
100:     return y_forward
101: 
102: 
103: class MaskGenerator(nn.Module):
104:     def __init__(self, 
105:             d_z, 
106:             max_len,
107:             d_pe = 16,
108:             trend_smoother = False,
109:             agg = 'max',
110:             pre_agg_mlp_d_z = 32,
111:             time_net_d_z = 64,
112:             trans_dec_args = trans_decoder_default_args,
113:             n_dec_layers = 2,
114:             tau = 1.0,
115:             use_ste = True,
116: 
117:             use_decoupled_ste=False,
118:             forward_ste_temperature=0.1,
119:             backward_ste_temperature=3.0,
120:             ste_learning_rate=0.001,
121:         ):
122:         super(MaskGenerator, self).__init__()
123: 
124:         self.d_z = d_z
125:         self.pre_agg_mlp_d_z = pre_agg_mlp_d_z
126:         self.time_net_d_z = time_net_d_z
127:         self.agg = agg
128:         self.max_len = max_len
129:         self.trend_smoother = trend_smoother
130:         self.use_ste = use_ste
131:         self.d_inp = self.d_z - d_pe
132:         self.tau = tau
133: 
134:         self.use_decoupled_ste = use_decoupled_ste
135:         self.forward_ste_temperature = forward_ste_temperature
136:         self.backward_ste_temperature = backward_ste_temperature
137:         self.ste_learning_rate = ste_learning_rate
138: 
139:         dec_layer = nn.TransformerDecoderLayer(d_model = d_z, **trans_dec_args) 
140:         self.mask_decoder = nn.TransformerDecoder(dec_layer, num_layers = n_dec_layers)
141: 
142:         # self.mask_decoder = nn.Sequential(
143:         #         RNN(
144:         #             input_size=d_z,
145:         #             rnn="gru",
146:         #             hidden_size=d_z,
147:         #             bidirectional=True,
148:         #         ),
149:         #         MLP([2 * d_z, d_z]),
150:         #     )
151: 
152:         
153:         self.pre_agg_net = nn.Sequential(
154:             nn.Linear(d_z, self.pre_agg_mlp_d_z),
155:             nn.PReLU(),
156:             nn.Linear(self.pre_agg_mlp_d_z, self.pre_agg_mlp_d_z),
157:             nn.PReLU(),
158:         )
159: 
160:         if self.d_inp > 1:
161:             self.time_prob_net = nn.Sequential(nn.Linear(d_z, self.d_inp), nn.Sigmoid())
162:         else:
163:             self.time_prob_net = nn.Linear(d_z, 2)
164: 
165:         # if self.d_inp > 1:
166:         #     self.time_prob_net =  MLP([d_z, 64, self.d_inp])
167:         #     self.time_prob_net_std = MLP([d_z, 64, self.d_inp])
168: 
169:         # else:
170:         #     self.time_prob_net =  MLP([d_z, 64, 2])
171:         #     self.time_prob_net_std = MLP([d_z, 64, 2])
172: 
173: 
174:         self.pos_encoder = PositionalEncodingTF(d_pe, max_len, MAX)
175: 
176:         self.init_weights()
177: 
178:     def init_weights(self):
179:         def iweights(m):
180:             if isinstance(m, nn.Linear):
181:                 torch.nn.init.xavier_uniform(m.weight)
182:                 m.bias.data.fill_(0.01)
183: 
184:         self.time_prob_net.apply(iweights)
185:         self.pre_agg_net.apply(iweights)
186: 
187:     def reparameterize(self, total_mask):
188: 
189:         if self.d_inp == 1:
190:             if total_mask.shape[-1] == 1:
191:                 # Need to add extra dim:
192:                 inv_probs = 1 - total_mask
193:                 total_mask_prob = torch.cat([inv_probs, total_mask], dim=-1)
194:             else:
195:                 total_mask_prob = total_mask.softmax(dim=-1)
196:         else:
197:             # Need to add extra dim:
198:             inv_probs = 1 - total_mask
199:             total_mask_prob = torch.stack([inv_probs, total_mask], dim=-1)
200: 
201:         if self.use_decoupled_ste:
202:             total_mask_reparameterize = decoupled_gumbel_softmax(
203:                                             torch.log(total_mask_prob + 1e-9),
204:                                             tau_forward = self.forward_ste_temperature,
205:                                             tau_backward=self.backward_ste_temperature,
206:                                             adapt_lr = self.ste_learning_rate,
207:                                             )[...,1]
208:         else:
209:             total_mask_reparameterize = F.gumbel_softmax(torch.log(total_mask_prob + 1e-9), tau=self.tau, hard=self.use_ste)[..., 1]
210: 
211:         return total_mask_reparameterize, total_mask_prob
212: 
213:     def forward(self, z_seq, src, times, get_agg_z = False):
214: 
215:         x = torch.cat([self.pos_encoder(times), src], dim=-1)  # t bs n
216:         # x = torch.cat([src, self.pos_encoder(times)], dim = -1) # t bs n
217: 
218:         # x = x.transpose(1,0) ###########
219: 
220: 
221:         if torch.any(times < -1e5):
222:             tgt_mask = (times < -1e5).transpose(0,1)
223:         else:
224:             tgt_mask = None
225: 
226:         z_seq_dec = self.mask_decoder(tgt = x, memory = z_seq, tgt_key_padding_mask = tgt_mask)
227: 
228:         # z_seq_dec = self.mask_decoder(x)  ###########
229:         # z_seq_dec = z_seq_dec.transpose(1,0)  ###########
230:         
231:         z_pre_agg = self.pre_agg_net(z_seq_dec)
232: 
233:         # mean = self.time_prob_net(z_seq_dec)
234:         # std = self.time_prob_net_std(z_seq_dec)
235:         # p_time = self.gauss_sample(mean, std)
236:         p_time = self.time_prob_net(z_seq_dec)
237: 
238:         total_mask_reparameterize, total_mask_prob = self.reparameterize(p_time.transpose(0,1))
239:         if self.d_inp == 1:
240:             total_mask = p_time.transpose(0,1).softmax(dim=-1)[...,1].unsqueeze(-1)
241:         else:
242:             total_mask = p_time.transpose(0,1) # Already sigmoid transformed
243: 
244:         # Transpose both src and times below bc expecting batch-first input
245: 
246:         # TODO: Get time and cycle returns later
247: 
248:         if get_agg_z:
249:             agg_z = z_pre_agg.max(dim=0)[0]
250:             return total_mask, total_mask_reparameterize, agg_z
251:         else:
252:             return total_mask, total_mask_reparameterize
253:         
254:     def gauss_sample(self, mean_logit, std, training=True):
255:         if training:
256:             att_bern = (mean_logit + std * torch.randn(mean_logit.shape, device=mean_logit.device)).sigmoid()
257:         else:
258:             att_bern = (mean_logit).sigmoid()
259:         return att_bern
consistency.py SHA256 f3d9f61f7b6d649d261314e25cdc4bbf63df1664ca998c7f56a595380a8de2ea
1: import torch
2: import torch.nn.functional as F
3: import numpy as np
4: 
5: import argparse, os
6: import sys
7: # Add the relative path to '../../' so that 'txai' can be found
8: # sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '/data/Yuejinghang/TimeXplusplus/txai')))
9: # sys.path.append('/data/Yuejinghang/TimeXplusplus')
10: 
11: from txai.utils.predictors.loss_smoother_stats import exp_criterion_eval_smoothers
12: from txai.utils.predictors.eval import eval_mv4, eval_mv4_loader
13: from txai.utils.cl import in_batch_triplet_sampling
14: from txai.models.run_model_utils import batch_forwards, batch_forwards_TransformerMVTS
15: from txai.utils.cl import basic_negative_sampling
16: 
17: from txai.utils.functional import js_divergence
18: 
19: default_scheduler_args = {
20:     'mode': 'max',
21:     'factor': 0.1,
22:     'patience': 5,
23:     'threshold': 0.00001,
24:     'threshold_mode': 'rel',
25:     'cooldown': 0,
26:     'min_lr': 1e-8,
27:     'eps': 1e-08,
28:     'verbose': True
29: }
30: 
31: from sklearn import metrics
32: def normalize_exp(exps):
33:     norm_exps = torch.empty_like(exps)
34:     for i in range(exps.shape[1]):
35:         norm_exps[:,i,:] = (exps[:,i,:] - exps[:,i,:].min()) / (exps[:,i,:].max() - exps[:,i,:].min() + 1e-9)
36:     return norm_exps
37: 
38: 
39: def print_results(mask_labelss, true_labelss):
40:     mask_labelss = normalize_exp(mask_labelss)
41: 
42:     if torch.is_tensor(mask_labelss):
43:         mask_labelss = mask_labelss.cpu().numpy()
44:     if torch.is_tensor(true_labelss):
45:         true_labelss = true_labelss.cpu().numpy()
46: 
47:     all_aupoc, all_auprc, all_aup, all_aur = [], [], [], []
48: 
49:     for i in range(mask_labelss.shape[1]):
50:         mask_label = mask_labelss[:, i, :]
51:         true_label = true_labelss[:, i, :]
52: 
53:         mask_prec, mask_rec, mask_thres = metrics.precision_recall_curve(
54:             true_label.flatten().astype(int), mask_label.flatten())
55:         try:
56:             AUROC = metrics.roc_auc_score(true_label.flatten(), mask_label.flatten())
57:         except ValueError:
58:             pass
59:         all_aupoc.append(AUROC)
60:         AUPRC = metrics.auc(mask_rec, mask_prec)
61:         all_auprc.append(AUPRC)
62:         AUP = metrics.auc(mask_thres, mask_prec[:-1])
63:         all_aup.append(AUP)
64:         AUR = metrics.auc(mask_thres, mask_rec[:-1])
65:         all_aur.append(AUR)
66:     print('Saliency AUROC: = {:.4f} +- {:.4f}'.format(np.mean(all_aupoc), np.std(all_aupoc) / np.sqrt(len(all_aupoc))))
67:     print('Saliency AUPRC: = {:.4f} +- {:.4f}'.format(np.mean(all_auprc), np.std(all_auprc) / np.sqrt(len(all_auprc))))
68:     print('Saliency AUP: = {:.4f} +- {:.4f}'.format(np.mean(all_aup), np.std(all_aup) / np.sqrt(len(all_aup))))
69:     print('Saliency AUR: = {:.4f} +- {:.4f}'.format(np.mean(all_aur), np.std(all_aur) / np.sqrt(len(all_aur))))
70: 
71:     resutlt_cur = {"AUROC": all_aupoc,
72:                    "AUPRC": all_auprc,
73:                    "AUP": all_aup,
74:                    "AUR": all_aur}
75:     return resutlt_cur
76: 
77: 
78: 
79: 
80: def kl_divergence_gaussian(mean1, logvar1, mean2, logvar2):
81:     kl_div = 0.5 * torch.mean((logvar2 - logvar1 - 1 + (logvar1.exp() + (mean1 - mean2).pow(2)) / logvar2.exp()))
82:     return kl_div
83: 
84: 
85: def contrast_loss(target, positive, negative, temperature=0.5, use_cosine_similarity=False):
86:     if use_cosine_similarity:
87:         consine_sim = torch.nn.CosineSimilarity(dim=1)
88:         positive_sim = consine_sim(target, positive)
89:         negative_sim = consine_sim(target, negative)
90:     else:
91:         positive_sim = torch.mul(target, positive).mean(dim=1)
92:         negative_sim = torch.mul(target, negative).mean(dim=1)
93: 
94:     positive_sim = torch.exp(positive_sim / temperature)
95:     negative_sim = torch.exp(negative_sim / temperature)
96: 
97:     loss = -torch.log(positive_sim / (positive_sim + negative_sim))
98:     return loss.mean()
99: 
100: 
101: def train_mv6_consistency(
102:         model,
103:         optimizer,
104:         train_loader,
105:         val_tuple,
106:         num_epochs,
107:         # Criterions:
108:         clf_criterion,
109:         sim_criterion,
110:         beta_exp,
111:         beta_sim,
112:         train_tuple,
113:         lam_label=1.0,
114:         clip_norm=True,
115:         use_scheduler=False,
116:         wait_for_scheduler=20,
117:         scheduler_args=default_scheduler_args,
118:         selection_criterion=None,
119:         save_path=None,
120:         early_stopping=True,
121:         label_matching=False,
122:         embedding_matching=True,
123:         opt_pred_mask=False,  # If true, optimizes based on clf_criterion
124:         opt_pred_mask_to_full_pred=False,
125:         batch_forward_size=None,
126:         simclr_training=False,
127:         num_negatives_simclr=64,
128:         max_batch_size_simclr_negs=None,
129:         bias_weight=0.1,
130: 
131:         cont_layer=1,
132:         cont_loss_weight_first=10,
133:         cont_loss_weight_last=10,
134:         sparse_loss_weight=10,
135:         sim_loss_weight=1,
136:         kl_loss_weight=1,
137:         use_decoupled_ste=True,
138:         forward_ste_temperature=0.5,
139:         backward_ste_temperature=0.5,
140:         ste_learning_rate=0.01,
141:         test=None,
142:         gt_exps=None,
143:         # scheduler=None,
144: ):
145:     '''
146:     Args:
147:         selection_criterion: function w signature f(out, val_tuple)
148: 
149:         if both label_matching and embedding_matching are true, then sim_criterion must be a list of length 2
150:             with [embedding_sim, label_sim] functions
151: 
152:     '''
153:     # TODO: Add weights and biases logging
154:     # print(cont_loss_weight)
155:     # print(sparse_loss_weight)
156:     # print(exp_loss_weight)
157:     # print(clf_loss_weight)
158: 
159:     best_epoch = 0
160:     if test != None:
161:         best_val_metric = 0.5#-1e9
162:     else:
163:         best_val_metric = -1e9
164: 
165:     if use_scheduler:
166:         scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, **scheduler_args)
167: 
168:     dataX, dataT, dataY = train_tuple  # Unpack training variables
169:     i=0
170:     for epoch in range(num_epochs):
171:         i = i + 1
172:         if i == 5:
173:             print(i)
174:         model.train()
175:         cum_sparse, cum_exp_loss, cum_clf_loss, cum_sim_loss, cum_cont_loss, cum_sparse_loss,cum_sim_loss,cum_kl_loss = [], [], [], [], [], [], [], []
176: 
177:         label_sim_list, emb_sim_list = [], []
178:         for step, (X, times, y, ids) in enumerate(train_loader):  # Need negative sampling here
179:             # i=i+1
180:             # if i==31:
181:             #     print(i)
182:             optimizer.zero_grad()
183: 
184:             # if detect_irreg:
185:             #     src_mask = (X < 1e-7)
186:             #     out_dict = model(X, times, captum_input = True)
187: 
188:             out_dict = model(X, times, captum_input=True)
189:             out = out_dict['pred']
190:             ste_mask = out_dict['ste_mask']
191:             if out.isnan().sum() > 0:
192:                 # Exits if nan's are found
193:                 print('out', out.isnan().sum())
194:                 exit()
195:             ## Loss-LC——原模型预测和代理模型预测的KL散度损失函数
196:             clf_loss = js_divergence(out_dict['pred_mask'].softmax(dim=-1), out_dict['pred'].softmax(dim=-1))
197: 
198:             # org_div, emb_div = out_dict['all_z']  #
199:             # reference_src, exp_src, _ = out_dict['reference_z']
200: 
201:             # ## Loss-KL——(X, X~)KL散度损失函数
202:             # sim_loss = kl_divergence_gaussian(emb_div[0], emb_div[1], org_div[0].mean(0, keepdim=True), org_div[1].mean(0, keepdim=True)) * bias_weight
203:             kl_loss = kl_loss_weight*kl_divergence_gaussian(out_dict['all_z'][1][0], out_dict['all_z'][1][1], out_dict['all_z'][0][0].mean(0, keepdim=True),
204:                                               out_dict['all_z'][0][1].mean(0, keepdim=True))
205: 
206:             # ## Loss-dr——(X~^r, X~)的距离损失函数
207:             # sim_loss += F.mse_loss(reference_src, exp_src)## 这里加上了上一个KL散度损失函数
208: 
209:             # if bias_weight==0:
210:             #     sim_loss = F.mse_loss(reference_src, exp_src)
211: 
212:             # sim_loss = beta_sim * sim_loss
213: 
214:             ## Loss-M——STE分布拟合 + con 损失函数(beta_exp就是文中的alpha)
215:             exp_loss = beta_exp * model.compute_loss(out_dict)
216:             # conc_emb_loss = conc_embeddings.abs().mean()
217: 
218:             ## ①将原始输入作为锚样本，x点乘M作为正样本，x点乘（1-M）作为负样本，计算对比损失函数
219:             if cont_layer == 1:
220:                 # positive_x_reference, positive_x_predict, negative_x_reference = out_dict['reference_z']
221:                 cont_loss = cont_loss_weight_first*contrast_loss(target=X[:, :, :],
222:                                           positive=out_dict['reference_z'][1][:, :, :].transpose(0, 1),
223:                                           negative=out_dict['reference_z'][2][:, :, :].transpose(0, 1),
224:                                           temperature=0.5,
225:                                           use_cosine_similarity=True)
226:             elif cont_layer == 2:
227:                 # positive_x_reference_z, positive_x_predict_z, negative_x_reference_z = out_dict['vis']
228:                 cont_loss = cont_loss_weight_last*contrast_loss(target=out_dict['vis'][0][:,:],
229:                                           positive=out_dict['vis'][1][:,:],
230:                                           negative=out_dict['vis'][2][:,:],
231:                                           temperature=0.5,
232:                                           use_cosine_similarity=True)
233:             elif cont_layer == 3:
234:                 cont_loss_first_layer = cont_loss_weight_first*contrast_loss(target=X[:, :, :],
235:                                           positive=out_dict['reference_z'][1][:, :, :].transpose(0, 1),
236:                                           negative=out_dict['reference_z'][2][:, :, :].transpose(0, 1),
237:                                           temperature=0.5,
238:                                           use_cosine_similarity=True)
239:                 cont_loss_last_layer = cont_loss_weight_last*contrast_loss(target=out_dict['vis'][0][:,:],
240:                                           positive=out_dict['vis'][1][:,:],
241:                                           negative=out_dict['vis'][2][:,:],
242:                                           temperature=0.5,
243:                                           use_cosine_similarity=True)
244:                 cont_loss = cont_loss_first_layer + cont_loss_last_layer
245:             ## ②将原始输入，x点乘M，x点乘（1-M）三者进入模型的特征编码分别作为锚样本、正样本和负样本，计算损失函数
246:             # target_z, positive_z, negative_z = out_dict['vis']
247:             # cont_loss = 10 * contrast_loss(target=target_z, positive=positive_z, negative=negative_z, temperature = 0.5, use_cosine_similarity = True)
248:             ## ③将训练集各个类别的特征编码均值作为特征锚点，参考《ICICLE: Interpretable Class Incremental Continual Learning》，
249:             ##
250: 
251:             ## ④计算掩码矩阵1的个数，保证|M|作为损失函数，保证稀疏性
252:             sparse_loss = sparse_loss_weight * torch.mean(out_dict['ste_mask'].sum(1))
253: 
254:             ## ⑤计算生成的正样本与噪声填充的正样本间的距离，避免过拟合
255:             sim_loss = sim_loss_weight*F.mse_loss(out_dict['reference_z'][0], out_dict['reference_z'][1])
256: 
257:             loss = clf_loss + exp_loss + cont_loss + sparse_loss + sim_loss + kl_loss# sim_loss # cont_loss + sparse_loss # #sim_loss # # #
258:             # +sim_loss
259:             # + conc_emb_loss
260:             # print('---------')
261:             # print('clf', clf_loss)
262:             # print('exp', exp_loss)
263:             # print('sim', sim_loss)
264:             # print('loss', loss)
265: 
266:             # import ipdb; ipdb.set_trace()
267: 
268:             if clip_norm:
269:                 # print('Clip')
270:                 torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
271: 
272:             # print('loss', loss.item())
273:             # exit()
274: 
275:             loss.backward()
276:             optimizer.step()
277:             # scheduler.step()
278: 
279:             cum_sparse.append(((ste_mask).sum() / ste_mask.flatten().shape[0]).item())
280:             cum_clf_loss.append(clf_loss.detach().item())
281:             cum_exp_loss.append([exp_loss.detach().clone().item()])
282:             # cum_sim_loss.append(sim_loss.detach().item())
283:             cum_cont_loss.append(cont_loss.detach().item())
284:             cum_sparse_loss.append(sparse_loss.detach().item())
285:             cum_sim_loss.append(sim_loss.detach().item())
286:             cum_kl_loss.append(kl_loss.detach().item())
287: 
288:         # Print all stats:
289:         # Convert to np:
290:         sparse = np.array(cum_sparse)  # Should be size (B, M)
291:         sparse = sparse.mean()
292:         clf = sum(cum_clf_loss) / len(cum_clf_loss)
293:         exp = np.array(cum_exp_loss)  # Size (B, M, L)
294:         exp = exp.mean(axis=0).flatten()
295:         # sim = np.mean(cum_sim_loss)
296:         cont = np.mean(cum_cont_loss)
297:         sparse_loss = np.mean(cum_sparse_loss)
298:         sim = np.mean(cum_sim_loss)
299:         kl = np.mean(cum_kl_loss)
300: 
301:         # sim_s = f'{sim:.4f}'
302: 
303:         print(
304:             f'Epoch: {epoch}: Sparsity = {sparse:.4f} \t Exp Loss = {exp} \t Clf Loss = {clf:.4f} \t Cont Loss = {cont}\t sparse Loss = {cont_loss}\t Sim Loss = {sim}\t kl Loss = {kl}')
305: 
306:         # Eval after every epoch
307:         # Call evaluation function:
308:         model.eval()
309: 
310:         if batch_forward_size is None:
311:             f1, out = eval_mv4(val_tuple, model)
312:         else:
313:             out = batch_forwards(model, val_tuple[0], val_tuple[1], batch_size=64)
314:             f1 = 0
315: 
316:         ste_mask = out['ste_mask']
317:         sparse = ste_mask.mean().item()
318: 
319:         # met = -1.0 * loss
320:         if test != None:
321:             if len(test) !=3:
322:                 f1, _, results_dict = eval_mv4_loader(test, model, gt_exps=gt_exps)
323:             else:
324:                 f1, _, results_dict = eval_mv4(test, model, gt_exps=gt_exps)
325:             generated_exps = results_dict["generated_exps"]
326:             gt_exps = results_dict["gt_exps"]
327:             resutlt_cur = print_results(generated_exps, gt_exps)
328:             met = np.mean(resutlt_cur['AUPRC'])
329:         else:
330:             met = -1.0 * loss
331: 
332: 
333:         cond = not early_stopping
334:         if early_stopping:
335:             cond = (met > best_val_metric)
336:         if cond:
337:             best_val_metric = met
338:             if save_path is not None:
339:                 model.save_state(save_path)
340:             best_epoch = epoch
341:             print('Save at epoch {}: Metric={:.4f}'.format(epoch, met))
342: 
343:         if use_scheduler and (epoch > wait_for_scheduler):
344:             scheduler.step(met)
345: 
346:         if (epoch + 1) % 10 == 0:
347:             valsparse = '{:.4f}'.format(sparse)
348:             print(f'Epoch {epoch + 1}, Val F1 = {f1:.4f}, Val Sparsity = {valsparse}')
349: 
350:     print(f'Best Epoch: {best_epoch + 1} \t Val F1 = {best_val_metric:.4f}')
README.md SHA256 59f23895af586a2b150baf15157cc875d6430300691a53f716329643996c6889
1: # ORTE_public
2: The complete code will be released soon.