-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathattack_steps.py
207 lines (177 loc) · 6.32 KB
/
attack_steps.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# MIT License
#
# Copyright (c) 2018 Andrew Ilyas, Logan Engstrom
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
"""
**For most use cases, this can just be considered an internal class and
ignored.**
This module contains the abstract class AttackerStep as well as a few subclasses.
AttackerStep is a generic way to implement optimizers specifically for use with
:class:`robustness.attacker.AttackerModel`. In general, except for when you want
to :ref:`create a custom optimization method <adding-custom-steps>`, you probably do not need to
import or edit this module and can just think of it as internal.
"""
import torch as ch
class AttackerStep:
'''
Generic class for attacker steps, under perturbation constraints
specified by an "origin input" and a perturbation magnitude.
Must implement project, step, and random_perturb
'''
def __init__(self, orig_input, eps, step_size, use_grad=True):
'''
Initialize the attacker step with a given perturbation magnitude.
Args:
eps (float): the perturbation magnitude
orig_input (ch.tensor): the original input
'''
self.orig_input = orig_input
self.eps = eps
self.step_size = step_size
self.use_grad = use_grad
def project(self, x):
'''
Given an input x, project it back into the feasible set
Args:
ch.tensor x : the input to project back into the feasible set.
Returns:
A `ch.tensor` that is the input projected back into
the feasible set, that is,
.. math:: \min_{x' \in S} \|x' - x\|_2
'''
raise NotImplementedError
def step(self, x, g):
'''
Given a gradient, make the appropriate step according to the
perturbation constraint (e.g. dual norm maximization for :math:`\ell_p`
norms).
Parameters:
g (ch.tensor): the raw gradient
Returns:
The new input, a ch.tensor for the next step.
'''
raise NotImplementedError
def random_perturb(self, x):
'''
Given a starting input, take a random step within the feasible set
'''
raise NotImplementedError
def to_image(self, x):
'''
Given an input (which may be in an alternative parameterization),
convert it to a valid image (this is implemented as the identity
function by default as most of the time we use the pixel
parameterization, but for alternative parameterizations this functino
must be overriden).
'''
return x
### Instantiations of the AttackerStep class
# L-infinity threat model
class LinfStep(AttackerStep):
"""
Attack step for :math:`\ell_\infty` threat model. Given :math:`x_0`
and :math:`\epsilon`, the constraint set is given by:
.. math:: S = \{x | \|x - x_0\|_\infty \leq \epsilon\}
"""
def project(self, x):
"""
"""
diff = x - self.orig_input
diff = ch.clamp(diff, -self.eps, self.eps)
return ch.clamp(diff + self.orig_input, 0, 1)
def step(self, x, g):
"""
"""
step = ch.sign(g) * self.step_size
return x + step
def random_perturb(self, x):
"""
"""
new_x = x + 2 * (ch.rand_like(x) - 0.5) * self.eps
return new_x
# return ch.clamp(new_x, 0, 1)
# L2 threat model
class L2Step(AttackerStep):
"""
Attack step for :math:`\ell_\infty` threat model. Given :math:`x_0`
and :math:`\epsilon`, the constraint set is given by:
.. math:: S = \{x | \|x - x_0\|_2 \leq \epsilon\}
"""
def project(self, x):
"""
"""
diff = x - self.orig_input
diff = diff.renorm(p=2, dim=0, maxnorm=self.eps)
return ch.clamp(self.orig_input + diff, 0, 1)
def step(self, x, g):
"""
"""
# Scale g so that each element of the batch is at least norm 1
l = len(x.shape) - 1
g_norm = ch.norm(g.view(g.shape[0], -1), dim=1).view(-1, *([1]*l))
scaled_g = g / (g_norm + 1e-10)
return x + scaled_g * self.step_size
def random_perturb(self, x):
"""
"""
new_x = x + (ch.rand_like(x) - 0.5).renorm(p=2, dim=1, maxnorm=self.eps)
return new_x
#return ch.clamp(new_x, 0, 1)
# Unconstrained threat model
class UnconstrainedStep(AttackerStep):
"""
Unconstrained threat model, :math:`S = [0, 1]^n`.
"""
def project(self, x):
"""
"""
return ch.clamp(x, 0, 1)
def step(self, x, g):
"""
"""
return x + g * self.step_size
def random_perturb(self, x):
"""
"""
new_x = x + (ch.rand_like(x) - 0.5).renorm(p=2, dim=1, maxnorm=step_size)
return new_x
# return ch.clamp(new_x, 0, 1)
class FourierStep(AttackerStep):
"""
Step under the Fourier (decorrelated) parameterization of an image.
See https://distill.pub/2017/feature-visualization/#preconditioning for more information.
"""
def project(self, x):
"""
"""
return x
def step(self, x, g):
"""
"""
return x + g * self.step_size
def random_perturb(self, x):
"""
"""
return x
def to_image(self, x):
"""
"""
return ch.sigmoid(ch.irfft(x, 2, normalized=True, onesided=False))