File size: 16,523 Bytes
7a5fdce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# function/attack/attack_api_det.py
"""
Detection attack helpers - detection-specific attack interface for YOLOv7-like models.

(修改点:_save_adv_tensor 支持 ref_path,用于保持原图片的格式与尺寸;generate() 在保存时传入 ref_path)
"""
import os
from pathlib import Path
from typing import List, Optional, Tuple
import numpy as np
from PIL import Image
import torch
import torch.nn.functional as F

# Optional imports from yolov7 utils (letterbox / nms). If missing, use simple fallback.
try:
    from utils.datasets import letterbox
    from utils.general import non_max_suppression
    _HAS_YOLO_UTILS = True
except Exception:
    _HAS_YOLO_UTILS = False

# -------------------------
# Helpers: image <-> tensor
# -------------------------
def _letterbox_to_tensor(path: str, img_size: int = 640, device='cpu') -> Tuple[torch.Tensor, Tuple[int,int], Tuple[int,int,int]]:
    img0 = Image.open(path).convert('RGB')
    w0, h0 = img0.size

    if _HAS_YOLO_UTILS:
        np_img = np.array(img0)
        img_lb, ratio, (dw, dh) = letterbox(np_img, new_shape=img_size)
        img_arr = img_lb
        try:
            r = float(ratio) if ratio is not None else min(img_size / h0, img_size / w0)
        except:
            r = min(img_size / h0, img_size / w0)
    else:
        r = min(img_size / h0, img_size / w0)
        new_w, new_h = int(w0 * r), int(h0 * r)
        img_resized = img0.resize((new_w, new_h), Image.BILINEAR)
        canvas = Image.new('RGB', (img_size, img_size), (114, 114, 114))
        dw = (img_size - new_w) // 2
        dh = (img_size - new_h) // 2
        canvas.paste(img_resized, (dw, dh))
        img_arr = np.array(canvas)

    img_bgr = img_arr[:, :, ::-1].transpose(2, 0, 1).copy()
    tensor = torch.from_numpy(img_bgr).float().unsqueeze(0) / 255.0  # 1,C,H,W
    return tensor.to(device), (w0, h0), (int(dw) if 'dw' in locals() else 0, int(dh) if 'dh' in locals() else 0, float(r))

def _tensor_to_pil_rgb(tensor_bchw: torch.Tensor) -> Image.Image:
    arr = (tensor_bchw.detach().cpu().squeeze(0).permute(1, 2, 0).numpy() * 255.0).round().astype('uint8')  # HWC BGR
    arr = arr[:, :, ::-1]  # to RGB
    return Image.fromarray(arr)

# -------------------------
# DetectionEvasionAttacker
# -------------------------
class DetectionEvasionAttacker:
    def __init__(self, model: torch.nn.Module, device: str = 'cuda:0', nc: int = 5, img_size: int = 640, verbose: bool = False):
        self.device = torch.device(device if isinstance(device, str) else device)
        self.model = model.to(self.device)
        self.nc = int(nc)
        self.img_size = int(img_size)
        self.verbose = verbose

    def _model_dtype(self):
        try:
            return next(self.model.parameters()).dtype
        except StopIteration:
            return torch.float32

    def _align_tensor_dtype(self, x: torch.Tensor) -> torch.Tensor:
        x = x.to(self.device)
        target_dtype = self._model_dtype()
        if x.dtype != target_dtype:
            x = x.to(dtype=target_dtype)
        return x

    def _preds_forward(self, imgs: torch.Tensor) -> torch.Tensor:
        imgs = self._align_tensor_dtype(imgs)
        out = self.model(imgs)
        if isinstance(out, (tuple, list)):
            preds = out[0]
        else:
            preds = out
        if torch.is_tensor(preds):
            return preds
        try:
            return torch.stack(preds, dim=0).to(self.device)
        except Exception as e:
            raise RuntimeError(f"Cannot parse model(...) output as preds tensor: {e}")

    def _try_loss_forward(self, imgs: torch.Tensor, targets) -> torch.Tensor:
        imgs = self._align_tensor_dtype(imgs)
        out = self.model(imgs, targets)
        if isinstance(out, (tuple, list)) and len(out) >= 1 and torch.is_tensor(out[0]):
            return out[0]
        if isinstance(out, dict) and 'loss' in out:
            return out['loss']
        raise RuntimeError("Model does not return training loss via model(imgs, targets).")

    def _proxy_loss_from_preds(self, preds: torch.Tensor) -> torch.Tensor:
        if preds is None:
            return torch.tensor(0.0, device=self.device)
        if preds.ndim == 3 and preds.shape[-1] >= 6:
            obj = preds[..., 4].unsqueeze(-1)
            cls_scores = preds[..., 5:5 + self.nc]
            cls_prob = torch.softmax(cls_scores, dim=-1)
            per_box = obj * cls_prob
            per_image = per_box.sum(dim=1)
            loss = per_image.sum()
            return loss
        return preds.sum()

    def generate_fgsm_from_loss(self, imgs: torch.Tensor, targets, eps: float = 8/255.0) -> torch.Tensor:
        self.model.train()
        imgs = imgs.to(self.device)
        imgs = self._align_tensor_dtype(imgs)
        orig = imgs.detach().clone()
        adv = orig.clone().detach().requires_grad_(True)
        loss = self._try_loss_forward(adv, targets)
        loss.backward()
        grad = adv.grad.detach()
        adv = adv + eps * grad.sign()
        adv = torch.max(torch.min(adv, orig + eps), orig - eps)
        adv = torch.clamp(adv, 0.0, 1.0)
        return adv.detach()

    def generate_pgd_from_loss(self, imgs: torch.Tensor, targets, eps: float = 8/255.0, alpha: float = 2/255.0, iters: int = 10, random_start: bool = True) -> torch.Tensor:
        self.model.train()
        imgs = imgs.to(self.device)
        imgs = self._align_tensor_dtype(imgs)
        orig = imgs.detach().clone()
        if random_start:
            adv = orig + (torch.rand_like(orig) * 2 - 1) * eps
        else:
            adv = orig.clone()
        adv = torch.clamp(adv, 0.0, 1.0).detach().requires_grad_(True)
        for i in range(iters):
            if adv.grad is not None:
                adv.grad.zero_()
            loss = self._try_loss_forward(adv, targets)
            loss.backward()
            grad = adv.grad.detach()
            adv = adv + alpha * grad.sign()
            adv = torch.max(torch.min(adv, orig + eps), orig - eps)
            adv = torch.clamp(adv, 0.0, 1.0).detach().requires_grad_(True)
            if self.verbose and i % 5 == 0:
                try:
                    print(f"[PGD loss] iter {i} loss {loss.item():.4f}")
                except:
                    pass
        return adv.detach()

    def generate_fgsm_proxy(self, imgs: torch.Tensor, eps: float = 8/255.0) -> torch.Tensor:
        self.model.eval()
        imgs = imgs.to(self.device)
        imgs = self._align_tensor_dtype(imgs)
        orig = imgs.detach().clone()
        adv = orig.clone().detach().requires_grad_(True)
        preds = self._preds_forward(adv)
        loss = self._proxy_loss_from_preds(preds)
        loss.backward()
        grad = adv.grad.detach()
        adv = adv - eps * grad.sign()
        adv = torch.max(torch.min(adv, orig + eps), orig - eps)
        adv = torch.clamp(adv, 0.0, 1.0)
        return adv.detach()

    def generate_pgd_proxy(self, imgs: torch.Tensor, eps: float = 8/255.0, alpha: float = 2/255.0, iters: int = 10, random_start: bool = True) -> torch.Tensor:
        self.model.eval()
        imgs = imgs.to(self.device)
        imgs = self._align_tensor_dtype(imgs)
        orig = imgs.detach().clone()
        if random_start:
            adv = orig + (torch.rand_like(orig) * 2 - 1) * eps
        else:
            adv = orig.clone()
        adv = torch.clamp(adv, 0.0, 1.0).detach().requires_grad_(True)
        for i in range(iters):
            if adv.grad is not None:
                adv.grad.zero_()
            preds = self._preds_forward(adv)
            loss = self._proxy_loss_from_preds(preds)
            loss.backward()
            grad = adv.grad.detach()
            adv = adv - alpha * grad.sign()
            adv = torch.max(torch.min(adv, orig + eps), orig - eps)
            adv = torch.clamp(adv, 0.0, 1.0).detach().requires_grad_(True)
            if self.verbose and i % 5 == 0:
                try:
                    print(f"[PGD proxy] iter {i} loss {loss.item():.4f}")
                except:
                    pass
        return adv.detach()

    # -------------------------
    # Batch helpers & generate API
    # -------------------------
    def _save_adv_tensor(self, tensor: torch.Tensor, out_path: str, ref_path: Optional[str] = None):
        """
        Save adv tensor (1,C,H,W) as an image.
        If ref_path is provided, mimic ref image's size & format (e.g., JPEG 448x416).
        """
        pil = _tensor_to_pil_rgb(tensor)  # PIL RGB
        # If a reference image provided, try to read its format/size/mode
        target_size = None
        target_format = None
        try:
            if ref_path is not None and os.path.exists(ref_path):
                ref_im = Image.open(ref_path)
                target_format = ref_im.format  # e.g., 'JPEG' or 'PNG'
                target_size = ref_im.size  # (W,H)
        except Exception:
            target_format = None
            target_size = None

        if target_size is not None:
            # resize to reference size (width, height)
            pil = pil.resize(target_size, Image.BILINEAR)

        # Ensure directory exists
        os.makedirs(os.path.dirname(out_path), exist_ok=True)
        # Decide save format by reference or by extension
        ext = Path(out_path).suffix.lower()
        fmt = None
        if target_format:
            fmt = target_format.upper()
        else:
            if ext in ('.jpg', '.jpeg'):
                fmt = 'JPEG'
            elif ext in ('.png',):
                fmt = 'PNG'
            else:
                fmt = 'PNG'

        # Save accordingly
        if fmt == 'JPEG':
            pil.save(out_path, format='JPEG', quality=95)
        else:
            pil.save(out_path, format=fmt)

    def generate(self, method: str = "FGSM",
             img_paths: Optional[List[str]] = None,
             source_folder: Optional[str] = None,
             save_path: Optional[str] = None,
             batch: int = 4,
             img_size: int = None,
             use_loss: bool = False,
             targets_list: Optional[List] = None,
             **kwargs):
        """
        General generate API supporting multiple methods and per-method kwargs.

        Parameters of interest in kwargs:
        - eps (float)
        - alpha (float)
        - iters/int (int)
        - random_start (bool)
        - norm ('inf','2','1')
        - other method-specific params forwarded.

        img_paths: if provided, use this list (preferred).
        source_folder: fallback to read all images from folder.
        """
        if img_paths is None:
            if source_folder:
                p = Path(source_folder)
                img_paths = sorted([str(x) for x in p.glob('*') if x.suffix.lower() in ('.jpg','.jpeg','.png')])
            else:
                raise ValueError("Either img_paths or source_folder must be provided")
        # clip / cast
        if img_size is None:
            img_size = self.img_size
        else:
            img_size = int(img_size)

        method_key = method.upper()
        # default args
        eps = float(kwargs.get('eps', kwargs.get('epsilon', 8/255.0)))
        alpha = float(kwargs.get('alpha', 2/255.0))
        iters = int(kwargs.get('iters', kwargs.get('steps', 10)))
        random_start = bool(kwargs.get('random_start', True))
        norm = str(kwargs.get('norm', 'inf')).lower()

        # Prepare image list
        if len(img_paths) == 0:
            raise ValueError("No images to attack")
        piclist = []
        advs = []

        # helper to chunk
        for i in range(0, len(img_paths), batch):
            batch_paths = img_paths[i:i + batch]
            batch_tensors = []
            for pth in batch_paths:
                t, _, _ = _letterbox_to_tensor(pth, img_size=img_size, device=self.device)
                t = t.float()
                batch_tensors.append(t.squeeze(0))
            x = torch.stack(batch_tensors, dim=0)  # B,C,H,W

            # Choose implementation
            try:
                if method_key in ("FGSM", "FFGSM"):
                    if use_loss and targets_list:
                        adv = self.generate_fgsm_from_loss(x, targets_list[i:i+batch], eps=eps)
                    else:
                        adv = self.generate_fgsm_proxy(x, eps=eps)
                elif method_key in ("PGD", "PGDL", "BIM", "IFGSM", "I-FGSM", "BASIC_ITERATIVE"):
                    # PGD-like attacks: use proxy or loss versions
                    if use_loss and targets_list:
                        adv = self.generate_pgd_from_loss(x, targets_list[i:i+batch], eps=eps, alpha=alpha, iters=iters, random_start=random_start)
                    else:
                        adv = self.generate_pgd_proxy(x, eps=eps, alpha=alpha, iters=iters, random_start=random_start)
                elif method_key in ("CW", "C&W", "CARLINI", "CARLINI-WAGNER"):
                    try:
                        import torchattacks
                        atk = torchattacks.CW(self.model, c=kwargs.get('c', 1e-3), kappa=kwargs.get('kappa', 0), steps=kwargs.get('cw_steps', 1000))
                        adv = atk(x, torch.zeros(x.size(0), dtype=torch.long, device=self.device))
                    except Exception as e:
                        raise RuntimeError("C&W attack requires 'torchattacks' package or custom implementation. "
                                        "Fallback: use PGD-from-loss for detection models. Error: " + str(e))
                elif method_key in ("DEEPLF", "DEEPOF", "DEEPLFOOL", "DEEPFOOL"):
                    try:
                        import torchattacks
                        atk = torchattacks.DeepFool(self.model)
                        adv = atk(x, torch.zeros(x.size(0), dtype=torch.long, device=self.device))
                    except Exception as e:
                        raise RuntimeError("DeepFool requires 'torchattacks' or custom impl. Fallback use PGD-from-loss.")
                elif method_key in ("AUTOATTACK", "AUTO"):
                    try:
                        import torchattacks
                        atk = torchattacks.AutoAttack(self.model)
                        adv = atk(x, torch.zeros(x.size(0), dtype=torch.long, device=self.device))
                    except Exception as e:
                        raise RuntimeError("AutoAttack requires 'torchattacks' package. Fallback: use PGD.")
                else:
                    # default fallback: PGD proxy
                    if use_loss and targets_list:
                        adv = self.generate_pgd_from_loss(x, targets_list[i:i+batch], eps=eps, alpha=alpha, iters=iters, random_start=random_start)
                    else:
                        adv = self.generate_pgd_proxy(x, eps=eps, alpha=alpha, iters=iters, random_start=random_start)
            except Exception as e:
                raise RuntimeError(f"Attack generation failed for method {method_key} on batch starting at {i}: {e}")

            # save adv images if requested (preserve ref)
            for bi, pth in enumerate(batch_paths):
                tensor_single = adv[bi:bi + 1]  # 1,C,H,W
                if save_path:
                    orig_ext = Path(pth).suffix.lower()
                    fname = Path(pth).stem + f"_adv_{method_key}" + orig_ext
                    outp = os.path.join(save_path, fname)
                    # Save adversarial image
                    self._save_adv_tensor(tensor_single, outp, ref_path=pth)
                    piclist.append(outp)

                    # Calculate and save the perturbation to /jjs_tmp/perturbation/
                    orig_tensor, _, _ = _letterbox_to_tensor(pth, img_size=img_size, device=self.device)
                    perturbation = tensor_single - orig_tensor  # Calculate perturbation
                    perturbation_dir = "jjs_tmp/perturbation/"  # Specify the directory
                    os.makedirs(perturbation_dir, exist_ok=True)  # Ensure directory exists
                    perturbation_path = os.path.join(perturbation_dir, f"{Path(pth).stem}_perturbation.bin")
                    perturbation.detach().cpu().numpy().tofile(perturbation_path)
                    #np.save(perturbation_path, perturbation.detach().cpu().numpy())  # Save perturbation as .npy
                advs.append(tensor_single.detach().cpu().numpy())

        adv_np = np.concatenate(advs, axis=0) if advs else np.zeros((0,3,img_size,img_size), dtype=np.float32)
        return adv_np, None, piclist