mutual_information.py SHA256 05db2f5e1ca037b112eb74d554cd32d5cffd16620aa71047e1dad3198a8ef889
63:         self.is_able = False
64:         self.device = next(model.parameters()).device
65:         self.penalized_parameter_names = get_every_but_forbidden_parameter_names(self.model, FORBIDDEN_LAYER_TYPES)
66:         self.subsampling = {}
67:         self.eps = torch.finfo(torch.float32).eps
68:         self.stds = torch.tensor([0.01, 0.1, 0.25, 0.5, 0.75, 1.0, 2.0, 3.0,
69:                      6.0, 9.0, 12.0, 15.0, 18.0, 21.0])
70: 
71: 
72:     def _spectra_hook(self, name):
73:         def spectra_hook(model, input, output):
74:             if self.is_able:
140:         num_seeds = 1
141:         sz1 = 2000
142:         sz1_y = 1000
143:         sz2 = 400
144:         batch_sz = 100
145:         MI_X_Z_violated = 0
146:         
147:         evaluators = {}
148: 
149:         for mode in ["mc", "jensen"]:
150:             evaluators1 = {}
151:             evaluators2 = {}
152:             MI_Z_X_results = []
153:             logprob_results = []
154:             for std in self.stds:  # sorted  
155:                 MI_Z_X_std, layer_logprob = self.compute_MI_Z_X(torch.ones(num_layers_incl_in).fill_(std), sz1, sz2, batch_sz, mode=mode)
156:                 MI_Z_X_results.append(MI_Z_X_std)
157:                 logprob_results.append(layer_logprob)
158:             MI_Z_X_results = torch.stack(MI_Z_X_results, dim=0)
159:             logprob_results = torch.stack(logprob_results, dim=0)
160: 
161:             best_std_i = torch.zeros(num_layers_incl_in, dtype=torch.long)
162:             
163:             print(self.layer_names)
164: 
165:             MI_constraint = -np.inf
166:             for curr_l in reversed(range(num_layers_incl_in)):
167:                 std_i_sat_constraint = (MI_Z_X_results[:, curr_l] >= MI_constraint).nonzero(as_tuple=True)[0]
168:                 assert len(std_i_sat_constraint.shape) == 1
169:                 if std_i_sat_constraint.shape[0] == 0:
170:                     best_std_l_i = logprob_results[:, curr_l].argmax()
171:                     MI_X_Z_violated += 1
172:                 else:
173:                     best_std_l_ii = logprob_results[std_i_sat_constraint, curr_l].argmax()
174:                     best_std_l_i = std_i_sat_constraint[best_std_l_ii]
175: 
176:                 best_std_i[curr_l] = best_std_l_i
177:                 MI_constraint = MI_Z_X_results[best_std_l_i, curr_l]
178: 
179:             best_stds = self.stds[best_std_i]
180:             
181:             print(self.layer_names)
182:             
183:             print(MI_Z_X_results.shape)
184:             
185:             
186:             for l in range(num_layers_incl_in):
187:                 evaluators1[name_template(f"MI_Z_X_results_{mode}____{self.layer_names[l]}")] = MI_Z_X_results[:, l].mean()
188:                 
189:             title = name_template(f"MI_Z_X_{mode}")
190: 
191:             MI_Z_Xy, c_l_y = self.compute_MI_Z_Xy(stds=best_stds, sz1=sz1_y, sz2=sz2, batch_sz=batch_sz, mode=mode)
192:             y_counts = torch.ones(num_classes) / len(self.feats[self.layer_names[0]][0])
193:             y_prop = y_counts / y_counts.sum()  # C
194:             avg_MI_Z_Xy = (MI_Z_Xy * y_prop.unsqueeze(0)).sum(dim=1)
195:             
196:             for l in range(num_layers_incl_in):
197:                 evaluators2[name_template(f"avg_MI_Z_Xy_{mode}____{self.layer_names[l]}")] = avg_MI_Z_Xy[l]
198:                 
199:             title = name_template(f"MI_Z_X|Y_{mode}")
200:                 
201:             evaluators = evaluators | evaluators1 | evaluators2
202:         
203:         evaluators[f'steps/ranks_{phase}'] = step
204:         tc.writer.log_scalars(evaluators)
205: 
206:         self.representations = {}
207:         self.subsampling = {}
208:         torch.cuda.empty_cache()
209:         
210:         
211:     def compute_MI_Z_X(self, stds, sz1, sz2, batch_sz, mode):
212: 
213:         num_layers_incl_in = len(self.layer_names)
214: 
215:         assert stds.shape == (num_layers_incl_in,)
216: 
217:         log_post = torch.distributions.normal.Normal(0, stds).log_prob(torch.zeros(num_layers_incl_in))
218:         assert log_post.shape == (num_layers_incl_in,)
219: 
220:         feat_ent_bounds_i = torch.zeros(num_layers_incl_in)
221:         layer_logprob = torch.zeros(num_layers_incl_in)
222: 
223:         for l in range(num_layers_incl_in):
224:             feats_l = torch.cat(self.feats[self.layer_names[l]], dim=0)
225:             assert len(feats_l.shape) == 2
226:             n_s, n_feat = feats_l.shape
227: 
228: 
229:             ref_i = torch.tensor(np.random.choice(n_s, sz2, replace=True))
230:             ref_feats = feats_l[ref_i]
231: 
232:             distr = torch.distributions.normal.Normal(ref_feats, stds[l].item())
233:             
234:             eval_i = torch.tensor(np.random.choice(n_s, sz1, replace=True))
235:             eval_feats = feats_l[eval_i]
236:             
237:             log_prior = self.compute_log_prior(eval_feats, distr, sz1, sz2, batch_sz, n_feat, mode)
238: 
239:             feat_ent_bounds_i[l] = (log_post[l] - log_prior).mean()
240:             layer_logprob[l] = log_prior.mean().item()
241: 
242:         return feat_ent_bounds_i, layer_logprob
245:     def compute_MI_Z_Xy(self, stds, sz1, sz2, batch_sz, mode):
246:         '''
247:         sz1 - sample size 1 = k ?
248:         sz2 - sample size 2 = n_c ?
249:         '''
250:         num_layers_incl_in = len(self.layer_names)
251:         num_classes = len(np.unique(self.y_true.cpu().numpy()))
252: 
253:         feat_ent_bounds_i = torch.zeros(num_layers_incl_in, num_classes)
254:         c_l_y = torch.zeros(num_layers_incl_in, num_classes)
255:         log_post = torch.distributions.normal.Normal(0, stds).log_prob(torch.zeros(num_layers_incl_in))
256:         for y in range(num_classes):
257:             for l in range(num_layers_incl_in):
258:                 feats_y_l = self.feats[self.layer_names[l]][y]
259:                 assert len(feats_y_l.shape) == 2
260:                 n_c, n_feat = feats_y_l.shape
261: 
262:                 # MI
263:                 print(n_c, sz2, "test")
264:                 ref_i =  torch.tensor(np.random.choice(n_c, sz2, replace=True))
265:                 ref_feats = feats_y_l[ref_i]
266: 
267:                 distr = torch.distributions.normal.Normal(ref_feats, stds[l].item())
268:                 
269:                 eval_i = torch.tensor(np.random.choice(n_c, sz1, replace=True))
270:                 eval_feats = feats_y_l[eval_i]
271:                 
272:                 log_prior = self.compute_log_prior(eval_feats, distr, sz1, sz2, batch_sz, n_feat, mode)
273:                 feat_ent_bounds_i[l, y] = (log_post[l] - log_prior).mean()
274: 
275:                 swapped_feats = eval_feats.clone()
276: 
277:                 swap_i = torch.tensor(np.random.choice(sz1, sz1, replace=True))
278:                 swap_j = torch.tensor(np.random.choice(n_feat, sz1, replace=True))
279: 
280:                 swapped_feats[range(sz1), swap_j] = eval_feats[swap_i, swap_j]
281: 
282:                 new_log_prior = self.compute_log_prior(swapped_feats, distr, sz1, sz2, batch_sz, n_feat, mode)
283:                 max_diff = (new_log_prior - log_prior).abs().max()
284:                 c_l_y[l, y] = max_diff.item()
285: 
286:         return feat_ent_bounds_i, c_l_y
287:     
288:     
289:     def compute_log_prior(self, eval_feats, distr, sz1, sz2, batch_sz, n_feat, mode):
290:         nb = int(np.ceil(sz1 / float(batch_sz)))
291:         log_priors = []
292:         for b_i in range(nb):
293:             s = (b_i * batch_sz)
294:             e =  min((b_i + 1) * batch_sz, sz1)
295:             b_sz = e - s
296: 
297:             eval_feats_b = eval_feats[s:e]
298:             eval_feats_expanded = eval_feats_b.unsqueeze(1).expand(b_sz, sz2, n_feat)
299:             log_prob = distr.log_prob(eval_feats_expanded)
300:             assert log_prob.shape == (b_sz, sz2, n_feat)
301: 
302:             log_prob = log_prob.sum(dim=2)
303: 
304:             if mode == "jensen":
305:                 log_prior = log_prob.mean(dim=1)
306:             elif mode == "mc":
307:                 log_prior =  - np.log(sz2) + torch.logsumexp(log_prob, dim=1)
308:             else:
309:                 raise NotImplementedError
310: 
311:             log_priors.append(log_prior)
312: 
313:         return torch.cat(log_priors, dim=0)
314:     
315: 
316:     def plot(self, evaluators, title, tc, step):
317:         import io
318: 
methods/early_exit.py SHA256 ea6cf2d9e5a5266f34532129e7409c41088cc0364327ebbb04378a328d715924
303:         def forward_generator_resnet(self, x):
304:             # we actually need to account for the original head
305:             n_heads = self.number_of_attached_heads + 1
306:             x = torch.relu(self.bn1(self.conv1(x)))
307:             head_idx = 0
308:             for i, block in enumerate(chain(self.layer1, self.layer2, self.layer3, self.layer4)):
309:                 x = block(x)
310:                 if i in self.head_place_at:
311:                     if args.gradient_equilibrium is True:
312:                         x = self.gradient_rescale(x, 1 / (n_heads - head_idx + 1))
313:                     elif args.gradient_equilibrium == 'reversed':
314:                         x = self.gradient_rescale(x, n_heads - head_idx)
315:                 x = yield x, None
316:                 if i in self.head_place_at:
317:                     if args.gradient_equilibrium is True:
318:                         x = self.gradient_rescale(x, n_heads - head_idx)
319:                     elif args.gradient_equilibrium == 'reversed':
320:                         x = self.gradient_rescale(x, 1 / (n_heads - head_idx + 1))
321:                     head_idx += 1
322:             x = F.adaptive_avg_pool2d(x, (1, 1))
323:             x = x.view(x.size(0), -1)
324:             y = self.linear(x)
325:             yield None, y
493:         elif args.aggregate_loss == 'ablation_from_l2w_increasing':
494:             nb_heads = len(losses)
495:             weights = torch.linspace(0.6, 1.4, steps=nb_heads).tolist()
496:             loss = sum(l * w for l, w in zip(losses, weights))
497:         elif args.aggregate_loss == 'ablation_from_l2w_deceasing':
498:             nb_heads = len(losses)
499:             weights = torch.linspace(1.4, 0.6, steps=nb_heads).tolist()
500:             loss = sum(l * w for l, w in zip(losses, weights))
501:         elif args.aggregate_loss == 'sdn':
502:             cur_coeffs = [0.01 + (tc.state.current_batch + 1) *
503:                           (max_coeff / (tc.state.current_batch + 1)) for max_coeff in max_coeffs]
504:             cur_coeffs = [min(max_coeff, cur_coeff) for max_coeff, cur_coeff in zip(max_coeffs, cur_coeffs)]
505:             # divides by number of exits so that hyperaparms could be more or less
506:             # ported from 'arith_mean' runs
507:             loss = sum(l * w for l, w in zip(losses, cur_coeffs)) / len(losses)
522:         if args.gather_stats and tc.state.current_batch % 20 == 0:
523:             dominance_values = defaultdict(float)
524:             unwrapped_model = tc.accelerator.unwrap_model(tc.model)
525:             named_params = {k: v for k, v in unwrapped_model.named_parameters()}
526:             # compute the aggregated gradient, save it
527:             grad_total_list = torch.autograd.grad(loss, list(named_params.values()), retain_graph=True,
528:                                                   allow_unused=True)
529:             grad_total = torch.cat([g.flatten() for g in grad_total_list])
530:             # for each exit
531:             for i, ic_loss in enumerate(losses):
532:                 # compute the gradient for the current exit
533:                 grad_ic_list = torch.autograd.grad(ic_loss, list(named_params.values()), retain_graph=True,
534:                                                    allow_unused=True, materialize_grads=True)
535:                 grad_ic = torch.cat([g.flatten() for g in grad_ic_list])
536:                 # compute and save the cosine
537:                 ic_grad_dominance = torch.nn.functional.cosine_similarity(grad_total, grad_ic, dim=0)
538:                 dominance_values[f'gradient_dominance_cosine_{i=}'] = ic_grad_dominance.item()
539:                 # for each parameter
540:                 for n, g_total, g_ic in zip(named_params.keys(), grad_total_list, grad_ic_list):
541:                     param_ic_grad_dominance = torch.nn.functional.cosine_similarity(g_total.flatten(), g_ic.flatten(),
542:                                                                                     dim=0)
543:                     dominance_values[f'gradient_dominance_cosine_{i=}/{n}'] = param_ic_grad_dominance.item()
572:             if args.is_mi_train and tc.state.current_batch % (args.mi_multiplier * batches_per_epoch) == 0:
573:                 tc.mi_train.enable()
574:                 tc.mi_train.analysis(tc.state.current_batch, scope='periodic', phase='train', tc=tc)
575:                 tc.mi_train.disable()
576:             if args.is_mi_test and tc.state.current_batch % (args.mi_multiplier * batches_per_epoch) == 0:
577:                 tc.mi_test.enable()
578:                 tc.mi_test.analysis(tc.state.current_batch, scope='periodic', phase='test', tc=tc)
579:                 tc.mi_test.disable()
645:     logging.info('Configured logging')
646:     tc = TrainingContext()
647:     setup_accelerator(args, tc)
648:     setup_files_and_logging(args, tc)
649:     setup_model(args, tc)
650:     setup_data(args, tc)
651:     setup_optimization(args, tc)
652:     setup_state(tc)
653:     # setup_tunnel(args, tc)
654:     # setup_mi(args, tc)
655:     setup_early_stopper(args, tc)
656:     setup_gradient_equalibrum(args, tc)
657:     setup_gradient_statistician_ee(args, tc)
architectures/early_exits/base.py SHA256 3296e71b699a22b9b041e6d6682810b9227fe38c2028ca2abf70dae2541e09f8
44:         ...
45: 
46:     def train(self, mode: Union[str, bool] = 'all'):
47:         if isinstance(mode, bool):
48:             nn.Module.train(self, mode)
49:             return
50:         else:
51:             self.training = mode
52:         if mode == 'all':
53:             nn.Module.train(self)
54:             self.requires_grad_(True)
55:         elif mode == 'without_backbone':
56:             nn.Module.train(self)
57:             self.requires_grad_(True)
58:             for m in self._core_modules:
59:                 m.eval()
60:                 m.requires_grad_(False)
104:         self._mode = 'all'
105: 
106:     def forward(self, x_input: torch.Tensor):
107:         assert self._mode in {'selected', 'threshold', 'all', 'patience'}
108:         enable_grad = True if self.training else False
109:         with ((torch.set_grad_enabled(enable_grad))):
110:             fg, x, head_outputs = self.forward_generator(x_input), None, []
111:             if self._mode == 'threshold':
112:                 sample_exited_at = torch.zeros(x_input.size(0), dtype=torch.int) - 1
113:                 # TODO possibly use a tensor instead of a list
114:                 sample_outputs = [torch.Tensor() for _ in range(x_input.size(0))]
115:                 try:
116:                     head_idx = 0
117:                     while True:
118:                         x, head_output = fg.send(x)
119:                         head_outputs.append(head_output)
120:                         head_probs = F.softmax(head_output, dim=-1)
121:                         head_confidences, _ = head_probs.max(dim=-1)
122:                         # early exiting masks
123:                         unresolved_samples_mask = sample_exited_at == -1
124:                         exit_mask_local = (head_confidences > self._confidence_threshold).cpu().squeeze(dim=-1)
125:                         exit_mask_global = torch.zeros_like(unresolved_samples_mask, dtype=torch.bool)
126:                         exit_mask_global[unresolved_samples_mask] = exit_mask_local
127:                         # update sample head index array
128:                         sample_exited_at[exit_mask_global] = head_idx
129:                         # update sample return list
130:                         exit_indices_global = exit_mask_global.nonzero().view(-1).tolist()
131:                         exit_indices_local = exit_mask_local.nonzero().view(-1).tolist()
132:                         assert len(exit_indices_global) == len(exit_indices_local), \
133:                             f'exit_indices_global: {exit_indices_global} exit_indices_local: {exit_indices_local}'
134:                         for j, k in zip(exit_indices_global, exit_indices_local):
135:                             sample_outputs[j] = head_output[k]
136:                         # head handled
137:                         head_idx += 1
138:                         # continue only if there are unresolved samples
139:                         if (exit_mask_local).all():
140:                             break
141:                         # continue only with remaining sample subset
142:                         x = x[~exit_mask_local]
143:                 except StopIteration:
144:                     exit_mask_global = unresolved_samples_mask
145:                     # update sample head index array
146:                     sample_exited_at[exit_mask_global] = head_idx
147:                     # update sample return list
148:                     exit_indices_global = exit_mask_global.nonzero().view(-1).tolist()
149:                     for j, k in enumerate(exit_indices_global):
150:                         sample_outputs[k] = head_output[j]
visualize/cost_vs_table.py SHA256 936850ee77962409ced0338abfca76977ea6b875bc17d19f7e1116f1b796ba4e
18: 
19: def generate_score_eff_table(core_stats, point_stats, ee_stats, name_dict, param, result_mult=100):
20:     saved_args = locals()
21:     cost_fractions = [0.25, 0.5, 0.75, 1.0, math.inf]
22:     # base_model_run_name = next(iter(core_stats.keys())) # TODO
23:     assert len(core_stats) > 0
24:     base_model_run_name = next(iter(core_stats.keys()))
25:     cost_100 = core_stats[base_model_run_name]['model_flops']
26:     # cost_100 = ee_stats[next(iter(ee_stats.keys()))]['head_flops'][-1]
27:     # collect
28:     ee_results = torch.zeros(len(ee_stats), len(cost_fractions))
29:     ee_stds = torch.zeros_like(ee_results)
30:     for i, run_name in enumerate(ee_stats.keys()):
31:         for j, cost_fraction in enumerate(cost_fractions):
32:             for k, threshold_cost in enumerate(ee_stats[run_name]['threshold_flops']):
33:                 if threshold_cost > cost_fraction * cost_100:
34:                     if k > 0:
35:                         result_valid = True
36:                         k -= 1
37:                     else:
38:                         result_valid = False
39:                     break
40:             if result_valid:
41:                 ee_results[i, j] = ee_stats[run_name]['threshold_scores'][k].item()
42:                 ee_stds[i, j] = ee_stats[run_name]['threshold_scores_std'][k].item()
43:             else:
44:                 ee_results[i, j] = math.nan
45:                 ee_stds[i, j] = math.nan
eval.py SHA256 4ec995d743b3f21ed3695cb0f3665fd67dc69367d5c24277bf3d98a65f5efc7c
124: def get_preds_earlyexiting(accelerator: Accelerator,
125:                            model: torch.nn.Module,
126:                            data_loader: torch.utils.data.DataLoader,
127:                            batches: int = 0):
128:     model.eval()
129:     unwrapped_model = accelerator.unwrap_model(model)
130:     batch_outputs = []
131:     batch_labels = []
132:     with torch.inference_mode():
133:         unwrapped_model.all_mode()
134:         for batch, (X, y) in enumerate(data_loader):
135:             output = model(X)
136:             output, y = accelerator.gather_for_metrics((output, y))
137:             y_preds = [y_pred.detach().cpu() for y_pred in output]
138:             batch_outputs.append(y_preds)
139:             batch_labels.append(y.detach().cpu())
140:             if batches > 0 and batch == batches - 1:
141:                 break
142:     head_preds = []
143:     for i in range(unwrapped_model.number_of_heads):
144:         head_outputs = torch.cat([batch_output[i] for batch_output in batch_outputs])
145:         head_preds.append(head_outputs)
146:     labels = torch.cat(batch_labels)
147:     return head_preds, labels
176: def average_earlyexiting_flops(head_costs: List, head_exit_counts: torch.Tensor):
177:     assert len(head_costs) == head_exit_counts.size(0), f'{head_costs=}\n{head_exit_counts=}'
178:     total_cost = 0.0
179:     for h_i, h_c in enumerate(head_costs):
180:         total_cost += h_c * head_exit_counts[h_i].item()
181:     average_cost = total_cost / head_exit_counts.sum().item()
182:     return average_cost
183: 
260:                 patience = torch.where(head_pred.argmax(-1) == prev_answers, patience + 1, 1)
261:                 unresolved_mask = exit_at == -1
262:                 exit_mask = (patience > patience_threshold) & unresolved_mask
263:                 exit_at[exit_mask] = i
264:                 outputs[exit_mask] = head_pred[exit_mask]
265:                 prev_answers = head_pred.argmax(-1)
266:             unresolved_mask = exit_at == -1
267:             outputs[unresolved_mask] = head_preds[-1][unresolved_mask]
268:             exit_at[unresolved_mask] = len(head_preds) - 1
269:             threshold_accuracy = ((outputs.argmax(dim=-1) == labels).sum() / labels.size(0)).item()
270:             exits_bincounted = exit_at.bincount(minlength=len(head_preds))
271:             threshold_cost = average_earlyexiting_flops(head_flops, exits_bincounted)
272:             threshold_accuracies.append(threshold_accuracy)
273:             threshold_flops.append(threshold_cost)
274:     else:
275:         head_probs = [preds.softmax(dim=-1) for preds in head_preds]
276:         thresholds = torch.linspace(0.0, 1.0, steps=eval_thresholds, device=labels.device)
277:         for threshold in thresholds:
278:             exit_at = torch.zeros_like(labels) - 1
279:             outputs = torch.zeros_like(head_probs[0])
280:             for i, head_prob in enumerate(head_probs):
281:                 head_confidences = prob_to_confidence(head_prob)
282:                 unresolved_mask = exit_at == -1
283:                 exit_mask = (head_confidences > threshold) & unresolved_mask
284:                 exit_at[exit_mask] = i
285:                 outputs[exit_mask] = head_prob[exit_mask]
286:             unresolved_mask = exit_at == -1
287:             outputs[unresolved_mask] = head_probs[-1][unresolved_mask]
288:             exit_at[unresolved_mask] = len(head_probs) - 1
289:             threshold_accuracy = ((outputs.argmax(dim=-1) == labels).sum() / labels.size(0)).item()
290:             exits_bincounted = exit_at.bincount(minlength=len(head_probs))
291:             threshold_cost = average_earlyexiting_flops(head_flops, exits_bincounted)
292:             threshold_accuracies.append(threshold_accuracy)
293:             threshold_flops.append(threshold_cost)
294:     results = {'head_scores': head_accuracies, 'head_flops': head_flops, 'thresholds': thresholds,
295:                'threshold_scores': threshold_accuracies, 'threshold_flops': threshold_flops}
common.py SHA256 ab8cc82d5db89e564e39b2de2daa07656bbc93b02ea068034c27452fcb8b3099
130: 
131:     # Ranks
132:     default_args.is_rank_train = False
133:     default_args.is_rank_test = False
134:     default_args.rank_multiplier = 50
135:     default_args.is_mi_train = False
136:     default_args.is_mi_test = False
137:     default_args.mi_multiplier = 50
138:     default_args.MAX_REPR_SIZE = 2000
scripts/sdn_example_resnet34_cifar100_mutual_info.py SHA256 47028e5c6dab06f1430c081cac29ca406b0de3895100a07039135a1375b6e1e4
95:     common_args.early_stopping_metric_type = 'acc'
96:     
97:     common_args.is_rank_train = False
98:     common_args.is_rank_test = False
99:     common_args.rank_multiplier = 50
100:     common_args.is_mi_train = False
101:     common_args.is_mi_test = False
102:     common_args.mi_multiplier = 50
103:     common_args.MAX_REPR_SIZE = 2000
104: 
scripts/regimes/configuration/regimes_configuration.py SHA256 14320504766357fcf9d35167a24424cc178f9a83c5262bc165ca21f0ec0c66f6
20: class DisjointConfiguration(RegimeConfiguration):
21:     def update_base_config(self, config: DictConfig, max_epochs_amount_per_phase: int):
22:         config.epochs = max_epochs_amount_per_phase
23: 
24:     def update_ee_config(self, config: DictConfig, max_epochs_amount_per_phase: int):
25:         config.phase2 = 0
26:         config.phase3 = max_epochs_amount_per_phase
27:         config.epochs = config.phase2 + config.phase3
28:         config.epochs_common = config.phase2
29:         config.with_backbone = True if config.phase2 != 0 else False
30:         config.with_phase3 = True if config.phase3 != 0 else False
31: 
32:     def regime_name(self) -> str:
33:         return "Disjoint"
34: 
35: 
36: class JointConfiguration(RegimeConfiguration):
37: 
38:     def update_base_config(self, config: DictConfig, max_epochs_amount_per_phase: int):
39:         config.epochs = 0
40: 
41:     def update_ee_config(self, config: DictConfig, max_epochs_amount_per_phase: int):
42:         config.phase2 = max_epochs_amount_per_phase
43:         config.phase3 = 0
44:         config.epochs = config.phase2 + config.phase3
45:         config.epochs_common = config.phase2
46:         config.with_backbone = True if config.phase2 != 0 else False
47:         config.with_phase3 = True if config.phase3 != 0 else False
48: 
49:     def regime_name(self) -> str:
50:         return "Joint"
51: 
52: 
53: class MixedConfiguration(RegimeConfiguration):
54: 
55:     def update_base_config(self, config: DictConfig, max_epochs_amount_per_phase: int):
56:         config.epochs = max_epochs_amount_per_phase
57: 
58:     def update_ee_config(self, config: DictConfig, max_epochs_amount_per_phase: int):
59:         config.phase2 = max_epochs_amount_per_phase
60:         config.phase3 = 0
61:         config.epochs = config.phase2 + config.phase3
62:         config.epochs_common = config.phase2
63:         config.with_backbone = True if config.phase2 != 0 else False
64:         config.with_phase3 = True if config.phase3 != 0 else False
65: 
scripts/regimes_resnet_gradient_equilibrium.py SHA256 221bc86b6bc566afd31fbf02e5f61fb5fd589c3174eeda2773f615b42910787e
63:     exp_ids = [1, 2, 3]
64:     # exp_ids = [1]
65:     common_args.runs_dir = Path(os.environ['RUNS_DIR'])
66:     # common_args.dataset = 'tinyimagenet'
67:     common_args.dataset = 'cifar100'
68:     common_args.dataset_args = {}
69:     common_args.train_val_split_test_size = 0.05
70:     common_args.train_val_split_seed = 42
126:     for regime in ['joint', 'mixed']:
127:         for ge, loss_scaling in [
128:             (False, 'arith_mean'),
129:             (True, 'arith_mean'),
130:             ('reverse', 'arith_mean'),
131:             (False, 'ablation_from_l2w_increasing'),
132:             (False, 'ablation_from_l2w_deceasing'),
133:             (False, 'sdn'),
134:         ]:
135:             if regime == 'joint':
186:             sdn_model_args.optimizer_class = 'adam'
187:             # sdn_model_args.optimizer_args = {}
188:             # sdn_model_args.optimizer_args.lr = 0.001
189:             # sdn_model_args.optimizer_args.weight_decay = 0.0
190: 
191:             sdn_model_args.gradient_equilibrium = ge
192:             sdn_model_args.aggregate_loss = loss_scaling
193: 
194:             # ════════════════════════ train SDN models ════════════════════════ #
195: 
utils.py SHA256 2e483377dd8014ebde526edd9205dcea406c6aec68ae407bca87b20dedaad4f0
971: class GradientRescaleFunction(torch.autograd.Function):
972: 
973:     @staticmethod
974:     def forward(ctx, input, weight):
975:         ctx.save_for_backward(input)
976:         # logging.info(f'Setting rescale weight to: {weight}')
977:         ctx.gd_scale_weight = weight
978:         output = input
979:         return output
980: 
981:     @staticmethod
982:     def backward(ctx, grad_output):
983:         input = ctx.saved_tensors
984:         grad_input = grad_weight = None
985:         if ctx.needs_input_grad[0]:
986:             # logging.info(f'Rescaling by: {ctx.gd_scale_weight}')
987:             grad_input = ctx.gd_scale_weight * grad_output
988:         return grad_input, grad_weight