(self, base_img, final_img)
| 47 | self._save_results(total_filter_mac, 'mac') |
| 48 | |
| 49 | def _mask_attribute_conductance(self, base_img, final_img): |
| 50 | total_step = self.opt['total_step'] |
| 51 | |
| 52 | with torch.no_grad(): |
| 53 | _, _, p_x_full = self.mask_generator(final_img) |
| 54 | p_x_flat = p_x_full.flatten() |
| 55 | order_array = torch.argsort(p_x_flat).cpu().numpy() |
| 56 | |
| 57 | start_ratio = self.opt['pretrained_ratio'] |
| 58 | all_hook_layer_conductance = [0.0] * len(self.hook_list) |
| 59 | last_hook_layer_output = [] |
| 60 | |
| 61 | for step in range(total_step): |
| 62 | alpha = 1 - start_ratio + start_ratio * step / total_step |
| 63 | interpolated_img = self._get_interpolated_img_from_mask_attribute_path(base_img, final_img, alpha, order_array).to(self.device) |
| 64 | self.model.zero_grad() |
| 65 | interpolated_output = self.model(interpolated_img,None,None) |
| 66 | |
| 67 | if isinstance(interpolated_output, tuple): |
| 68 | interpolated_output = interpolated_output[0] |
| 69 | |
| 70 | loss = attr_grad(interpolated_output, reduce='sum') |
| 71 | loss.backward() |
| 72 | now_hook_layer_output = [] |
| 73 | for hook in self.hook_list: |
| 74 | if hasattr(hook, 'output') and hook.output is not None: |
| 75 | now_hook_layer_output.append(hook.output.detach()) |
| 76 | else: |
| 77 | now_hook_layer_output.append(None) |
| 78 | |
| 79 | if step > 0: |
| 80 | dfdy = [] |
| 81 | approx_dydx = [] |
| 82 | for i, hook in enumerate(self.hook_list): |
| 83 | if hasattr(hook, 'grad') and hook.grad is not None and now_hook_layer_output[i] is not None: |
| 84 | dfdy.append(hook.grad.detach()) |
| 85 | approx_dydx.append(now_hook_layer_output[i] - last_hook_layer_output[i]) |
| 86 | else: |
| 87 | dfdy.append(torch.zeros_like(last_hook_layer_output[i]) if last_hook_layer_output[i] is not None else None) |
| 88 | approx_dydx.append(torch.zeros_like(last_hook_layer_output[i]) if last_hook_layer_output[i] is not None else None) |
| 89 | |
| 90 | for i, (df, dy) in enumerate(zip(dfdy, approx_dydx)): |
| 91 | if df is not None and dy is not None: |
| 92 | all_hook_layer_conductance[i] += df * dy |
| 93 | |
| 94 | last_hook_layer_output = now_hook_layer_output |
| 95 | return [torch.mean(torch.abs(cond) if isinstance(cond, torch.Tensor) else torch.tensor(0.0)).detach().cpu().numpy() for cond in all_hook_layer_conductance] |
| 96 | |
| 97 | def main(): |
| 98 | root_path = osp.abspath(osp.join(__file__, osp.pardir, osp.pardir)) |
no test coverage detected