| 290 | |
| 291 | |
| 292 | class SpectrumSimulationAttack(AdversarialInputAttacker): |
| 293 | def __init__( |
| 294 | self, |
| 295 | model: List[nn.Module], |
| 296 | total_step: int = 10, |
| 297 | random_start: bool = False, |
| 298 | step_size: float = 16 / 255 / 10, |
| 299 | criterion: Callable = nn.CrossEntropyLoss(), |
| 300 | targeted_attack=False, |
| 301 | mu: float = 1, |
| 302 | *args, |
| 303 | **kwargs, |
| 304 | ): |
| 305 | self.random_start = random_start |
| 306 | self.total_step = total_step |
| 307 | self.step_size = step_size |
| 308 | self.criterion = criterion |
| 309 | self.targerted_attack = targeted_attack |
| 310 | self.mu = mu |
| 311 | super(SpectrumSimulationAttack, self).__init__(model, *args, **kwargs) |
| 312 | |
| 313 | def perturb(self, x): |
| 314 | x = x + (torch.rand_like(x) - 0.5) * 2 * self.epsilon |
| 315 | x = clamp(x) |
| 316 | return x |
| 317 | |
| 318 | def attack( |
| 319 | self, |
| 320 | x, |
| 321 | y, |
| 322 | ): |
| 323 | """ |
| 324 | The attack algorithm of our proposed Spectrum Simulate Attack |
| 325 | :param images: the input images |
| 326 | :param gt: ground-truth |
| 327 | :param model: substitute model |
| 328 | :param mix: the mix the clip operation |
| 329 | :param max: the max the clip operation |
| 330 | :return: the adversarial images |
| 331 | """ |
| 332 | ori_x = x.clone() |
| 333 | momentum = self.mu |
| 334 | num_iter = self.total_step |
| 335 | eps = self.epsilon |
| 336 | alpha = self.step_size |
| 337 | grad = 0 |
| 338 | rho = 0.5 |
| 339 | N = 20 |
| 340 | sigma = 16 |
| 341 | |
| 342 | for i in tqdm(range(num_iter)): |
| 343 | noise = 0 |
| 344 | for n in range(N): |
| 345 | x.requires_grad = True |
| 346 | gauss = torch.randn(*x.shape) * (sigma / 255) |
| 347 | gauss = gauss.cuda() |
| 348 | x_dct = dct_2d(x + gauss).cuda() |
| 349 | mask = (torch.rand_like(x) * 2 * rho + 1 - rho).cuda() |
nothing calls this directly
no outgoing calls
no test coverage detected