MCPcopy Create free account
hub / github.com/Trustworthy-AI-Group/TransferAttack / forward

Method forward

transferattack/attack.py:67–102  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

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 """

Callers 1

__call__Method · 0.95

Calls 7

init_deltaMethod · 0.95
get_logitsMethod · 0.95
transformMethod · 0.95
get_lossMethod · 0.95
get_gradMethod · 0.95
get_momentumMethod · 0.95
update_deltaMethod · 0.95

Tested by

no test coverage detected