Spaces:
Sleeping
Sleeping
MarshallCN commited on
Commit ·
ca697b6
1
Parent(s): 7246f36
track images with git-lfs
Browse files- .gitignore +10 -0
- app.py +291 -0
- app_old.py +197 -0
- attacks.py +286 -0
- federated_utils.py +98 -0
- images/train/c1.png +3 -0
- images/train/c2.png +3 -0
- images/train/c3.png +3 -0
- images/train/c4.png +3 -0
- requirements.txt +13 -0
- weights/fed_model2.pt +3 -0
- weights/yolov8s_3cls.pt +3 -0
.gitignore
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Local/*
|
| 2 |
+
labels/*
|
| 3 |
+
Adversarial_attack.ipynb
|
| 4 |
+
Drone_VisDrone.ipynb
|
| 5 |
+
AdvTest.ipynb
|
| 6 |
+
*.pyc
|
| 7 |
+
*checkpoint*
|
| 8 |
+
*checkpoint*/
|
| 9 |
+
**/.ipynb_checkpoints/
|
| 10 |
+
*-checkpoint.*
|
app.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import numpy as np
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import torch
|
| 6 |
+
from ultralytics import YOLO
|
| 7 |
+
import cv2
|
| 8 |
+
import attacks # 上面那个 attacks.py,确保和 app.py 在同一目录或可 import 的包路径
|
| 9 |
+
import os, glob
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# MODEL_PATH = "weights/yolov8s_3cls.pt"
|
| 13 |
+
MODEL_PATH = "weights/fed_model2.pt"
|
| 14 |
+
MODEL_PATH_C = "weights/yolov8s_3cls.pt"
|
| 15 |
+
|
| 16 |
+
names = ['car', 'van', 'truck']
|
| 17 |
+
imgsz = 640
|
| 18 |
+
|
| 19 |
+
SAMPLE_DIR = "./images/train"
|
| 20 |
+
SAMPLE_IMAGES = sorted([
|
| 21 |
+
p for p in glob.glob(os.path.join(SAMPLE_DIR, "*"))
|
| 22 |
+
if os.path.splitext(p)[1].lower() in [".jpg", ".jpeg", ".png", ".bmp", ".webp"]
|
| 23 |
+
])[:4] # 只取前4张
|
| 24 |
+
|
| 25 |
+
# Load ultralytics model (wrapper)
|
| 26 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 27 |
+
yolom = YOLO(MODEL_PATH) # wrapper
|
| 28 |
+
# yolom_c = YOLO(MODEL_PATH_C) # wrapper
|
| 29 |
+
# put underlying module to eval on correct device might be needed in attacks functions
|
| 30 |
+
|
| 31 |
+
# def run_detection_on_pil(img_pil: Image.Image, eval_model_state, conf: float = 0.45):
|
| 32 |
+
# """
|
| 33 |
+
# Use ultralytics wrapper predict to get a visualization image with boxes.
|
| 34 |
+
# This is inference-only and does not require gradient.
|
| 35 |
+
# """
|
| 36 |
+
# # ultralytics accepts numpy array (H,W,3) in RGB, we pass it directly
|
| 37 |
+
# img = np.array(img_pil)
|
| 38 |
+
# # use model.predict with verbose=False to avoid prints
|
| 39 |
+
# eva_model = yolom if eval_model_state == "yolom" else YOLO(MODEL_PATH_C)
|
| 40 |
+
# res = eva_model.predict(source=img, conf=conf, imgsz=imgsz, save=False, verbose=False)
|
| 41 |
+
# r = res[0]
|
| 42 |
+
# im_out = img.copy()
|
| 43 |
+
# # Boxes object may be empty
|
| 44 |
+
# try:
|
| 45 |
+
# boxes = r.boxes
|
| 46 |
+
# for box in boxes:
|
| 47 |
+
# xyxy = box.xyxy[0].cpu().numpy().astype(int)
|
| 48 |
+
# x1, y1, x2, y2 = map(int, xyxy)
|
| 49 |
+
# conf_score = float(box.conf[0].cpu().numpy())
|
| 50 |
+
# cls_id = int(box.cls[0].cpu().numpy())
|
| 51 |
+
# # label = f"{cls_id}:{conf_score:.2f}"
|
| 52 |
+
# label = f"{names[cls_id]}:{conf_score:.2f}"
|
| 53 |
+
# cv2.rectangle(im_out, (x1, y1), (x2, y2), (0,255,0), 2)
|
| 54 |
+
# cv2.putText(im_out, label, (x1, max(10,y1-5)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 1)
|
| 55 |
+
# except Exception as e:
|
| 56 |
+
# # if no boxes or structure unexpected, just return original
|
| 57 |
+
# pass
|
| 58 |
+
# return Image.fromarray(im_out)
|
| 59 |
+
def iou(a, b):
|
| 60 |
+
ax1, ay1, ax2, ay2 = a
|
| 61 |
+
bx1, by1, bx2, by2 = b
|
| 62 |
+
iw = max(0, min(ax2, bx2) - max(ax1, bx1))
|
| 63 |
+
ih = max(0, min(ay2, by2) - max(ay1, by1))
|
| 64 |
+
inter = iw * ih
|
| 65 |
+
if inter <= 0:
|
| 66 |
+
return 0.0
|
| 67 |
+
area_a = max(0, ax2 - ax1) * max(0, ay2 - ay1)
|
| 68 |
+
area_b = max(0, bx2 - bx1) * max(0, by2 - by1)
|
| 69 |
+
return inter / (area_a + area_b - inter + 1e-9)
|
| 70 |
+
|
| 71 |
+
# def center_and_diag(b): #IOU足够好 未启用
|
| 72 |
+
# x1, y1, x2, y2 = b
|
| 73 |
+
# cx = 0.5 * (x1 + x2); cy = 0.5 * (y1 + y2)
|
| 74 |
+
# diag = max(1e-9, ((x2 - x1)**2 + (y2 - y1)**2)**0.5)
|
| 75 |
+
# area = max(0, (x2 - x1)) * max(0, (y2 - y1))
|
| 76 |
+
# return cx, cy, diag, area
|
| 77 |
+
|
| 78 |
+
def run_detection_on_pil(img_pil: Image.Image, eval_model_state, conf: float = 0.45, GT_boxes=None):
|
| 79 |
+
"""
|
| 80 |
+
推理+可视化。GT_boxes 和返回的 preds 都是:
|
| 81 |
+
[{'xyxy': (x1,y1,x2,y2), 'cls': int, 'conf': float(optional)}]
|
| 82 |
+
"""
|
| 83 |
+
import numpy as np, cv2, math
|
| 84 |
+
from ultralytics import YOLO
|
| 85 |
+
|
| 86 |
+
# ---- 1) 推理 ----
|
| 87 |
+
img = np.array(img_pil)
|
| 88 |
+
eva_model = yolom if eval_model_state == "yolom" else YOLO(MODEL_PATH_C)
|
| 89 |
+
res = eva_model.predict(source=img, conf=conf, imgsz=imgsz, save=False, verbose=False)
|
| 90 |
+
r = res[0]
|
| 91 |
+
im_out = img.copy()
|
| 92 |
+
|
| 93 |
+
# 名称表(尽量稳)
|
| 94 |
+
names = getattr(r, "names", None)
|
| 95 |
+
if names is None and hasattr(eva_model, "model") and hasattr(eva_model.model, "names"):
|
| 96 |
+
names = eva_model.model.names
|
| 97 |
+
|
| 98 |
+
# ---- 2) 规整预测框到简单结构 ----
|
| 99 |
+
preds = []
|
| 100 |
+
try:
|
| 101 |
+
bxs = r.boxes
|
| 102 |
+
if bxs is not None and len(bxs) > 0:
|
| 103 |
+
for b in bxs:
|
| 104 |
+
xyxy = b.xyxy[0].detach().cpu().numpy().tolist()
|
| 105 |
+
x1, y1, x2, y2 = [int(v) for v in xyxy]
|
| 106 |
+
cls_id = int(b.cls[0].detach().cpu().numpy())
|
| 107 |
+
conf_score = float(b.conf[0].detach().cpu().numpy())
|
| 108 |
+
preds.append({'xyxy': (x1, y1, x2, y2), 'cls': cls_id, 'conf': conf_score})
|
| 109 |
+
except Exception as e:
|
| 110 |
+
print("collect preds error:", e)
|
| 111 |
+
|
| 112 |
+
# ---- 3) IoU 匹配 + 画框 ----
|
| 113 |
+
IOU_THR = 0.3
|
| 114 |
+
# CENTER_DIST_RATIO = 0.30 # 中心点距离 / 预测框对角线 <= 0.30 即视为同一目标
|
| 115 |
+
# AREA_RATIO_THR = 0.25 # 面积比例下限:min(area_p, area_g) / max(...) >= 0.25
|
| 116 |
+
gt_used = set()
|
| 117 |
+
|
| 118 |
+
for p in preds:
|
| 119 |
+
color = (0, 255, 0) # 同类:绿
|
| 120 |
+
px1, py1, px2, py2 = p['xyxy']
|
| 121 |
+
pname = names[p['cls']] if (names is not None and p['cls'] in getattr(names, 'keys', lambda: [])()) else (
|
| 122 |
+
names[p['cls']] if (isinstance(names, (list, tuple)) and 0 <= p['cls'] < len(names)) else str(p['cls'])
|
| 123 |
+
)
|
| 124 |
+
label = f"{pname}:{p.get('conf', 0.0):.2f}"
|
| 125 |
+
|
| 126 |
+
if GT_boxes != None:
|
| 127 |
+
# 找 IoU 最高的未用 GT
|
| 128 |
+
best_j, best_iou = -1, 0.0
|
| 129 |
+
for j, g in enumerate(GT_boxes):
|
| 130 |
+
if j in gt_used:
|
| 131 |
+
continue
|
| 132 |
+
i = iou(p['xyxy'], g['xyxy'])
|
| 133 |
+
if i > best_iou:
|
| 134 |
+
best_iou, best_j = i, j
|
| 135 |
+
|
| 136 |
+
# 颜色规则:匹配且同类=绿;匹配但异类=红;
|
| 137 |
+
if best_iou >= IOU_THR:
|
| 138 |
+
gt_used.add(best_j)
|
| 139 |
+
if p['cls'] != int(GT_boxes[best_j]['cls']):
|
| 140 |
+
color = (255, 0, 0) # 异类:红
|
| 141 |
+
|
| 142 |
+
cv2.rectangle(im_out, (px1, py1), (px2, py2), color, 2)
|
| 143 |
+
cv2.putText(im_out, label, (px1, max(10, py1 - 5)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1)
|
| 144 |
+
|
| 145 |
+
return Image.fromarray(im_out), preds
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def detect_and_attack(image, eval_model_state, attack_mode, eps, alpha, iters, conf):
|
| 149 |
+
if image is None:
|
| 150 |
+
return None, None
|
| 151 |
+
|
| 152 |
+
pil = Image.fromarray(image.astype('uint8'), 'RGB')
|
| 153 |
+
|
| 154 |
+
original_vis, GT_boxes = run_detection_on_pil(pil, eval_model_state, conf=conf, GT_boxes=None)
|
| 155 |
+
|
| 156 |
+
if attack_mode == "none":
|
| 157 |
+
return original_vis, None
|
| 158 |
+
|
| 159 |
+
try:
|
| 160 |
+
if attack_mode == "fgsm":
|
| 161 |
+
adv_pil = attacks.fgsm_attack_on_detector(yolom, pil, eps=eps, device=device, imgsz=imgsz)
|
| 162 |
+
elif attack_mode == "pgd":
|
| 163 |
+
adv_pil = attacks.pgd_attack_on_detector(yolom, pil, eps=eps, alpha=alpha, iters=iters, device=device, imgsz=imgsz)
|
| 164 |
+
else:
|
| 165 |
+
adv_pil = attacks.demo_random_perturbation(pil, eps=eps)
|
| 166 |
+
except Exception as ex:
|
| 167 |
+
print("Whitebox attack failed:", ex)
|
| 168 |
+
adv_pil = attacks.demo_random_perturbation(pil, eps=eps)
|
| 169 |
+
|
| 170 |
+
adv_vis, _ = run_detection_on_pil(adv_pil, eval_model_state, conf=conf, GT_boxes=GT_boxes)
|
| 171 |
+
return original_vis, adv_vis
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
# Gradio UI
|
| 175 |
+
if __name__ == "__main__":
|
| 176 |
+
title = "Federated Adversarial Attack — FGSM/PGD Demo"
|
| 177 |
+
desc_html = (
|
| 178 |
+
"Adversarial examples are generated locally using a "
|
| 179 |
+
"<strong>client-side</strong> model’s gradients (white-box), then evaluated against the "
|
| 180 |
+
"<strong>server-side aggregated (FedAvg) central model</strong>. "
|
| 181 |
+
"If the perturbation transfers, it can "
|
| 182 |
+
"degrade or alter the FedAvg model’s predictions on the same input image."
|
| 183 |
+
)
|
| 184 |
+
with gr.Blocks(title=title) as demo:
|
| 185 |
+
# 标题居中
|
| 186 |
+
gr.Markdown(f"""
|
| 187 |
+
<div>
|
| 188 |
+
<h1 style='text-align:center;margin-bottom:0.2rem'>{title}</h1>
|
| 189 |
+
<p style='opacity:0.85'>{desc_html}</p>
|
| 190 |
+
</div>""")
|
| 191 |
+
|
| 192 |
+
with gr.Row():
|
| 193 |
+
# ===== 左列:两个输入区块 =====
|
| 194 |
+
with gr.Column(scale=5):
|
| 195 |
+
# 输入区块 1:上传窗口 & 样例选择 —— 左右并列
|
| 196 |
+
with gr.Row():
|
| 197 |
+
with gr.Column(scale=7):
|
| 198 |
+
in_img = gr.Image(type="numpy", label="Input image")
|
| 199 |
+
with gr.Column(scale=2):
|
| 200 |
+
if SAMPLE_IMAGES:
|
| 201 |
+
gr.Examples(
|
| 202 |
+
examples=SAMPLE_IMAGES,
|
| 203 |
+
inputs=[in_img],
|
| 204 |
+
label=f"Select from sample images",
|
| 205 |
+
examples_per_page=4,
|
| 206 |
+
# run_on_click 默认为 False(只填充,不执行)
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
# 输入 2:攻击与参数
|
| 210 |
+
with gr.Accordion("Attack mode", open=True):
|
| 211 |
+
attack_mode = gr.Radio(
|
| 212 |
+
choices=["none", "fgsm", "pgd", "random noise"],
|
| 213 |
+
value="fgsm",
|
| 214 |
+
label="",
|
| 215 |
+
show_label=False
|
| 216 |
+
)
|
| 217 |
+
eps = gr.Slider(0.0, 0.3, step=0.01, value=0.0314, label="eps")
|
| 218 |
+
alpha = gr.Slider(0.001, 0.05, step=0.001, value=0.0078, label="alpha (PGD step)")
|
| 219 |
+
iters = gr.Slider(1, 100, step=1, value=10, label="PGD iterations")
|
| 220 |
+
conf = gr.Slider(0.0, 1.0, step=0.01, value=0.45, label="Confidence threshold (live)")
|
| 221 |
+
|
| 222 |
+
with gr.Row():
|
| 223 |
+
btn_clear = gr.ClearButton(
|
| 224 |
+
components=[in_img, eps, alpha, iters, conf], # 不清空 attack_mode
|
| 225 |
+
value="Clear"
|
| 226 |
+
)
|
| 227 |
+
btn_submit = gr.Button("Submit", variant="primary")
|
| 228 |
+
|
| 229 |
+
# ===== 右列:两个输出区块 =====
|
| 230 |
+
with gr.Column(scale=5):
|
| 231 |
+
# 新增:评测模型选择
|
| 232 |
+
with gr.Row():
|
| 233 |
+
eval_choice = gr.Dropdown(
|
| 234 |
+
choices=[(f"Client model {MODEL_PATH}", "client"),
|
| 235 |
+
(f"Central model {MODEL_PATH_C}", "central")],
|
| 236 |
+
value="client", # ★ 初始值为合法 value
|
| 237 |
+
label="Evaluation model"
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
eval_model_state = gr.State(value="yolom")
|
| 241 |
+
|
| 242 |
+
# ★ 合并后的单一回调:规范化下拉值 + 返回(更新后的下拉值, 模型对象)
|
| 243 |
+
def on_eval_change(val: str):
|
| 244 |
+
if isinstance(val, (list, tuple)):
|
| 245 |
+
val = val[0] if len(val) else "client"
|
| 246 |
+
if val not in ("client", "central"):
|
| 247 |
+
val = "client"
|
| 248 |
+
model = "yolom" if val == "client" else "yolom_c"
|
| 249 |
+
return gr.update(value=val), model
|
| 250 |
+
|
| 251 |
+
# 页面加载时同步一次,避免初次为空/不一致
|
| 252 |
+
demo.load(
|
| 253 |
+
fn=on_eval_change,
|
| 254 |
+
inputs=eval_choice,
|
| 255 |
+
outputs=[eval_choice, eval_model_state]
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
# 仅这一条 change 绑定(删掉你原来那个只写 State 的 change,避免并发覆盖)
|
| 259 |
+
eval_choice.change(
|
| 260 |
+
fn=on_eval_change,
|
| 261 |
+
inputs=eval_choice,
|
| 262 |
+
outputs=[eval_choice, eval_model_state]
|
| 263 |
+
)
|
| 264 |
+
out_orig = gr.Image(label="Original detection")
|
| 265 |
+
out_adv = gr.Image(label="After attack detection")
|
| 266 |
+
|
| 267 |
+
# Submit:手动运行
|
| 268 |
+
btn_submit.click(
|
| 269 |
+
fn=detect_and_attack,
|
| 270 |
+
inputs=[in_img, eval_model_state, attack_mode, eps, alpha, iters, conf],
|
| 271 |
+
outputs=[out_orig, out_adv]
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
# 仅 conf 滑块“实时”
|
| 275 |
+
conf.release(
|
| 276 |
+
fn=detect_and_attack,
|
| 277 |
+
inputs=[in_img, eval_model_state, attack_mode, eps, alpha, iters, conf],
|
| 278 |
+
outputs=[out_orig, out_adv]
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
demo.queue(default_concurrency_limit=2, max_size=20)
|
| 282 |
+
if os.getenv("SPACE_ID"):
|
| 283 |
+
demo.launch(
|
| 284 |
+
server_name="0.0.0.0",
|
| 285 |
+
server_port=int(os.getenv("PORT", 7860)),
|
| 286 |
+
show_error=True,
|
| 287 |
+
)
|
| 288 |
+
else:
|
| 289 |
+
demo.launch(share=True)
|
| 290 |
+
|
| 291 |
+
|
app_old.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
from ultralytics import YOLO
|
| 7 |
+
import cv2
|
| 8 |
+
import attacks # 上面那个 attacks.py,确保和 app.py 在同一目录或可 import 的包路径
|
| 9 |
+
import os, glob
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# MODEL_PATH = "weights/yolov8s_3cls.pt"
|
| 13 |
+
MODEL_PATH = "weights/fed_model2.pt"
|
| 14 |
+
MODEL_PATH_C = "weights/yolov8s_3cls.pt"
|
| 15 |
+
|
| 16 |
+
names = ['car', 'van', 'truck']
|
| 17 |
+
imgsz = 640
|
| 18 |
+
|
| 19 |
+
SAMPLE_DIR = "./images/train"
|
| 20 |
+
SAMPLE_IMAGES = sorted([
|
| 21 |
+
p for p in glob.glob(os.path.join(SAMPLE_DIR, "*"))
|
| 22 |
+
if os.path.splitext(p)[1].lower() in [".jpg", ".jpeg", ".png", ".bmp", ".webp"]
|
| 23 |
+
])[:4] # 只取前4张
|
| 24 |
+
|
| 25 |
+
# Load ultralytics model (wrapper)
|
| 26 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 27 |
+
yolom = YOLO(MODEL_PATH) # wrapper
|
| 28 |
+
# yolom_c = YOLO(MODEL_PATH_C) # wrapper
|
| 29 |
+
# put underlying module to eval on correct device might be needed in attacks functions
|
| 30 |
+
|
| 31 |
+
def run_detection_on_pil(img_pil: Image.Image, eval_model_state, conf: float = 0.45):
|
| 32 |
+
"""
|
| 33 |
+
Use ultralytics wrapper predict to get a visualization image with boxes.
|
| 34 |
+
This is inference-only and does not require gradient.
|
| 35 |
+
"""
|
| 36 |
+
# ultralytics accepts numpy array (H,W,3) in RGB, we pass it directly
|
| 37 |
+
img = np.array(img_pil)
|
| 38 |
+
# use model.predict with verbose=False to avoid prints
|
| 39 |
+
eva_model = yolom if eval_model_state == "yolom" else YOLO(MODEL_PATH_C)
|
| 40 |
+
res = eva_model.predict(source=img, conf=conf, imgsz=imgsz, save=False, verbose=False)
|
| 41 |
+
r = res[0]
|
| 42 |
+
im_out = img.copy()
|
| 43 |
+
# Boxes object may be empty
|
| 44 |
+
try:
|
| 45 |
+
boxes = r.boxes
|
| 46 |
+
for box in boxes:
|
| 47 |
+
xyxy = box.xyxy[0].cpu().numpy().astype(int)
|
| 48 |
+
x1, y1, x2, y2 = map(int, xyxy)
|
| 49 |
+
conf_score = float(box.conf[0].cpu().numpy())
|
| 50 |
+
cls_id = int(box.cls[0].cpu().numpy())
|
| 51 |
+
# label = f"{cls_id}:{conf_score:.2f}"
|
| 52 |
+
label = f"{names[cls_id]}:{conf_score:.2f}"
|
| 53 |
+
cv2.rectangle(im_out, (x1, y1), (x2, y2), (0,255,0), 2)
|
| 54 |
+
cv2.putText(im_out, label, (x1, max(10,y1-5)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 1)
|
| 55 |
+
except Exception as e:
|
| 56 |
+
# if no boxes or structure unexpected, just return original
|
| 57 |
+
pass
|
| 58 |
+
return Image.fromarray(im_out)
|
| 59 |
+
|
| 60 |
+
def detect_and_attack(image, eval_model_state, attack_mode, eps, alpha, iters, conf):
|
| 61 |
+
if image is None:
|
| 62 |
+
return None, None
|
| 63 |
+
|
| 64 |
+
pil = Image.fromarray(image.astype('uint8'), 'RGB')
|
| 65 |
+
|
| 66 |
+
original_vis = run_detection_on_pil(pil, eval_model_state, conf=conf)
|
| 67 |
+
|
| 68 |
+
if attack_mode == "none":
|
| 69 |
+
return original_vis, None
|
| 70 |
+
|
| 71 |
+
try:
|
| 72 |
+
if attack_mode == "fgsm":
|
| 73 |
+
adv_pil = attacks.fgsm_attack_on_detector(yolom, pil, eps=eps, device=device, imgsz=imgsz)
|
| 74 |
+
elif attack_mode == "pgd":
|
| 75 |
+
adv_pil = attacks.pgd_attack_on_detector(yolom, pil, eps=eps, alpha=alpha, iters=iters, device=device, imgsz=imgsz)
|
| 76 |
+
else:
|
| 77 |
+
adv_pil = attacks.demo_random_perturbation(pil, eps=eps)
|
| 78 |
+
except Exception as ex:
|
| 79 |
+
print("Whitebox attack failed:", ex)
|
| 80 |
+
adv_pil = attacks.demo_random_perturbation(pil, eps=eps)
|
| 81 |
+
|
| 82 |
+
adv_vis = run_detection_on_pil(adv_pil, eval_model_state, conf=conf)
|
| 83 |
+
return original_vis, adv_vis
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# Gradio UI
|
| 87 |
+
if __name__ == "__main__":
|
| 88 |
+
title = "Federated Adversarial Attack — FGSM/PGD Demo"
|
| 89 |
+
desc_html = (
|
| 90 |
+
"Adversarial examples are generated locally using a "
|
| 91 |
+
"<strong>client-side</strong> model’s gradients (white-box), then evaluated against the "
|
| 92 |
+
"<strong>server-side aggregated (FedAvg) central model</strong>. "
|
| 93 |
+
"If the perturbation transfers, it can "
|
| 94 |
+
"degrade or alter the FedAvg model’s predictions on the same input image."
|
| 95 |
+
)
|
| 96 |
+
with gr.Blocks(title=title) as demo:
|
| 97 |
+
# 标题居中
|
| 98 |
+
gr.Markdown(f"""
|
| 99 |
+
<div>
|
| 100 |
+
<h1 style='text-align:center;margin-bottom:0.2rem'>{title}</h1>
|
| 101 |
+
<p style='opacity:0.85'>{desc_html}</p>
|
| 102 |
+
</div>""")
|
| 103 |
+
|
| 104 |
+
with gr.Row():
|
| 105 |
+
# ===== 左列:两个输入区块 =====
|
| 106 |
+
with gr.Column(scale=5):
|
| 107 |
+
# 输入区块 1:上传窗口 & 样例选择 —— 左右并列
|
| 108 |
+
with gr.Row():
|
| 109 |
+
with gr.Column(scale=7):
|
| 110 |
+
in_img = gr.Image(type="numpy", label="Input image")
|
| 111 |
+
with gr.Column(scale=2):
|
| 112 |
+
if SAMPLE_IMAGES:
|
| 113 |
+
gr.Examples(
|
| 114 |
+
examples=SAMPLE_IMAGES,
|
| 115 |
+
inputs=[in_img],
|
| 116 |
+
label=f"Select from sample images",
|
| 117 |
+
examples_per_page=4,
|
| 118 |
+
# run_on_click 默认为 False(只填充,不执行)
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
# 输入 2:攻击与参数
|
| 122 |
+
with gr.Accordion("Attack mode", open=True):
|
| 123 |
+
attack_mode = gr.Radio(
|
| 124 |
+
choices=["none", "fgsm", "pgd", "random noise"],
|
| 125 |
+
value="fgsm",
|
| 126 |
+
label="",
|
| 127 |
+
show_label=False
|
| 128 |
+
)
|
| 129 |
+
eps = gr.Slider(0.0, 0.3, step=0.01, value=0.0314, label="eps")
|
| 130 |
+
alpha = gr.Slider(0.001, 0.05, step=0.001, value=0.0078, label="alpha (PGD step)")
|
| 131 |
+
iters = gr.Slider(1, 100, step=1, value=10, label="PGD iterations")
|
| 132 |
+
conf = gr.Slider(0.0, 1.0, step=0.01, value=0.45, label="Confidence threshold (live)")
|
| 133 |
+
|
| 134 |
+
with gr.Row():
|
| 135 |
+
btn_clear = gr.ClearButton(
|
| 136 |
+
components=[in_img, eps, alpha, iters, conf], # 不清空 attack_mode
|
| 137 |
+
value="Clear"
|
| 138 |
+
)
|
| 139 |
+
btn_submit = gr.Button("Submit", variant="primary")
|
| 140 |
+
|
| 141 |
+
# ===== 右列:两个输出区块 =====
|
| 142 |
+
with gr.Column(scale=5):
|
| 143 |
+
# 新增:评测模型选择
|
| 144 |
+
with gr.Row():
|
| 145 |
+
eval_choice = gr.Dropdown(
|
| 146 |
+
choices=[(f"Client model {MODEL_PATH}", "client"),
|
| 147 |
+
(f"Central model {MODEL_PATH_C}", "central")],
|
| 148 |
+
value="client", # ★ 初始值为合法 value
|
| 149 |
+
label="Evaluation model"
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
eval_model_state = gr.State(value="yolom")
|
| 153 |
+
|
| 154 |
+
# ★ 合并后的单一回调:规范化下拉值 + 返回(更新后的下拉值, 模型对象)
|
| 155 |
+
def on_eval_change(val: str):
|
| 156 |
+
if isinstance(val, (list, tuple)):
|
| 157 |
+
val = val[0] if len(val) else "client"
|
| 158 |
+
if val not in ("client", "central"):
|
| 159 |
+
val = "client"
|
| 160 |
+
model = "yolom" if val == "client" else "yolom_c"
|
| 161 |
+
return gr.update(value=val), model
|
| 162 |
+
|
| 163 |
+
# 页面加载时同步一次,避免初次为空/不一致
|
| 164 |
+
demo.load(
|
| 165 |
+
fn=on_eval_change,
|
| 166 |
+
inputs=eval_choice,
|
| 167 |
+
outputs=[eval_choice, eval_model_state]
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
# 仅这一条 change 绑定(删掉你原来那个只写 State 的 change,避免并发覆盖)
|
| 171 |
+
eval_choice.change(
|
| 172 |
+
fn=on_eval_change,
|
| 173 |
+
inputs=eval_choice,
|
| 174 |
+
outputs=[eval_choice, eval_model_state]
|
| 175 |
+
)
|
| 176 |
+
out_orig = gr.Image(label="Original detection")
|
| 177 |
+
out_adv = gr.Image(label="After attack detection")
|
| 178 |
+
|
| 179 |
+
# Submit:手动运行
|
| 180 |
+
btn_submit.click(
|
| 181 |
+
fn=detect_and_attack,
|
| 182 |
+
inputs=[in_img, eval_model_state, attack_mode, eps, alpha, iters, conf],
|
| 183 |
+
outputs=[out_orig, out_adv]
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
# 仅 conf 滑块“实时”
|
| 187 |
+
conf.release(
|
| 188 |
+
fn=detect_and_attack,
|
| 189 |
+
inputs=[in_img, eval_model_state, attack_mode, eps, alpha, iters, conf],
|
| 190 |
+
outputs=[out_orig, out_adv]
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
# demo.queue(concurrency_count=2, max_size=20)
|
| 194 |
+
demo.launch()
|
| 195 |
+
# demo.launch(server_name="0.0.0.0", server_port=7860)
|
| 196 |
+
|
| 197 |
+
|
attacks.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
attacks.py
|
| 3 |
+
|
| 4 |
+
提供对检测模型(以 YOLOv8/ultralytics 为主)执行 FGSM 与 PGD 的实现。
|
| 5 |
+
|
| 6 |
+
设计思路与注意事项:
|
| 7 |
+
- 假定我们可以访问到底层的 torch.nn.Module(例如 ultralytics.YOLO 实例的 .model 成员)
|
| 8 |
+
并能以 tensor 输入直接跑 forward(),得到原始预测张量 (batch, N_preds, C)
|
| 9 |
+
其中通常 C = 5 + num_classes(bbox4 + obj_conf + class_logits)。
|
| 10 |
+
- 计算 loss: 对每个 anchor/pred,取 obj_conf * max_class_prob 作为该预测的置信度,
|
| 11 |
+
把全局置信度求和作为被攻击的目标函数;对该目标函数**做最小化**以让检测置信下降。
|
| 12 |
+
- FGSM: x_adv = x - eps * sign(grad(loss))
|
| 13 |
+
- PGD: 多步迭代,每步做 x = x - alpha * sign(grad), 并投影到 L_inf 球体:|x-x_orig|<=eps
|
| 14 |
+
- 如果你的 ultralytics 版本/模型封装与假定不同,代码会抛错并提示如何修改。
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from typing import Tuple, Optional
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn as nn
|
| 20 |
+
import numpy as np
|
| 21 |
+
from PIL import Image
|
| 22 |
+
import torchvision.transforms as T
|
| 23 |
+
import math
|
| 24 |
+
import torch.nn.functional as F
|
| 25 |
+
from typing import Tuple, Dict
|
| 26 |
+
|
| 27 |
+
# ============= Resize image =====================
|
| 28 |
+
def _get_max_stride(net) -> int:
|
| 29 |
+
s = getattr(net, "stride", None)
|
| 30 |
+
if isinstance(s, torch.Tensor):
|
| 31 |
+
return int(s.max().item())
|
| 32 |
+
try:
|
| 33 |
+
return int(max(s))
|
| 34 |
+
except Exception:
|
| 35 |
+
return 32 # 兜底
|
| 36 |
+
|
| 37 |
+
def letterbox_tensor(
|
| 38 |
+
x: torch.Tensor,
|
| 39 |
+
*,
|
| 40 |
+
imgsz: int,
|
| 41 |
+
stride: int,
|
| 42 |
+
fill: float = 114.0 / 255.0,
|
| 43 |
+
scaleup: bool = True
|
| 44 |
+
) -> Tuple[torch.Tensor, Dict]:
|
| 45 |
+
"""
|
| 46 |
+
x: [1,3,H,W] in [0,1]
|
| 47 |
+
返回: x_lb, meta (含缩放比例与左右上下 padding 以便反映射)
|
| 48 |
+
"""
|
| 49 |
+
assert x.ndim == 4 and x.shape[0] == 1
|
| 50 |
+
_, C, H, W = x.shape
|
| 51 |
+
if imgsz is None:
|
| 52 |
+
# 动态设定目标边长:把 max(H,W) 向上取整到 stride 的倍数(更贴近原生自动整形)
|
| 53 |
+
imgsz = int(math.ceil(max(H, W) / stride) * stride)
|
| 54 |
+
|
| 55 |
+
r = min(imgsz / H, imgsz / W) # 等比缩放比例
|
| 56 |
+
if not scaleup:
|
| 57 |
+
r = min(r, 1.0)
|
| 58 |
+
|
| 59 |
+
new_w = int(round(W * r))
|
| 60 |
+
new_h = int(round(H * r))
|
| 61 |
+
|
| 62 |
+
# 先等比缩放
|
| 63 |
+
if (new_h, new_w) != (H, W):
|
| 64 |
+
x = F.interpolate(x, size=(new_h, new_w), mode="bilinear", align_corners=False)
|
| 65 |
+
|
| 66 |
+
# 再 padding 到 (imgsz, imgsz),保持与 YOLO 一致的对称填充
|
| 67 |
+
dw = imgsz - new_w
|
| 68 |
+
dh = imgsz - new_h
|
| 69 |
+
left, right = dw // 2, dw - dw // 2
|
| 70 |
+
top, bottom = dh // 2, dh - dh // 2
|
| 71 |
+
|
| 72 |
+
x = F.pad(x, (left, right, top, bottom), mode="constant", value=fill)
|
| 73 |
+
|
| 74 |
+
meta = {
|
| 75 |
+
"ratio": r,
|
| 76 |
+
"pad": (left, top),
|
| 77 |
+
"resized_shape": (new_h, new_w),
|
| 78 |
+
"imgsz": imgsz,
|
| 79 |
+
}
|
| 80 |
+
return x, meta
|
| 81 |
+
|
| 82 |
+
def unletterbox_to_original(
|
| 83 |
+
x_lb: torch.Tensor, meta: Dict, orig_hw: Tuple[int, int]
|
| 84 |
+
) -> torch.Tensor:
|
| 85 |
+
"""
|
| 86 |
+
把 letterboxed 张量([1,3,imgsz,imgsz])反映射回原始 H0,W0 尺寸(去 padding + 反缩放)
|
| 87 |
+
"""
|
| 88 |
+
assert x_lb.ndim == 4 and x_lb.shape[0] == 1
|
| 89 |
+
H0, W0 = orig_hw
|
| 90 |
+
(left, top) = meta["pad"]
|
| 91 |
+
(h_r, w_r) = meta["resized_shape"]
|
| 92 |
+
|
| 93 |
+
# 去 padding(裁出等比缩放后的区域)
|
| 94 |
+
x_unpad = x_lb[..., top:top + h_r, left:left + w_r] # [1,3,h_r,w_r]
|
| 95 |
+
|
| 96 |
+
# 反缩放到原图大小
|
| 97 |
+
x_rec = F.interpolate(x_unpad, size=(H0, W0), mode="bilinear", align_corners=False)
|
| 98 |
+
return x_rec
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
# ----- basic preprocessing / deprocessing (RGB PIL <-> torch tensor) -----
|
| 102 |
+
_to_tensor = T.Compose([
|
| 103 |
+
T.ToTensor(), # float in [0,1], shape C,H,W
|
| 104 |
+
])
|
| 105 |
+
|
| 106 |
+
_to_pil = T.ToPILImage()
|
| 107 |
+
|
| 108 |
+
def pil_to_tensor(img_pil: Image.Image, device: torch.device) -> torch.Tensor:
|
| 109 |
+
"""PIL RGB -> float tensor [1,3,H,W] on device"""
|
| 110 |
+
t = _to_tensor(img_pil).unsqueeze(0).to(device) # 1,C,H,W
|
| 111 |
+
t.requires_grad = True
|
| 112 |
+
return t
|
| 113 |
+
|
| 114 |
+
def tensor_to_pil(t: torch.Tensor) -> Image.Image:
|
| 115 |
+
"""tensor [1,3,H,W] (0..1) -> PIL RGB"""
|
| 116 |
+
t = t.detach().cpu().squeeze(0).clamp(0.0, 1.0)
|
| 117 |
+
return _to_pil(t)
|
| 118 |
+
|
| 119 |
+
# ----- helper to obtain underlying torch module from ultralytics YOLO wrapper -----
|
| 120 |
+
def get_torch_module_from_ultralytics(model) -> nn.Module:
|
| 121 |
+
"""
|
| 122 |
+
Try to retrieve an nn.Module that accepts an input tensor and returns raw preds.
|
| 123 |
+
For ultralytics.YOLO, .model is usually the underlying Detect/Model (nn.Module).
|
| 124 |
+
"""
|
| 125 |
+
if hasattr(model, "model") and isinstance(model.model, nn.Module):
|
| 126 |
+
return model.model
|
| 127 |
+
# Some wrappers nest further; attempt a few common names
|
| 128 |
+
for attr in ("model", "module", "net", "model_"):
|
| 129 |
+
if hasattr(model, attr) and isinstance(getattr(model, attr), nn.Module):
|
| 130 |
+
return getattr(model, attr)
|
| 131 |
+
raise RuntimeError("无法找到底层 torch.nn.Module。请确保传入的是 ultralytics.YOLO 实例且能访问 model.model。")
|
| 132 |
+
|
| 133 |
+
# ----- interpret raw model outputs to confidences -----
|
| 134 |
+
def preds_to_confidence_sum(preds: torch.Tensor) -> torch.Tensor:
|
| 135 |
+
"""
|
| 136 |
+
preds: tensor shape (batch, N_preds, C) or (batch, C, H, W) depending on model.
|
| 137 |
+
We support the common YOLO format where last dim: [x,y,w,h,obj_conf, class_probs...]
|
| 138 |
+
Returns scalar: sum of (obj_conf * max_class_prob) over batch and predictions.
|
| 139 |
+
"""
|
| 140 |
+
if preds is None:
|
| 141 |
+
raise ValueError("preds is None")
|
| 142 |
+
# handle shape (batch, N_preds, C)
|
| 143 |
+
if preds.ndim == 3:
|
| 144 |
+
# assume last dim: 5 + num_classes
|
| 145 |
+
if preds.shape[-1] < 6:
|
| 146 |
+
# can't interpret
|
| 147 |
+
raise RuntimeError(f"preds last dim too small ({preds.shape[-1]}). Expecting >=6.")
|
| 148 |
+
obj_conf = preds[..., 4] # (batch, N)
|
| 149 |
+
class_probs = preds[..., 5:] # (batch, N, num_cls)
|
| 150 |
+
max_class, _ = class_probs.max(dim=-1) # (batch, N)
|
| 151 |
+
conf = obj_conf * max_class
|
| 152 |
+
return conf.sum()
|
| 153 |
+
# some models output (batch, C, H, W) - flatten
|
| 154 |
+
if preds.ndim == 4:
|
| 155 |
+
# try to collapse so that last dim is class
|
| 156 |
+
b, c, h, w = preds.shape
|
| 157 |
+
flat = preds.view(b, c, -1).permute(0, 2, 1) # (batch, N, C)
|
| 158 |
+
return preds_to_confidence_sum(flat)
|
| 159 |
+
raise RuntimeError(f"Unhandled preds dimensionality: {preds.shape}")
|
| 160 |
+
|
| 161 |
+
# ----- core attack implementations -----
|
| 162 |
+
def fgsm_attack_on_detector(
|
| 163 |
+
model,
|
| 164 |
+
img_pil: Image.Image,
|
| 165 |
+
eps: float = 0.03,
|
| 166 |
+
device: Optional[torch.device] = None,
|
| 167 |
+
imgsz: Optional[int] = None, # None=自动对齐到 stride 倍数;也可传 640
|
| 168 |
+
|
| 169 |
+
) -> Image.Image:
|
| 170 |
+
"""
|
| 171 |
+
Perform a single-step FGSM on a detection model (white-box).
|
| 172 |
+
- model: ultralytics.YOLO wrapper (or anything where get_torch_module_from_ultralytics works)
|
| 173 |
+
- img_pil: input PIL RGB
|
| 174 |
+
- eps: max per-pixel perturbation in [0,1] (L_inf)
|
| 175 |
+
Returns PIL image of adversarial example.
|
| 176 |
+
"""
|
| 177 |
+
device = device or (torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu"))
|
| 178 |
+
# get torch module
|
| 179 |
+
net = get_torch_module_from_ultralytics(model)
|
| 180 |
+
net = net.to(device).eval()
|
| 181 |
+
for p in net.parameters():
|
| 182 |
+
p.requires_grad_(False) # 建议:避免对参数求梯度
|
| 183 |
+
|
| 184 |
+
# (a) 原图 -> [1,3,H0,W0],随后先 detach 掉梯度
|
| 185 |
+
x_orig = pil_to_tensor(img_pil, device)
|
| 186 |
+
H0, W0 = x_orig.shape[-2:]
|
| 187 |
+
x_orig = x_orig.detach()
|
| 188 |
+
|
| 189 |
+
# (b) 可微 letterbox
|
| 190 |
+
s = _get_max_stride(net)
|
| 191 |
+
x_lb, meta = letterbox_tensor(x_orig, imgsz=imgsz, stride=s, fill=114/255.0)
|
| 192 |
+
x_lb = x_lb.clone().detach().requires_grad_(True)
|
| 193 |
+
|
| 194 |
+
# (c) 前向与你的损失
|
| 195 |
+
with torch.enable_grad():
|
| 196 |
+
preds = net(x_lb)
|
| 197 |
+
if isinstance(preds, (tuple, list)):
|
| 198 |
+
tensor_pred = next((p for p in preds if isinstance(p, torch.Tensor) and p.ndim >= 3), None)
|
| 199 |
+
if tensor_pred is None:
|
| 200 |
+
raise RuntimeError("模型 forward 返回了 tuple/list,但无法从中找到预测张量。")
|
| 201 |
+
preds = tensor_pred
|
| 202 |
+
|
| 203 |
+
loss = - preds_to_confidence_sum(preds)
|
| 204 |
+
loss.backward()
|
| 205 |
+
|
| 206 |
+
# (d) FGSM 在 letterboxed 空间施扰
|
| 207 |
+
# FGSM update: x_adv = x + eps * sign(grad(loss wrt x))
|
| 208 |
+
with torch.no_grad():
|
| 209 |
+
adv_lb = (x_lb + eps * x_lb.grad.sign()).clamp(0, 1)
|
| 210 |
+
|
| 211 |
+
# 清理(单步可选;PGD循环时必做)
|
| 212 |
+
x_lb.grad = None
|
| 213 |
+
net.zero_grad(set_to_none=True)
|
| 214 |
+
|
| 215 |
+
# (e) 反映射回原图尺寸
|
| 216 |
+
adv_orig = unletterbox_to_original(adv_lb, meta, (H0, W0)).detach()
|
| 217 |
+
|
| 218 |
+
# (f) 转回 PIL
|
| 219 |
+
adv_pil = tensor_to_pil(adv_orig)
|
| 220 |
+
return adv_pil
|
| 221 |
+
|
| 222 |
+
def pgd_attack_on_detector(
|
| 223 |
+
model,
|
| 224 |
+
img_pil: Image.Image,
|
| 225 |
+
eps: float = 0.03, # L_inf 半径(输入在[0,1]域)
|
| 226 |
+
alpha: float = 0.007, # 步长
|
| 227 |
+
iters: int = 10,
|
| 228 |
+
device: Optional[torch.device] = None,
|
| 229 |
+
imgsz: Optional[int] = None, # None=自动对齐到 stride 倍数;也可传 640
|
| 230 |
+
):
|
| 231 |
+
"""
|
| 232 |
+
在 YOLO 的 letterbox 域做 PGD,
|
| 233 |
+
迭代结束后把对抗样本映回原图大小并返回 PIL。
|
| 234 |
+
依赖你已实现的: pil_to_tensor, tensor_to_pil, letterbox_tensor, unletterbox_to_original, _get_max_stride
|
| 235 |
+
"""
|
| 236 |
+
device = device or (torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu"))
|
| 237 |
+
net = get_torch_module_from_ultralytics(model).to(device).eval()
|
| 238 |
+
|
| 239 |
+
# 仅对输入求梯度,冻结参数以省资源
|
| 240 |
+
for p in net.parameters():
|
| 241 |
+
p.requires_grad_(False)
|
| 242 |
+
|
| 243 |
+
# 原图 -> Tensor([1,3,H0,W0], [0,1])
|
| 244 |
+
x0 = pil_to_tensor(img_pil, device).detach()
|
| 245 |
+
H0, W0 = x0.shape[-2:]
|
| 246 |
+
|
| 247 |
+
# 可微 letterbox(等比缩放 + 对称 pad 到 stride 倍数)
|
| 248 |
+
s = _get_max_stride(net)
|
| 249 |
+
x_lb_orig, meta = letterbox_tensor(x0, imgsz=imgsz, stride=s, fill=114/255.0) # [1,3,S,S]
|
| 250 |
+
x = x_lb_orig.clone().detach().requires_grad_(True)
|
| 251 |
+
|
| 252 |
+
for _ in range(iters):
|
| 253 |
+
# 前向 + 反向(需要梯度)
|
| 254 |
+
preds = net(x)
|
| 255 |
+
if isinstance(preds, (tuple, list)):
|
| 256 |
+
preds = next((p for p in preds if isinstance(p, torch.Tensor) and p.ndim >= 3), None)
|
| 257 |
+
if preds is None:
|
| 258 |
+
raise RuntimeError("模型 forward 返回 tuple/list,但未找到预测张量。")
|
| 259 |
+
loss = - preds_to_confidence_sum(preds) # 我们希望置信度总和下��� → 最小化
|
| 260 |
+
loss.backward()
|
| 261 |
+
|
| 262 |
+
# 更新步与投影(不记录计算图)
|
| 263 |
+
with torch.no_grad():
|
| 264 |
+
x.add_(alpha * x.grad.sign())
|
| 265 |
+
# 投影到 L_inf 球: 通过裁剪 delta 更稳
|
| 266 |
+
delta = (x - x_lb_orig).clamp(-eps, eps)
|
| 267 |
+
x.copy_((x_lb_orig + delta).clamp(0.0, 1.0))
|
| 268 |
+
|
| 269 |
+
# 清理并设置下一步
|
| 270 |
+
x.grad = None
|
| 271 |
+
net.zero_grad(set_to_none=True)
|
| 272 |
+
x.requires_grad_(True)
|
| 273 |
+
|
| 274 |
+
# 反映射回原图尺寸
|
| 275 |
+
adv_orig = unletterbox_to_original(x.detach(), meta, (H0, W0)).detach()
|
| 276 |
+
return tensor_to_pil(adv_orig)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
# ----- graceful fallback / demo noise if whitebox impossible -----
|
| 280 |
+
def demo_random_perturbation(img_pil: Image.Image, eps: float = 0.03) -> Image.Image:
|
| 281 |
+
"""Non-gradient demo perturbation used as fallback."""
|
| 282 |
+
arr = np.asarray(img_pil).astype(np.float32) / 255.0
|
| 283 |
+
noise = np.sign(np.random.randn(*arr.shape)).astype(np.float32)
|
| 284 |
+
adv = np.clip(arr + eps * noise, 0.0, 1.0)
|
| 285 |
+
adv_img = Image.fromarray((adv * 255).astype(np.uint8))
|
| 286 |
+
return adv_img
|
federated_utils.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# federated_utils.py
|
| 2 |
+
import copy
|
| 3 |
+
import torch
|
| 4 |
+
import tempfile
|
| 5 |
+
from typing import List, Optional, Tuple
|
| 6 |
+
from ultralytics import YOLO
|
| 7 |
+
import os
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
def average_state_dicts(state_dicts: List[dict]) -> dict:
|
| 11 |
+
keys = list(state_dicts[0].keys())
|
| 12 |
+
for sd in state_dicts:
|
| 13 |
+
assert list(sd.keys()) == keys, "state_dict keys mismatch"
|
| 14 |
+
avg = {}
|
| 15 |
+
for k in keys:
|
| 16 |
+
s = sum(sd[k].cpu().float() for sd in state_dicts)
|
| 17 |
+
avg[k] = (s / len(state_dicts)).to(state_dicts[0][k].device)
|
| 18 |
+
return avg
|
| 19 |
+
|
| 20 |
+
def load_model_state(path: str) -> dict:
|
| 21 |
+
model = YOLO(path)
|
| 22 |
+
sd = model.model.state_dict()
|
| 23 |
+
return {k: v.cpu() for k, v in sd.items()}
|
| 24 |
+
|
| 25 |
+
def save_state_dict(sd: dict, out_path: str):
|
| 26 |
+
torch.save(sd, out_path)
|
| 27 |
+
|
| 28 |
+
def train_client_local(client_data_yaml: str,
|
| 29 |
+
init_weights_path: str,
|
| 30 |
+
epochs: int = 1,
|
| 31 |
+
batch: int = 8,
|
| 32 |
+
imgsz: int = 640,
|
| 33 |
+
device: Optional[str] = None) -> dict:
|
| 34 |
+
"""用 ultralytics 进行极短本地训练,返回 state_dict(CPU)。"""
|
| 35 |
+
device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
| 36 |
+
model = YOLO(init_weights_path)
|
| 37 |
+
# 轻量训练;若你有更具体的超参可以改这里
|
| 38 |
+
model.train(data=client_data_yaml, epochs=epochs, batch=batch, imgsz=imgsz, device=device, save=False, verbose=False)
|
| 39 |
+
sd = model.model.state_dict()
|
| 40 |
+
return {k: v.cpu() for k, v in sd.items()}
|
| 41 |
+
|
| 42 |
+
def run_fedavg_from_checkpoints(client_ckpt_paths: List[str], out_global_path: str) -> str:
|
| 43 |
+
sds = []
|
| 44 |
+
for p in client_ckpt_paths:
|
| 45 |
+
try:
|
| 46 |
+
tmp = torch.load(p, map_location='cpu')
|
| 47 |
+
if isinstance(tmp, dict) and 'model' in tmp:
|
| 48 |
+
sd = tmp['model']
|
| 49 |
+
else:
|
| 50 |
+
sd = tmp
|
| 51 |
+
sd_cpu = {k: v.cpu() for k, v in sd.items()}
|
| 52 |
+
except Exception:
|
| 53 |
+
# 如果直接load失败,就用YOLO包装加载
|
| 54 |
+
model = YOLO(p)
|
| 55 |
+
sd_cpu = {k: v.cpu() for k, v in model.model.state_dict().items()}
|
| 56 |
+
sds.append(sd_cpu)
|
| 57 |
+
avg = average_state_dicts(sds)
|
| 58 |
+
torch.save(avg, out_global_path)
|
| 59 |
+
return out_global_path
|
| 60 |
+
|
| 61 |
+
def run_federated_simulation(client_data_yaml_list: List[str],
|
| 62 |
+
init_global_weights: str,
|
| 63 |
+
rounds: int = 1,
|
| 64 |
+
local_epochs: int = 1,
|
| 65 |
+
device: Optional[str] = None,
|
| 66 |
+
imgsz: int = 640,
|
| 67 |
+
batch: int = 8) -> Tuple[str, List[str]]:
|
| 68 |
+
"""
|
| 69 |
+
超轻量联邦模拟(同步执行):
|
| 70 |
+
for r in rounds:
|
| 71 |
+
对每个 client: 从当前全局权重做本地小步训练 → 得到 client state_dict
|
| 72 |
+
平均得到新的全局 → 保存 global_round_r.pt
|
| 73 |
+
返回:(初始全局路径, [每轮全局路径列表])
|
| 74 |
+
"""
|
| 75 |
+
device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
| 76 |
+
global_state = load_model_state(init_global_weights)
|
| 77 |
+
round_paths: List[str] = []
|
| 78 |
+
for r in range(rounds):
|
| 79 |
+
client_states = []
|
| 80 |
+
for i, cyaml in enumerate(client_data_yaml_list):
|
| 81 |
+
# 将当前全局state写临时文件供 YOLO 加载
|
| 82 |
+
init_tmp = f"__tmp_global_r{r}_c{i}.pt"
|
| 83 |
+
torch.save(global_state, init_tmp)
|
| 84 |
+
try:
|
| 85 |
+
sd_client = train_client_local(
|
| 86 |
+
cyaml, init_tmp, epochs=local_epochs, batch=batch, imgsz=imgsz, device=device
|
| 87 |
+
)
|
| 88 |
+
except Exception as e:
|
| 89 |
+
print(f"[WARN] client {i} local train failed: {e}; fallback to global")
|
| 90 |
+
sd_client = load_model_state(init_tmp)
|
| 91 |
+
client_states.append(sd_client)
|
| 92 |
+
# FedAvg
|
| 93 |
+
new_global = average_state_dicts(client_states)
|
| 94 |
+
out_path = f"global_round_{r}.pt"
|
| 95 |
+
save_state_dict(new_global, out_path)
|
| 96 |
+
round_paths.append(out_path)
|
| 97 |
+
global_state = new_global
|
| 98 |
+
return init_global_weights, round_paths
|
images/train/c1.png
ADDED
|
Git LFS Details
|
images/train/c2.png
ADDED
|
Git LFS Details
|
images/train/c3.png
ADDED
|
Git LFS Details
|
images/train/c4.png
ADDED
|
Git LFS Details
|
requirements.txt
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --- Core ---
|
| 2 |
+
gradio>=4.44.0
|
| 3 |
+
ultralytics>=8.3.0
|
| 4 |
+
torch>=2.2.0
|
| 5 |
+
torchvision>=0.17.0
|
| 6 |
+
|
| 7 |
+
# --- Image/Array utils ---
|
| 8 |
+
opencv-python
|
| 9 |
+
Pillow
|
| 10 |
+
numpy
|
| 11 |
+
|
| 12 |
+
# (可选)日志/可视化
|
| 13 |
+
tqdm
|
weights/fed_model2.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5556943eb4eda78916605d095385ca06dd2947727c65c7171e544ca4eceda630
|
| 3 |
+
size 22515300
|
weights/yolov8s_3cls.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:abd83b970eba32dc547e661fe0c062a4657952334267b861c74259bd4a25cccc
|
| 3 |
+
size 22513856
|