Skip to content

Commit 8bbb29e

Browse files
committed
Fix style checks
Signed-off-by: Beat Buesser <[email protected]>
1 parent 7e589ee commit 8bbb29e

File tree

6 files changed

+57
-86
lines changed

6 files changed

+57
-86
lines changed

.github/workflows/ci-lingvo.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ jobs:
5050
sudo apt-get update
5151
sudo apt-get -y -q install ffmpeg libavcodec-extra
5252
python -m pip install --upgrade pip setuptools wheel
53-
pip install -q -r <(sed '/^scipy/d;/^matplotlib/d;/^pandas/d;/^statsmodels/d;/^numba/d;/^jax/d;/^h5py/d;/^Pillow/d;/^pytest/d;/^pytest-mock/d;/^torch/d;/^torchaudio/d;/^torchvision/d;/^xgboost/d;/^requests/d;/^tensorflow/d;/^keras/d;/^kornia/d;/^librosa/d;/^tqdm/d;/^timm/d;/^catboost/d;/^scikit-learn/d;/^GPy/d;/^lief/d' requirements_test.txt)
53+
pip install -q -r <(sed '/^scipy/d;/^matplotlib/d;/^pandas/d;/^statsmodels/d;/^numba/d;/^jax/d;/^h5py/d;/^Pillow/d;/^pytest/d;/^pytest-mock/d;/^torch/d;/^torchaudio/d;/^torchvision/d;/^xgboost/d;/^requests/d;/^tensorflow/d;/^keras/d;/^kornia/d;/^librosa/d;/^tqdm/d;/^timm/d;/^catboost/d;/^scikit-learn/d;/^GPy/d;/^lief/d;/^ultralytics/d;/^ipython/d' requirements_test.txt)
5454
pip install scipy==1.5.4
5555
pip install matplotlib==3.3.4
5656
pip install pandas==1.1.5

.github/workflows/ci-tensorflow-v1.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ jobs:
4848
sudo apt-get update
4949
sudo apt-get -y -q install ffmpeg libavcodec-extra
5050
python -m pip install --upgrade pip setuptools wheel
51-
pip install -q -r <(sed '/^pandas/d;/^scipy/d;/^matplotlib/d;/^xgboost/d;/^tensorflow/d;/^keras/d;/^jax/d;/^torch/d;/^Pillow/d;/^h5py/d;/^kornia/d;/^scikit-learn/d;/^pytest-mock/d;/^GPy/d;/^lief/d;/^statsmodels/d' requirements_test.txt)
51+
pip install -q -r <(sed '/^pandas/d;/^scipy/d;/^matplotlib/d;/^xgboost/d;/^tensorflow/d;/^keras/d;/^jax/d;/^torch/d;/^Pillow/d;/^h5py/d;/^kornia/d;/^scikit-learn/d;/^pytest-mock/d;/^GPy/d;/^lief/d;/^statsmodels/d;/^ultralytics/d;/^ipython/d' requirements_test.txt)
5252
pip install pandas==1.3.5
5353
pip install scipy==1.7.2
5454
pip install matplotlib==3.5.3

art/attacks/evasion/overload/box_iou.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
# pylint: disable=C0103,C0114
12
# GNU AFFERO GENERAL PUBLIC LICENSE
23
# Version 3, 19 November 2007
34
#
@@ -660,8 +661,14 @@
660661
# For more information on this, and how to apply and follow the GNU AGPL, see
661662
# <https://www.gnu.org/licenses/>.
662663

664+
from typing import TYPE_CHECKING
663665

664-
def box_iou(box1: "torch.tensor", box2: "torch.tensor", eps: float = 1e-7) -> "torch.tensor":
666+
if TYPE_CHECKING:
667+
# pylint: disable=C0412
668+
import torch
669+
670+
671+
def box_iou(box1: "torch.Tensor", box2: "torch.Tensor", eps: float = 1e-7) -> "torch.Tensor":
665672
"""
666673
=== NOTE ===
667674
This function is copied from YOLOv5 repository (yolov5/utils/metrics.py)
@@ -684,4 +691,3 @@ def box_iou(box1: "torch.tensor", box2: "torch.tensor", eps: float = 1e-7) -> "t
684691

685692
# IoU = inter / (area1 + area2 - inter)
686693
return inter / ((a2 - a1).prod(2) + (b2 - b1).prod(2) - inter + eps)
687-

art/attacks/evasion/overload/overload.py

Lines changed: 27 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -97,12 +97,11 @@ def generate(self, x: np.ndarray, y: Optional[np.ndarray] = None, **kwargs) -> n
9797

9898
return x_adv
9999

100-
def _generate_batch(self, x_batch: np.ndarray, y_batch: Optional[np.ndarray] = None) -> np.ndarray:
100+
def _generate_batch(self, x_batch: np.ndarray) -> np.ndarray:
101101
"""
102102
Run the attack on a batch of images.
103103
104104
:param x_batch: A batch of original examples.
105-
:param y_batch: Not Used.
106105
:return: A batch of adversarial examples.
107106
"""
108107

@@ -144,7 +143,7 @@ def _attack(self, x_adv: "torch.Tensor", x: "torch.Tensor") -> "torch.Tensor":
144143
x_adv.requires_grad_(False)
145144
return x_adv
146145

147-
def _loss(self, x: "torch.tensor") -> Tuple["torch.tensor", "torch.tensor"]:
146+
def _loss(self, x: "torch.Tensor") -> Tuple["torch.Tensor", "torch.Tensor"]:
148147
"""
149148
Compute the weight of each pixel and the overload loss for a given image.
150149
@@ -155,13 +154,13 @@ def _loss(self, x: "torch.tensor") -> Tuple["torch.tensor", "torch.tensor"]:
155154
import torch
156155

157156
adv_logits = self.estimator.model.model(x)
158-
if type(adv_logits) is tuple:
157+
if isinstance(adv_logits, tuple):
159158
adv_logits = adv_logits[0]
160159

161-
THRESHOLD = self.estimator.model.conf
160+
threshold = self.estimator.model.conf
162161
conf = adv_logits[..., 4]
163162
prob = adv_logits[..., 5:]
164-
prob = torch.where(conf[:, :, None] * prob > THRESHOLD, torch.ones_like(prob), prob)
163+
prob = torch.where(conf[:, :, None] * prob > threshold, torch.ones_like(prob), prob)
165164
prob = torch.sum(prob, dim=2)
166165
conf = conf * prob
167166

@@ -174,19 +173,19 @@ def _loss(self, x: "torch.tensor") -> Tuple["torch.tensor", "torch.tensor"]:
174173
stride_x = x.shape[-2] // self.num_grid
175174
stride_y = x.shape[-1] // self.num_grid
176175
grid_box = torch.zeros((0, 4), device=x.device)
177-
for ii in range(self.num_grid):
178-
for jj in range(self.num_grid):
179-
x1 = ii * stride_x
180-
y1 = jj * stride_y
181-
x2 = min(x1 + stride_x, x.shape[-2])
182-
y2 = min(y1 + stride_y, x.shape[-1])
183-
bb = torch.as_tensor([x1, y1, x2, y2], device=x.device)[None, :]
184-
grid_box = torch.cat([grid_box, bb], dim=0)
185-
186-
for xi in range(x.shape[0]):
187-
xyhw = adv_logits[xi, :, :4]
188-
prob = torch.max(adv_logits[xi, :, 5:], dim=1).values
189-
box_idx = adv_logits[xi, :, 4] * prob > THRESHOLD
176+
for i_i in range(self.num_grid):
177+
for j_j in range(self.num_grid):
178+
x_1 = i_i * stride_x
179+
y_1 = j_j * stride_y
180+
x_2 = min(x_1 + stride_x, x.shape[-2])
181+
y_2 = min(y_1 + stride_y, x.shape[-1])
182+
b_b = torch.as_tensor([x_1, y_1, x_2, y_2], device=x.device)[None, :]
183+
grid_box = torch.cat([grid_box, b_b], dim=0)
184+
185+
for x_i in range(x.shape[0]):
186+
xyhw = adv_logits[x_i, :, :4]
187+
prob = torch.max(adv_logits[x_i, :, 5:], dim=1).values
188+
box_idx = adv_logits[x_i, :, 4] * prob > threshold
190189
xyhw = xyhw[box_idx]
191190
c_xyxy = self.xywh2xyxy(xyhw)
192191
scores = box_iou(grid_box, c_xyxy)
@@ -197,20 +196,21 @@ def _loss(self, x: "torch.tensor") -> Tuple["torch.tensor", "torch.tensor"]:
197196
# Increase the weight of the grid with fewer objects
198197
idx_min = torch.argmin(scores)
199198
grid_min = grid_box[idx_min]
200-
x1, y1, x2, y2 = grid_min.int()
201-
pixel_weight[xi, :, y1:y2, x1:x2] = pixel_weight[xi, :, y1:y2, x1:x2] * 2
202-
pixel_weight = pixel_weight / torch.max(pixel_weight[xi, :]) / 255.0
199+
x_1, y_1, x_2, y_2 = grid_min.int()
200+
pixel_weight[x_i, :, y_1:y_2, x_1:x_2] = pixel_weight[x_i, :, y_1:y_2, x_1:x_2] * 2
201+
pixel_weight = pixel_weight / torch.max(pixel_weight[x_i, :]) / 255.0
203202

204203
return ind_loss, pixel_weight
205204

206-
def xywh2xyxy(self, xywh: "torch.tensor") -> "torch.tensor":
205+
@staticmethod
206+
def xywh2xyxy(xywh: "torch.Tensor") -> "torch.Tensor":
207207
"""
208208
Convert the representation from xywh format yo xyxy format.
209209
210-
: param xyhw: A n by 4 boxes store the information in xyhw format
211-
where [x ,y, w h] is [center_x, center_y, width, height]
212-
: return: The n by 4 boxex in xyxy format
213-
where [x1, y1, x2, y2] is [top_left_x, top_left_y, bottom_right_x, bottom_right_y]
210+
:param xyhw: A n by 4 boxes store the information in xyhw format
211+
where [x ,y, w h] is [center_x, center_y, width, height]
212+
:return: The n by 4 boxes in xyxy format
213+
where [x1, y1, x2, y2] is [top_left_x, top_left_y, bottom_right_x, bottom_right_y]
214214
"""
215215
xyxy = xywh.clone()
216216
xyxy[:, 0] = xywh[:, 0] - xywh[:, 2] / 2

requirements_test.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,8 @@ pytest-mock~=3.14.0
6262
pytest-cov~=4.1.0
6363
requests~=2.31.0
6464
ultralytics==8.0.217
65+
ipython==8.25.0
66+
6567
# ART
6668
-e .
6769

tests/attacks/evasion/test_overload_attack.py

Lines changed: 18 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -26,29 +26,25 @@
2626

2727
logger = logging.getLogger(__name__)
2828

29+
2930
@pytest.mark.only_with_platform("pytorch")
3031
def test_generate(art_warning):
3132
try:
3233
import torch
33-
model = torch.hub.load('ultralytics/yolov5:v7.0', model='yolov5s')
34-
py_model = PyTorchYolo(model=model,
35-
input_shape=(3, 640, 640),
36-
channels_first=True)
34+
35+
model = torch.hub.load("ultralytics/yolov5:v7.0", model="yolov5s")
36+
py_model = PyTorchYolo(model=model, input_shape=(3, 640, 640), channels_first=True)
3737
# Download a sample image
3838
import requests
3939
from io import BytesIO
4040
from PIL import Image
4141

42-
TARGET = 'https://ultralytics.com/images/zidane.jpg'
43-
response = requests.get(TARGET)
42+
target = "https://ultralytics.com/images/zidane.jpg"
43+
response = requests.get(target)
4444
org_img = np.asarray(Image.open(BytesIO(response.content)).resize((640, 640)))
4545
x = np.stack([org_img.transpose((2, 0, 1))], axis=0).astype(np.float32)
4646

47-
attack = OverloadPyTorch(py_model,
48-
eps = 16.0 / 255.0,
49-
max_iter = 10,
50-
num_grid = 10,
51-
batch_size = 1)
47+
attack = OverloadPyTorch(py_model, eps=16.0 / 255.0, max_iter=10, num_grid=10, batch_size=1)
5248

5349
x_adv = attack.generate(x / 255.0)
5450
assert x.shape == x_adv.shape
@@ -67,59 +63,26 @@ def test_generate(art_warning):
6763
def test_check_params(art_warning):
6864
try:
6965
import torch
70-
model = torch.hub.load('ultralytics/yolov5:v7.0', model='yolov5s')
71-
py_model = PyTorchYolo(model=model,
72-
input_shape=(3, 640, 640),
73-
channels_first=True)
66+
67+
model = torch.hub.load("ultralytics/yolov5:v7.0", model="yolov5s")
68+
py_model = PyTorchYolo(model=model, input_shape=(3, 640, 640), channels_first=True)
7469

7570
with pytest.raises(ValueError):
76-
_ = OverloadPyTorch(estimator=py_model,
77-
eps=-1.0,
78-
max_iter=5,
79-
num_grid=10,
80-
batch_size=1)
71+
_ = OverloadPyTorch(estimator=py_model, eps=-1.0, max_iter=5, num_grid=10, batch_size=1)
8172
with pytest.raises(ValueError):
82-
_ = OverloadPyTorch(estimator=py_model,
83-
eps=2.0,
84-
max_iter=5,
85-
num_grid=10,
86-
batch_size=1)
73+
_ = OverloadPyTorch(estimator=py_model, eps=2.0, max_iter=5, num_grid=10, batch_size=1)
8774
with pytest.raises(TypeError):
88-
_ = OverloadPyTorch(estimator=py_model,
89-
eps=8 / 255.0,
90-
max_iter=1.0,
91-
num_grid=10,
92-
batch_size=1)
75+
_ = OverloadPyTorch(estimator=py_model, eps=8 / 255.0, max_iter=1.0, num_grid=10, batch_size=1)
9376
with pytest.raises(ValueError):
94-
_ = OverloadPyTorch(estimator=py_model,
95-
eps=8 / 255.0,
96-
max_iter=0,
97-
num_grid=10,
98-
batch_size=1)
77+
_ = OverloadPyTorch(estimator=py_model, eps=8 / 255.0, max_iter=0, num_grid=10, batch_size=1)
9978
with pytest.raises(TypeError):
100-
_ = OverloadPyTorch(estimator=py_model,
101-
eps=8 / 255.0,
102-
max_iter=5,
103-
num_grid=1.0,
104-
batch_size=1)
79+
_ = OverloadPyTorch(estimator=py_model, eps=8 / 255.0, max_iter=5, num_grid=1.0, batch_size=1)
10580
with pytest.raises(ValueError):
106-
_ = OverloadPyTorch(estimator=py_model,
107-
eps=8 / 255.0,
108-
max_iter=5,
109-
num_grid=0,
110-
batch_size=1)
81+
_ = OverloadPyTorch(estimator=py_model, eps=8 / 255.0, max_iter=5, num_grid=0, batch_size=1)
11182
with pytest.raises(TypeError):
112-
_ = OverloadPyTorch(estimator=py_model,
113-
eps=8 / 255.0,
114-
max_iter=5,
115-
num_grid=10,
116-
batch_size=1.0)
83+
_ = OverloadPyTorch(estimator=py_model, eps=8 / 255.0, max_iter=5, num_grid=10, batch_size=1.0)
11784
with pytest.raises(ValueError):
118-
_ = OverloadPyTorch(estimator=py_model,
119-
eps=8 / 255.0,
120-
max_iter=5,
121-
num_grid=0,
122-
batch_size=0)
85+
_ = OverloadPyTorch(estimator=py_model, eps=8 / 255.0, max_iter=5, num_grid=0, batch_size=0)
12386

12487
except ARTTestException as e:
12588
art_warning(e)

0 commit comments

Comments
 (0)