The general attack procedure Arguments: data (N, C, H, W): tensor for input images labels (N,): tensor for ground-truth labels if untargetd labels (2,N): tensor for [ground-truth, targeted labels] if targeted
(self, data, label, **kwargs)
| 65 | return load_single_model(model_name) |
| 66 | |
| 67 | def forward(self, data, label, **kwargs): |
| 68 | """ |
| 69 | The general attack procedure |
| 70 | |
| 71 | Arguments: |
| 72 | data (N, C, H, W): tensor for input images |
| 73 | labels (N,): tensor for ground-truth labels if untargetd |
| 74 | labels (2,N): tensor for [ground-truth, targeted labels] if targeted |
| 75 | """ |
| 76 | if self.targeted: |
| 77 | assert len(label) == 2 |
| 78 | label = label[1] # the second element is the targeted label tensor |
| 79 | data = data.clone().detach().to(self.device) |
| 80 | label = label.clone().detach().to(self.device) |
| 81 | |
| 82 | # Initialize adversarial perturbation |
| 83 | delta = self.init_delta(data) |
| 84 | |
| 85 | momentum = 0 |
| 86 | for _ in range(self.epoch): |
| 87 | # Obtain the output |
| 88 | logits = self.get_logits(self.transform(data+delta, momentum=momentum)) |
| 89 | |
| 90 | # Calculate the loss |
| 91 | loss = self.get_loss(logits, label) |
| 92 | |
| 93 | # Calculate the gradients |
| 94 | grad = self.get_grad(loss, delta) |
| 95 | |
| 96 | # Calculate the momentum |
| 97 | momentum = self.get_momentum(grad, momentum) |
| 98 | |
| 99 | # Update adversarial perturbation |
| 100 | delta = self.update_delta(delta, data, momentum, self.alpha) |
| 101 | |
| 102 | return delta.detach() |
| 103 | |
| 104 | def get_logits(self, x, **kwargs): |
| 105 | """ |
no test coverage detected