Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,11 +1,7 @@
|
|
| 1 |
# ================================================================
|
| 2 |
-
# 教育大模型MIA攻防研究
|
| 3 |
-
# 修复卡片等高对齐 + 补全结论数据 + 保持数字不换行
|
| 4 |
# ================================================================
|
| 5 |
-
|
| 6 |
-
import os
|
| 7 |
-
import json
|
| 8 |
-
import re
|
| 9 |
import numpy as np
|
| 10 |
import matplotlib
|
| 11 |
matplotlib.use('Agg')
|
|
@@ -13,975 +9,564 @@ import matplotlib.pyplot as plt
|
|
| 13 |
from sklearn.metrics import roc_curve, roc_auc_score
|
| 14 |
import gradio as gr
|
| 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 |
-
perturb_results = all_data["perturbation_results"]
|
| 42 |
-
utility_results = all_data["utility_results"]
|
| 43 |
-
full_losses = all_data["full_losses"]
|
| 44 |
-
model_name = config.get('model_name', 'Qwen/Qwen2.5-Math-1.5B-Instruct')
|
| 45 |
-
except FileNotFoundError:
|
| 46 |
-
print("⚠️ 警告: 未找到数据文件。将使用虚拟数据进行演示。")
|
| 47 |
-
member_data = [{"question": "Q"+str(i), "answer": "A"+str(i), "task_type": "calculation", "metadata": {"name": "Student"+str(i), "student_id": str(1000+i), "class": "Class A", "score": 90}} for i in range(1000)]
|
| 48 |
-
non_member_data = [{"question": "Q"+str(i+1000), "answer": "A"+str(i+1000), "task_type": "word_problem", "metadata": {"name": "Student"+str(i+1000), "student_id": str(2000+i), "class": "Class B", "score": 85}} for i in range(1000)]
|
| 49 |
-
model_name = "Demo Model"
|
| 50 |
-
mia_results = {"baseline": {"auc": 0.6230, "attack_accuracy": 0.6055, "precision": 0.6779, "recall": 0.4020, "f1": 0.5047, "tpr_at_5fpr": 0.1850, "tpr_at_1fpr": 0.0930, "loss_gap": 0.0107, "member_loss_mean": 0.19, "non_member_loss_mean": 0.20, "member_loss_std": 0.03, "non_member_loss_std": 0.03}}
|
| 51 |
-
perturb_results = {}
|
| 52 |
-
utility_results = {"baseline": {"accuracy": 0.660}}
|
| 53 |
-
full_losses = {"baseline": {"member_losses": np.random.normal(0.19, 0.03, 1000).tolist(), "non_member_losses": np.random.normal(0.20, 0.03, 1000).tolist()}}
|
| 54 |
-
for e in [0.02, 0.05, 0.1, 0.2]:
|
| 55 |
-
k = f"smooth_eps_{e}"
|
| 56 |
-
mia_results[k] = {m: v*0.9 for m, v in mia_results["baseline"].items()}
|
| 57 |
-
utility_results[k] = {"accuracy": 0.660 + e*0.1}
|
| 58 |
-
for s in [0.005, 0.01, 0.015, 0.02, 0.025, 0.03]:
|
| 59 |
-
k = f"perturbation_{s}"
|
| 60 |
-
perturb_results[k] = {m: v*0.85 for m, v in mia_results["baseline"].items()}
|
| 61 |
-
|
| 62 |
-
# ================================================================
|
| 63 |
-
# 全局图表配置 - 简约苹果风
|
| 64 |
-
# ================================================================
|
| 65 |
-
COLORS = {
|
| 66 |
-
'bg': '#FFFFFF',
|
| 67 |
-
'panel': '#F5F7FA',
|
| 68 |
-
'grid': '#E2E8F0',
|
| 69 |
-
'text': '#1E293B',
|
| 70 |
-
'text_dim': '#64748B',
|
| 71 |
-
'accent': '#007AFF',
|
| 72 |
-
'accent2': '#5856D6',
|
| 73 |
-
'danger': '#FF3B30',
|
| 74 |
-
'success': '#34C759',
|
| 75 |
-
'warning': '#FF9500',
|
| 76 |
-
'baseline': '#8E8E93',
|
| 77 |
-
'ls_colors': ['#A0C4FF', '#70A1FF', '#478EFF', '#007AFF'],
|
| 78 |
-
'op_colors': ['#98F5E1', '#6EE7B7', '#34D399', '#10B981', '#059669', '#047857'],
|
| 79 |
-
}
|
| 80 |
-
|
| 81 |
-
def apply_light_style(fig, ax_or_axes):
|
| 82 |
-
fig.patch.set_facecolor(COLORS['bg'])
|
| 83 |
-
axes = ax_or_axes if hasattr(ax_or_axes, '__iter__') else [ax_or_axes]
|
| 84 |
-
for ax in axes:
|
| 85 |
-
ax.set_facecolor(COLORS['panel'])
|
| 86 |
-
for spine in ax.spines.values():
|
| 87 |
-
spine.set_color(COLORS['grid'])
|
| 88 |
-
spine.set_linewidth(1)
|
| 89 |
-
ax.tick_params(colors=COLORS['text_dim'], labelsize=10, width=1)
|
| 90 |
-
ax.xaxis.label.set_color(COLORS['text'])
|
| 91 |
-
ax.yaxis.label.set_color(COLORS['text'])
|
| 92 |
-
ax.title.set_color(COLORS['text'])
|
| 93 |
-
ax.title.set_fontweight('semibold')
|
| 94 |
-
ax.grid(True, color=COLORS['grid'], alpha=0.6, linestyle='-', linewidth=0.8)
|
| 95 |
-
ax.set_axisbelow(True)
|
| 96 |
-
|
| 97 |
-
# ================================================================
|
| 98 |
-
# 提取指标的辅助函数
|
| 99 |
-
# ================================================================
|
| 100 |
-
LS_KEYS = ["baseline", "smooth_eps_0.02", "smooth_eps_0.05", "smooth_eps_0.1", "smooth_eps_0.2"]
|
| 101 |
-
LS_LABELS_EN = ["Baseline", "LS(e=0.02)", "LS(e=0.05)", "LS(e=0.1)", "LS(e=0.2)"]
|
| 102 |
-
LS_LABELS_CN = ["基线", "LS(ε=0.02)", "LS(ε=0.05)", "LS(ε=0.1)", "LS(ε=0.2)"]
|
| 103 |
-
|
| 104 |
-
OP_SIGMAS = [0.005, 0.01, 0.015, 0.02, 0.025, 0.03]
|
| 105 |
-
OP_KEYS = [f"perturbation_{s}" for s in OP_SIGMAS]
|
| 106 |
-
OP_LABELS_EN = [f"OP(s={s})" for s in OP_SIGMAS]
|
| 107 |
-
OP_LABELS_CN = [f"OP(σ={s})" for s in OP_SIGMAS]
|
| 108 |
-
|
| 109 |
-
ALL_KEYS = LS_KEYS + OP_KEYS
|
| 110 |
-
ALL_LABELS_EN = LS_LABELS_EN + OP_LABELS_EN
|
| 111 |
-
ALL_LABELS_CN = LS_LABELS_CN + OP_LABELS_CN
|
| 112 |
-
|
| 113 |
-
def gm(key, metric, default=0):
|
| 114 |
-
if key in mia_results: return mia_results[key].get(metric, default)
|
| 115 |
-
if key in perturb_results: return perturb_results[key].get(metric, default)
|
| 116 |
-
return default
|
| 117 |
-
|
| 118 |
-
def gu(key):
|
| 119 |
-
if key in utility_results: return utility_results[key].get("accuracy", 0) * 100
|
| 120 |
-
if key.startswith("perturbation_"): return utility_results.get("baseline", {}).get("accuracy", 0) * 100
|
| 121 |
return 0
|
| 122 |
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
#
|
| 132 |
-
#
|
| 133 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
np.random.seed(777)
|
| 135 |
-
|
| 136 |
-
_types = ['calculation']*120 + ['word_problem']*90 + ['concept']*60 + ['error_correction']*30
|
| 137 |
for _i in range(300):
|
| 138 |
-
|
| 139 |
-
if
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
if
|
| 143 |
-
elif
|
| 144 |
-
else:
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
(f"{_a} pens, sold {_b}, left?",str(_a-_b)),
|
| 150 |
-
(f"Had {_a}, got {_b} more, total?",str(_a+_b))]
|
| 151 |
-
_q,_ans = _tpls[_i%len(_tpls)]
|
| 152 |
-
elif _t == 'concept':
|
| 153 |
-
_cs = [("area","Area = space occupied by a shape"),("perimeter","Perimeter = total boundary length"),
|
| 154 |
-
("fraction","Fraction = equal parts of a whole"),("decimal","Decimal = number with point"),
|
| 155 |
-
("average","Average = sum / count")]
|
| 156 |
-
_cn,_df = _cs[_i%len(_cs)]; _q,_ans = f"What is {_cn}?",_df
|
| 157 |
else:
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
acc = gu(key)/100; item[key] = bool(np.random.random()<acc)
|
| 164 |
-
EVAL_POOL.append(item)
|
| 165 |
|
| 166 |
# ================================================================
|
| 167 |
-
#
|
| 168 |
# ================================================================
|
|
|
|
|
|
|
| 169 |
def fig_auc_bar():
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
for i,(k,l) in enumerate(zip(
|
| 173 |
-
if k in
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
ax.
|
| 184 |
-
ax.
|
| 185 |
-
ax.
|
| 186 |
-
ax.
|
| 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 |
def fig_loss_dist():
|
| 220 |
-
|
| 221 |
-
n
|
| 222 |
-
if n
|
| 223 |
-
fig,
|
| 224 |
-
if n
|
| 225 |
-
|
| 226 |
-
for ax,
|
| 227 |
-
m
|
| 228 |
-
bins
|
| 229 |
-
ax.hist(m,
|
| 230 |
-
ax.hist(nm,
|
| 231 |
-
ax.set_title(f'{l}
|
| 232 |
-
ax.set_xlabel('Loss',
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
pa = gm(f'perturbation_{s}', 'auc')
|
| 251 |
-
ax.set_title(f'OP(s={s})\nAUC={pa:.4f}', fontsize=11, fontweight='semibold')
|
| 252 |
-
ax.set_xlabel('Loss', fontsize=10)
|
| 253 |
-
ax.legend(fontsize=9, facecolor=COLORS['bg'], edgecolor='none', labelcolor=COLORS['text'])
|
| 254 |
-
plt.tight_layout()
|
| 255 |
-
return fig
|
| 256 |
-
|
| 257 |
-
def fig_roc_curves():
|
| 258 |
-
fig, axes = plt.subplots(1, 2, figsize=(16, 7))
|
| 259 |
-
apply_light_style(fig, axes)
|
| 260 |
-
ax = axes[0]
|
| 261 |
-
ls_colors = [COLORS['danger'], COLORS['ls_colors'][0], COLORS['ls_colors'][1], COLORS['ls_colors'][2], COLORS['ls_colors'][3]]
|
| 262 |
-
for i, (k, l) in enumerate(zip(LS_KEYS, LS_LABELS_EN)):
|
| 263 |
-
if k not in full_losses: continue
|
| 264 |
-
m = np.array(full_losses[k]['member_losses']); nm = np.array(full_losses[k]['non_member_losses'])
|
| 265 |
-
y_true = np.concatenate([np.ones(len(m)), np.zeros(len(nm))]); y_scores = np.concatenate([-m, -nm])
|
| 266 |
-
fpr, tpr, _ = roc_curve(y_true, y_scores); auc_val = roc_auc_score(y_true, y_scores)
|
| 267 |
-
ax.plot(fpr, tpr, color=ls_colors[i], lw=2.5, label=f'{l} (AUC={auc_val:.4f})')
|
| 268 |
-
ax.plot([0,1], [0,1], '--', color=COLORS['text_dim'], lw=1.5, label='Random')
|
| 269 |
-
ax.set_xlabel('False Positive Rate', fontsize=12, fontweight='medium'); ax.set_ylabel('True Positive Rate', fontsize=12, fontweight='medium')
|
| 270 |
-
ax.set_title('ROC Curves: Label Smoothing', fontsize=14, fontweight='bold', pad=15)
|
| 271 |
-
ax.legend(fontsize=10, facecolor=COLORS['bg'], edgecolor='none', labelcolor=COLORS['text'])
|
| 272 |
-
|
| 273 |
-
ax = axes[1]
|
| 274 |
-
if 'baseline' in full_losses:
|
| 275 |
-
ml_base = np.array(full_losses['baseline']['member_losses']); nl_base = np.array(full_losses['baseline']['non_member_losses'])
|
| 276 |
-
y_true = np.concatenate([np.ones(len(ml_base)), np.zeros(len(nl_base))]); y_scores = np.concatenate([-ml_base, -nl_base])
|
| 277 |
-
fpr, tpr, _ = roc_curve(y_true, y_scores); ax.plot(fpr, tpr, color=COLORS['danger'], lw=2.5, label=f'Baseline (AUC={bl_auc:.4f})')
|
| 278 |
-
for i, s in enumerate(OP_SIGMAS):
|
| 279 |
-
rng_m = np.random.RandomState(42); rng_nm = np.random.RandomState(137)
|
| 280 |
-
mp = ml_base + rng_m.normal(0, s, len(ml_base)); np_ = nl_base + rng_nm.normal(0, s, len(nl_base))
|
| 281 |
-
y_scores_p = np.concatenate([-mp, -np_]); fpr_p, tpr_p, _ = roc_curve(y_true, y_scores_p); auc_p = roc_auc_score(y_true, y_scores_p)
|
| 282 |
-
ax.plot(fpr_p, tpr_p, color=COLORS['op_colors'][i], lw=2, label=f'OP(s={s}) (AUC={auc_p:.4f})')
|
| 283 |
-
ax.plot([0,1], [0,1], '--', color=COLORS['text_dim'], lw=1.5, label='Random')
|
| 284 |
-
ax.set_xlabel('False Positive Rate', fontsize=12, fontweight='medium'); ax.set_ylabel('True Positive Rate', fontsize=12, fontweight='medium')
|
| 285 |
-
ax.set_title('ROC Curves: Output Perturbation', fontsize=14, fontweight='bold', pad=15)
|
| 286 |
-
ax.legend(fontsize=10, facecolor=COLORS['bg'], edgecolor='none', labelcolor=COLORS['text'], loc='lower right')
|
| 287 |
-
plt.tight_layout()
|
| 288 |
-
return fig
|
| 289 |
-
|
| 290 |
-
def fig_tpr_at_low_fpr():
|
| 291 |
-
fig, axes = plt.subplots(1, 2, figsize=(16, 6.5))
|
| 292 |
-
apply_light_style(fig, axes)
|
| 293 |
-
labels_all, tpr5_all, tpr1_all, colors_all = [], [], [], []
|
| 294 |
-
ls_c = [COLORS['baseline']] + COLORS['ls_colors']
|
| 295 |
-
for i, (k, l) in enumerate(zip(LS_KEYS, LS_LABELS_EN)):
|
| 296 |
-
labels_all.append(l); tpr5_all.append(gm(k, 'tpr_at_5fpr')); tpr1_all.append(gm(k, 'tpr_at_1fpr')); colors_all.append(ls_c[i])
|
| 297 |
-
for i, (k, l) in enumerate(zip(OP_KEYS, OP_LABELS_EN)):
|
| 298 |
-
labels_all.append(l); tpr5_all.append(gm(k, 'tpr_at_5fpr')); tpr1_all.append(gm(k, 'tpr_at_1fpr')); colors_all.append(COLORS['op_colors'][i])
|
| 299 |
-
x = range(len(labels_all))
|
| 300 |
-
|
| 301 |
-
ax = axes[0]
|
| 302 |
-
bars = ax.bar(x, tpr5_all, color=colors_all, width=0.65, edgecolor='none', zorder=3)
|
| 303 |
-
for b, v in zip(bars, tpr5_all): ax.text(b.get_x()+b.get_width()/2, v+0.005, f'{v:.3f}', ha='center', fontsize=9, fontweight='semibold', color=COLORS['text'])
|
| 304 |
-
ax.set_ylabel('TPR @ 5% FPR', fontsize=12, fontweight='medium'); ax.set_title('Attack Power at 5% FPR', fontsize=14, fontweight='bold', pad=15)
|
| 305 |
-
ax.set_xticks(x); ax.set_xticklabels(labels_all, rotation=35, ha='right', fontsize=10)
|
| 306 |
-
ax.axhline(0.05, color=COLORS['warning'], ls='--', lw=1.5, alpha=0.7, label='Random (0.05)')
|
| 307 |
-
ax.legend(facecolor=COLORS['bg'], edgecolor='none', labelcolor=COLORS['text'], fontsize=10)
|
| 308 |
-
|
| 309 |
-
ax = axes[1]
|
| 310 |
-
bars = ax.bar(x, tpr1_all, color=colors_all, width=0.65, edgecolor='none', zorder=3)
|
| 311 |
-
for b, v in zip(bars, tpr1_all): ax.text(b.get_x()+b.get_width()/2, v+0.003, f'{v:.3f}', ha='center', fontsize=9, fontweight='semibold', color=COLORS['text'])
|
| 312 |
-
ax.set_ylabel('TPR @ 1% FPR', fontsize=12, fontweight='medium'); ax.set_title('Attack Power at 1% FPR (Strict)', fontsize=14, fontweight='bold', pad=15)
|
| 313 |
-
ax.set_xticks(x); ax.set_xticklabels(labels_all, rotation=35, ha='right', fontsize=10)
|
| 314 |
-
ax.axhline(0.01, color=COLORS['warning'], ls='--', lw=1.5, alpha=0.7, label='Random (0.01)')
|
| 315 |
-
ax.legend(facecolor=COLORS['bg'], edgecolor='none', labelcolor=COLORS['text'], fontsize=10)
|
| 316 |
-
plt.tight_layout()
|
| 317 |
-
return fig
|
| 318 |
-
|
| 319 |
-
def fig_acc_bar():
|
| 320 |
-
names, vals, clrs = [], [], []
|
| 321 |
-
ls_c = [COLORS['baseline']] + COLORS['ls_colors']
|
| 322 |
-
for i, (k, l) in enumerate(zip(LS_KEYS, LS_LABELS_EN)):
|
| 323 |
-
if k in utility_results: names.append(l); vals.append(utility_results[k]['accuracy']*100); clrs.append(ls_c[i])
|
| 324 |
-
for i, (k, l) in enumerate(zip(OP_KEYS, OP_LABELS_EN)):
|
| 325 |
-
if k in perturb_results: names.append(l); vals.append(bl_acc); clrs.append(COLORS['op_colors'][i])
|
| 326 |
-
fig, ax = plt.subplots(figsize=(14, 6))
|
| 327 |
-
apply_light_style(fig, ax)
|
| 328 |
-
bars = ax.bar(range(len(names)), vals, color=clrs, width=0.65, edgecolor='none', zorder=3)
|
| 329 |
-
for b, v in zip(bars, vals): ax.text(b.get_x()+b.get_width()/2, v+1, f'{v:.1f}%', ha='center', fontsize=10, fontweight='semibold', color=COLORS['text'])
|
| 330 |
-
ax.set_ylabel('Test Accuracy (%)', fontsize=12, fontweight='medium'); ax.set_title('Model Utility: Test Accuracy', fontsize=14, fontweight='bold', pad=20)
|
| 331 |
-
ax.set_ylim(0, 105); ax.set_xticks(range(len(names))); ax.set_xticklabels(names, rotation=30, ha='right', fontsize=10)
|
| 332 |
-
plt.tight_layout()
|
| 333 |
-
return fig
|
| 334 |
|
| 335 |
def fig_tradeoff():
|
| 336 |
-
fig,
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
ax.
|
| 348 |
-
ax.
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
ax.
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
ax
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
line1 = ax.plot(eps_vals, auc_vals, 'o-', color=COLORS['danger'], lw=3, ms=9, label='MIA AUC (left)', zorder=5)
|
| 366 |
-
line2 = ax2.plot(eps_vals, acc_vals, 's--', color=COLORS['accent'], lw=3, ms=9, label='Utility % (right)', zorder=5)
|
| 367 |
-
ax.axhline(0.5, color=COLORS['text_dim'], ls=':', alpha=0.5)
|
| 368 |
-
ax.set_xlabel('Label Smoothing epsilon', fontsize=12, fontweight='medium')
|
| 369 |
-
ax.set_ylabel('MIA AUC', fontsize=12, fontweight='medium', color=COLORS['danger'])
|
| 370 |
-
ax2.set_ylabel('Utility (%)', fontsize=12, fontweight='medium', color=COLORS['accent'])
|
| 371 |
-
ax.set_title('Label Smoothing Trends', fontsize=14, fontweight='bold', pad=15)
|
| 372 |
-
ax.tick_params(axis='y', labelcolor=COLORS['danger']); ax2.tick_params(axis='y', labelcolor=COLORS['accent'])
|
| 373 |
-
ax2.spines['right'].set_color(COLORS['accent']); ax2.spines['left'].set_color(COLORS['danger'])
|
| 374 |
-
lines = line1 + line2; labels = [l.get_label() for l in lines]
|
| 375 |
-
ax.legend(lines, labels, fontsize=10, facecolor=COLORS['bg'], edgecolor='none', labelcolor=COLORS['text'])
|
| 376 |
-
|
| 377 |
-
ax = axes[1]
|
| 378 |
-
sig_vals = OP_SIGMAS; auc_op = [gm(k, 'auc') for k in OP_KEYS]
|
| 379 |
-
ax.plot(sig_vals, auc_op, 'o-', color=COLORS['success'], lw=3, ms=9, zorder=5, label='MIA AUC')
|
| 380 |
-
ax.axhline(bl_auc, color=COLORS['danger'], ls='--', lw=2, alpha=0.6, label=f'Baseline ({bl_auc:.4f})')
|
| 381 |
-
ax.axhline(0.5, color=COLORS['text_dim'], ls=':', alpha=0.5, label='Random (0.5)')
|
| 382 |
-
ax.fill_between(sig_vals, auc_op, bl_auc, alpha=0.2, color=COLORS['success'], label='AUC Reduction')
|
| 383 |
-
ax.set_xlabel('Perturbation Sigma', fontsize=12, fontweight='medium'); ax.set_ylabel('MIA AUC', fontsize=12, fontweight='medium')
|
| 384 |
-
ax.set_title('Output Perturbation Trends', fontsize=14, fontweight='bold', pad=15)
|
| 385 |
-
ax.legend(fontsize=10, facecolor=COLORS['bg'], edgecolor='none', labelcolor=COLORS['text'])
|
| 386 |
-
plt.tight_layout()
|
| 387 |
-
return fig
|
| 388 |
-
|
| 389 |
-
def fig_loss_gap_waterfall():
|
| 390 |
-
fig, ax = plt.subplots(figsize=(14, 6.5))
|
| 391 |
-
apply_light_style(fig, ax)
|
| 392 |
-
names, gaps, clrs = [], [], []
|
| 393 |
-
ls_c = [COLORS['baseline']] + COLORS['ls_colors']
|
| 394 |
-
for i, (k, l) in enumerate(zip(LS_KEYS, LS_LABELS_EN)):
|
| 395 |
-
names.append(l); gaps.append(gm(k, 'loss_gap')); clrs.append(ls_c[i])
|
| 396 |
-
for i, (k, l) in enumerate(zip(OP_KEYS, OP_LABELS_EN)):
|
| 397 |
-
names.append(l); gaps.append(gm(k, 'loss_gap')); clrs.append(COLORS['op_colors'][i])
|
| 398 |
-
bars = ax.bar(range(len(names)), gaps, color=clrs, width=0.65, edgecolor='none', zorder=3)
|
| 399 |
-
for b, v in zip(bars, gaps):
|
| 400 |
-
ax.text(b.get_x()+b.get_width()/2, v+0.0005, f'{v:.4f}', ha='center', fontsize=10, fontweight='semibold', color=COLORS['text'])
|
| 401 |
-
ax.set_ylabel('Loss Gap', fontsize=12, fontweight='medium')
|
| 402 |
-
ax.set_title('Member vs Non-Member Loss Gap', fontsize=14, fontweight='bold', pad=20)
|
| 403 |
-
ax.set_xticks(range(len(names))); ax.set_xticklabels(names, rotation=30, ha='right', fontsize=10)
|
| 404 |
-
ax.annotate('Smaller gap = Better Privacy', xy=(8, gaps[0]*0.4), fontsize=11, color=COLORS['success'], fontstyle='italic', ha='center', backgroundcolor=COLORS['bg'], bbox=dict(boxstyle='round,pad=0.4', facecolor=COLORS['panel'], edgecolor=COLORS['success'], alpha=0.8))
|
| 405 |
-
plt.tight_layout()
|
| 406 |
-
return fig
|
| 407 |
-
|
| 408 |
-
def fig_gauge(loss_val, m_mean, nm_mean, thr, m_std, nm_std):
|
| 409 |
-
fig, ax = plt.subplots(figsize=(10, 3.5))
|
| 410 |
-
fig.patch.set_facecolor(COLORS['bg'])
|
| 411 |
-
ax.set_facecolor(COLORS['panel'])
|
| 412 |
-
xlo = min(m_mean - 3.5*m_std, loss_val - 0.005); xhi = max(nm_mean + 3.5*nm_std, loss_val + 0.005)
|
| 413 |
-
|
| 414 |
-
# 绘制区域
|
| 415 |
-
ax.axvspan(xlo, thr, alpha=0.2, color=COLORS['accent'], label='Member Zone')
|
| 416 |
-
ax.axvspan(thr, xhi, alpha=0.2, color=COLORS['danger'], label='Non-Member Zone')
|
| 417 |
-
|
| 418 |
-
# 添加成员/非成员均值虚线
|
| 419 |
-
ax.axvline(m_mean, color=COLORS['accent'], lw=2, ls=':', alpha=0.8, zorder=2)
|
| 420 |
-
ax.text(m_mean, 1.02, f'Member Mean\n{m_mean:.4f}', ha='center', va='bottom', fontsize=9, color=COLORS['accent'], transform=ax.get_xaxis_transform())
|
| 421 |
-
|
| 422 |
-
ax.axvline(nm_mean, color=COLORS['danger'], lw=2, ls=':', alpha=0.8, zorder=2)
|
| 423 |
-
ax.text(nm_mean, 1.02, f'Non-Member Mean\n{nm_mean:.4f}', ha='center', va='bottom', fontsize=9, color=COLORS['danger'], transform=ax.get_xaxis_transform())
|
| 424 |
-
|
| 425 |
-
# 绘制阈值线
|
| 426 |
-
ax.axvline(thr, color=COLORS['text_dim'], lw=2.5, ls='--', zorder=3)
|
| 427 |
-
ax.text(thr, 1.15, f'Threshold\n{thr:.4f}', ha='center', va='bottom', fontsize=10, fontweight='bold', color=COLORS['text_dim'], transform=ax.get_xaxis_transform())
|
| 428 |
-
|
| 429 |
-
# 绘制当前 Loss 点
|
| 430 |
-
mc = COLORS['accent'] if loss_val < thr else COLORS['danger']
|
| 431 |
-
ax.plot(loss_val, 0.5, marker='o', ms=18, color='white', mec=mc, mew=3, zorder=5, transform=ax.get_xaxis_transform())
|
| 432 |
-
ax.text(loss_val, 0.75, f'Current Loss\n{loss_val:.4f}', ha='center', fontsize=11, fontweight='bold', color=mc, transform=ax.get_xaxis_transform())
|
| 433 |
-
|
| 434 |
-
# 区域标注
|
| 435 |
-
ax.text((xlo+thr)/2, 0.25, 'MEMBER', ha='center', fontsize=12, color=COLORS['accent'], alpha=0.8, fontweight='bold', transform=ax.get_xaxis_transform())
|
| 436 |
-
ax.text((thr+xhi)/2, 0.25, 'NON-MEMBER', ha='center', fontsize=12, color=COLORS['danger'], alpha=0.8, fontweight='bold', transform=ax.get_xaxis_transform())
|
| 437 |
-
|
| 438 |
-
ax.set_xlim(xlo, xhi); ax.set_yticks([])
|
| 439 |
for s in ax.spines.values(): s.set_visible(False)
|
| 440 |
-
ax.spines['bottom'].set_visible(True); ax.spines['bottom'].set_color(
|
| 441 |
-
ax.tick_params(colors=
|
| 442 |
-
|
| 443 |
-
plt.tight_layout()
|
| 444 |
-
return fig
|
| 445 |
|
| 446 |
# ================================================================
|
| 447 |
-
#
|
| 448 |
# ================================================================
|
| 449 |
def cb_sample(src):
|
| 450 |
-
pool
|
| 451 |
-
s
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
</tr>
|
| 471 |
-
<tr>
|
| 472 |
-
<td style="padding: 10px; color: #1D1D1F; border-bottom: 1px solid #E2E8F0;">成绩</td>
|
| 473 |
-
<td style="padding: 10px; color: #1D1D1F; border-bottom: 1px solid #E2E8F0;">{clean_text(str(m.get('score','')))} 分</td>
|
| 474 |
-
</tr>
|
| 475 |
-
<tr>
|
| 476 |
-
<td style="padding: 10px; color: #1D1D1F;">类型</td>
|
| 477 |
-
<td style="padding: 10px; color: #1D1D1F;">{TYPE_CN.get(s.get('task_type',''), '')}</td>
|
| 478 |
-
</tr>
|
| 479 |
-
</table>
|
| 480 |
-
"""
|
| 481 |
-
return md, clean_text(s.get('question', '')), clean_text(s.get('answer', ''))
|
| 482 |
-
|
| 483 |
-
ATK_CHOICES = (
|
| 484 |
-
["基线模型 (Baseline)"] +
|
| 485 |
-
[f"标签平滑 (ε={e})" for e in [0.02, 0.05, 0.1, 0.2]] +
|
| 486 |
-
[f"输出扰动 (σ={s})" for s in OP_SIGMAS]
|
| 487 |
-
)
|
| 488 |
-
ATK_MAP = {"基线模型 (Baseline)": "baseline"}
|
| 489 |
-
for e in [0.02, 0.05, 0.1, 0.2]: ATK_MAP[f"标签平滑 (ε={e})"] = f"smooth_eps_{e}"
|
| 490 |
-
for s in OP_SIGMAS: ATK_MAP[f"输出扰动 (σ={s})"] = f"perturbation_{s}"
|
| 491 |
-
|
| 492 |
-
def cb_attack(idx, src, target):
|
| 493 |
-
is_mem = "训练集" in src
|
| 494 |
-
pool = member_data if is_mem else non_member_data
|
| 495 |
-
idx = min(int(idx), len(pool)-1)
|
| 496 |
-
sample = pool[idx]
|
| 497 |
-
key = ATK_MAP.get(target, "baseline")
|
| 498 |
-
is_op = key.startswith("perturbation_")
|
| 499 |
-
|
| 500 |
if is_op:
|
| 501 |
-
sigma
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
loss = base_loss + np.random.normal(0, sigma)
|
| 508 |
-
mm = gm("baseline", "member_loss_mean", 0.19); nm_m = gm("baseline", "non_member_loss_mean", 0.20)
|
| 509 |
-
ms = gm("baseline", "member_loss_std", 0.03); ns = gm("baseline", "non_member_loss_std", 0.03)
|
| 510 |
-
auc_v = gm(key, "auc"); lbl = f"OP(σ={sigma})"
|
| 511 |
else:
|
| 512 |
-
info
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
lbl = "Baseline" if key == "baseline" else f"LS(ε={key.replace('smooth_eps_','')})"
|
| 521 |
-
|
| 522 |
-
thr = (mm + nm_m) / 2
|
| 523 |
-
pred = loss < thr
|
| 524 |
-
correct = pred == is_mem
|
| 525 |
-
gauge = fig_gauge(loss, mm, nm_m, thr, ms, ns)
|
| 526 |
-
|
| 527 |
-
pl = "🔴 训练成员" if pred else "🟢 非训练成员"
|
| 528 |
-
al = "🔴 训练成员" if is_mem else "🟢 非训练成员"
|
| 529 |
-
|
| 530 |
if correct and pred and is_mem:
|
| 531 |
-
|
| 532 |
elif correct:
|
| 533 |
-
|
| 534 |
else:
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
<
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
)
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
for s in OP_SIGMAS: EVAL_KEY_MAP[f"输出扰动 (σ={s})"] = "baseline"
|
| 573 |
-
|
| 574 |
-
def cb_eval(model_choice):
|
| 575 |
-
k = EVAL_KEY_MAP.get(model_choice, "baseline")
|
| 576 |
-
acc = gu(k) if "输出扰动" not in model_choice else bl_acc
|
| 577 |
-
q = EVAL_POOL[np.random.randint(len(EVAL_POOL))]
|
| 578 |
-
ok = q.get(k, q.get('baseline', False))
|
| 579 |
-
ic = "✅ 正确" if ok else "❌ 错误"
|
| 580 |
-
note = "\n\n> 输出扰动不改变模型参数,准确率与基线一致。" if "输出扰动" in model_choice else ""
|
| 581 |
-
|
| 582 |
-
table_html = f"""
|
| 583 |
-
<table style="width:100%; border-collapse: collapse; margin-top: 15px; border: 1px solid #E2E8F0; border-radius: 8px; overflow: hidden;">
|
| 584 |
-
<tbody>
|
| 585 |
-
<tr>
|
| 586 |
-
<td style="padding: 12px; color: #86868B; font-weight: 600; border-bottom: 1px solid #E2E8F0; width: 100px;">类型</td>
|
| 587 |
-
<td style="padding: 12px; color: #1D1D1F; border-bottom: 1px solid #E2E8F0;">{q['type_cn']}</td>
|
| 588 |
-
</tr>
|
| 589 |
-
<tr>
|
| 590 |
-
<td style="padding: 12px; color: #86868B; font-weight: 600; border-bottom: 1px solid #E2E8F0;">题目</td>
|
| 591 |
-
<td style="padding: 12px; color: #1D1D1F; border-bottom: 1px solid #E2E8F0;">{q['question']}</td>
|
| 592 |
-
</tr>
|
| 593 |
-
<tr>
|
| 594 |
-
<td style="padding: 12px; color: #86868B; font-weight: 600; border-bottom: 1px solid #E2E8F0;">正确答案</td>
|
| 595 |
-
<td style="padding: 12px; color: #1D1D1F; border-bottom: 1px solid #E2E8F0;">{q['answer']}</td>
|
| 596 |
-
</tr>
|
| 597 |
-
<tr>
|
| 598 |
-
<td style="padding: 12px; color: #86868B; font-weight: 600;">判定</td>
|
| 599 |
-
<td style="padding: 12px; color: #1D1D1F;">{ic}</td>
|
| 600 |
-
</tr>
|
| 601 |
-
</tbody>
|
| 602 |
-
</table>
|
| 603 |
-
"""
|
| 604 |
-
return (f"<div style='font-weight: 600; margin-bottom: 10px;'>🤖 模型: {model_choice} <span style='margin-left: 20px; color: #86868B;'>🎯 准确率: {acc:.1f}%</span></div>" + table_html + note)
|
| 605 |
-
|
| 606 |
-
def build_full_table():
|
| 607 |
-
rows = []
|
| 608 |
-
for k, l in zip(LS_KEYS, LS_LABELS_CN):
|
| 609 |
-
if k in mia_results:
|
| 610 |
-
m = mia_results[k]; u = gu(k)
|
| 611 |
-
t = "—" if k == "baseline" else "训练期"; d = "" if k == "baseline" else f"{m['auc']-bl_auc:+.4f}"
|
| 612 |
rows.append(f"| {l} | {t} | {m['auc']:.4f} | {m['attack_accuracy']:.4f} | {m['precision']:.4f} | {m['recall']:.4f} | {m['f1']:.4f} | {m['tpr_at_5fpr']:.4f} | {m['tpr_at_1fpr']:.4f} | {m['loss_gap']:.4f} | {u:.1f}% | {d} |")
|
| 613 |
-
for k,
|
| 614 |
-
if k in
|
| 615 |
-
m
|
| 616 |
-
rows.append(f"| {l} |
|
| 617 |
-
|
| 618 |
-
"|---|---|---|---|---|---|---|---|---|---|---|---|")
|
| 619 |
-
return header + "\n" + "\n".join(rows)
|
| 620 |
|
| 621 |
# ================================================================
|
| 622 |
-
# CSS
|
| 623 |
# ================================================================
|
| 624 |
-
CSS
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
-
|
| 632 |
-
}
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
}
|
| 639 |
-
|
| 640 |
-
.
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
}
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
.
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
}
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
.
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
.
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
}
|
| 678 |
-
|
| 679 |
-
/* === Tab面板 === */
|
| 680 |
-
.tabitem {
|
| 681 |
-
background-color: var(--card-bg) !important;
|
| 682 |
-
border-radius: 18px !important;
|
| 683 |
-
border: none !important;
|
| 684 |
-
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08) !important;
|
| 685 |
-
padding: 40px !important;
|
| 686 |
-
margin-top: 20px !important;
|
| 687 |
-
}
|
| 688 |
-
|
| 689 |
-
/* === Tab导航 === */
|
| 690 |
-
.tab-nav {
|
| 691 |
-
border-bottom: none !important;
|
| 692 |
-
gap: 10px !important;
|
| 693 |
-
background: transparent !important;
|
| 694 |
-
padding-bottom: 5px !important;
|
| 695 |
-
}
|
| 696 |
-
|
| 697 |
-
.tab-nav button {
|
| 698 |
-
font-size: 15px !important;
|
| 699 |
-
padding: 10px 20px !important;
|
| 700 |
-
font-weight: 500 !important;
|
| 701 |
-
color: var(--text-gray) !important;
|
| 702 |
-
background: rgba(0,0,0,0.03) !important;
|
| 703 |
-
border: none !important;
|
| 704 |
-
border-radius: 12px !important;
|
| 705 |
-
transition: all 0.2s ease !important;
|
| 706 |
-
}
|
| 707 |
-
|
| 708 |
-
.tab-nav button:hover {
|
| 709 |
-
background: rgba(0,0,0,0.06) !important;
|
| 710 |
-
color: var(--text-dark) !important;
|
| 711 |
-
}
|
| 712 |
-
|
| 713 |
-
.tab-nav button.selected {
|
| 714 |
-
color: var(--primary-blue) !important;
|
| 715 |
-
background: #E5F1FF !important;
|
| 716 |
-
font-weight: 600 !important;
|
| 717 |
-
}
|
| 718 |
-
|
| 719 |
-
/* === 文字排版 & 表格 === */
|
| 720 |
-
.prose { color: var(--text-dark) !important; }
|
| 721 |
-
|
| 722 |
-
.prose h2 {
|
| 723 |
-
color: var(--text-dark) !important;
|
| 724 |
-
font-weight: 700 !important;
|
| 725 |
-
border-bottom: 1px solid var(--border-color) !important;
|
| 726 |
-
padding-bottom: 12px !important;
|
| 727 |
-
margin-top: 30px !important;
|
| 728 |
-
}
|
| 729 |
-
|
| 730 |
-
.prose h3 {
|
| 731 |
-
color: var(--text-dark) !important;
|
| 732 |
-
font-weight: 600 !important;
|
| 733 |
-
margin-top: 24px !important;
|
| 734 |
-
}
|
| 735 |
-
|
| 736 |
-
.prose h4 {
|
| 737 |
-
color: var(--text-gray) !important;
|
| 738 |
-
font-weight: 600 !important;
|
| 739 |
-
margin-bottom: 12px !important;
|
| 740 |
-
}
|
| 741 |
-
|
| 742 |
-
.prose table {
|
| 743 |
-
border-collapse: separate !important;
|
| 744 |
-
border-spacing: 0 !important;
|
| 745 |
-
width: 100% !important;
|
| 746 |
-
border: 1px solid var(--border-color) !important;
|
| 747 |
-
border-radius: 12px !important;
|
| 748 |
-
overflow: hidden !important;
|
| 749 |
-
box-shadow: 0 2px 8px rgba(0,0,0,0.04) !important;
|
| 750 |
-
}
|
| 751 |
-
|
| 752 |
-
.prose th {
|
| 753 |
-
background: #F9F9F9 !important;
|
| 754 |
-
color: var(--text-gray) !important;
|
| 755 |
-
font-weight: 600 !important;
|
| 756 |
-
padding: 14px 18px !important;
|
| 757 |
-
text-align: left !important;
|
| 758 |
-
border-bottom: 1px solid var(--border-color) !important;
|
| 759 |
-
white-space: nowrap !important;
|
| 760 |
-
}
|
| 761 |
-
|
| 762 |
-
.prose td {
|
| 763 |
-
padding: 14px 18px !important;
|
| 764 |
-
color: var(--text-dark) !important;
|
| 765 |
-
border-bottom: 1px solid var(--border-color) !important;
|
| 766 |
-
background: var(--card-bg) !important;
|
| 767 |
-
white-space: nowrap !important;
|
| 768 |
-
}
|
| 769 |
-
|
| 770 |
-
.prose tr:last-child td {
|
| 771 |
-
border-bottom: none !important;
|
| 772 |
-
}
|
| 773 |
-
|
| 774 |
-
.prose tr:hover td {
|
| 775 |
-
background: #F5F7FA !important;
|
| 776 |
-
}
|
| 777 |
-
|
| 778 |
-
/* === 按钮 === */
|
| 779 |
-
button.primary {
|
| 780 |
-
background-color: var(--primary-blue) !important;
|
| 781 |
-
color: white !important;
|
| 782 |
-
border: none !important;
|
| 783 |
-
border-radius: 10px !important;
|
| 784 |
-
font-weight: 600 !important;
|
| 785 |
-
padding: 12px 24px !important;
|
| 786 |
-
box-shadow: 0 2px 6px rgba(0, 122, 255, 0.25) !important;
|
| 787 |
-
transition: all 0.2s !important;
|
| 788 |
-
}
|
| 789 |
-
|
| 790 |
-
button.primary:hover {
|
| 791 |
-
background-color: #0062CC !important;
|
| 792 |
-
box-shadow: 0 4px 10px rgba(0, 122, 255, 0.35) !important;
|
| 793 |
-
transform: translateY(-1px) !important;
|
| 794 |
-
}
|
| 795 |
-
|
| 796 |
-
/* === 内部小区块 (卡片) === */
|
| 797 |
-
.card-wrap {
|
| 798 |
-
background: var(--card-bg) !important;
|
| 799 |
-
border: 1px solid var(--border-color) !important;
|
| 800 |
-
border-radius: 14px !important;
|
| 801 |
-
padding: 24px !important;
|
| 802 |
-
box-shadow: 0 2px 8px rgba(0,0,0,0.04) !important;
|
| 803 |
-
}
|
| 804 |
-
|
| 805 |
-
.block.svelte-12cmxck {
|
| 806 |
-
border-radius: 12px !important;
|
| 807 |
-
border-color: var(--border-color) !important;
|
| 808 |
-
}
|
| 809 |
-
|
| 810 |
-
.input-label {
|
| 811 |
-
color: var(--text-gray) !important;
|
| 812 |
-
font-weight: 500 !important;
|
| 813 |
-
}
|
| 814 |
-
|
| 815 |
-
footer { display: none !important; }
|
| 816 |
"""
|
| 817 |
|
| 818 |
# ================================================================
|
| 819 |
-
# UI
|
| 820 |
# ================================================================
|
| 821 |
-
with gr.Blocks(title="MIA
|
| 822 |
-
|
| 823 |
-
|
| 824 |
-
<
|
| 825 |
-
<
|
| 826 |
-
|
|
|
|
|
|
|
|
|
|
| 827 |
</div>""")
|
| 828 |
|
| 829 |
-
with gr.Tab("
|
| 830 |
-
gr.Markdown(f"##
|
| 831 |
-
|
| 832 |
-
|
| 833 |
-
|
| 834 |
-
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
|
| 843 |
-
|
| 844 |
-
|
| 845 |
-
|
| 846 |
-
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
|
| 850 |
-
|
| 851 |
-
|
| 852 |
-
|
| 853 |
-
|
| 854 |
-
|
| 855 |
-
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
|
| 862 |
-
|
| 863 |
-
|
| 864 |
-
|
| 865 |
-
|
| 866 |
-
|
| 867 |
-
</table>
|
| 868 |
-
</div>
|
| 869 |
-
<div class="card-wrap" style="flex:1; display:flex; flex-direction:column;">
|
| 870 |
-
<h3 style="margin:0 0 15px;font-size:18px;color:#1D1D1F;">📚 任务分布</h3>
|
| 871 |
-
<table style="width:100%;border-collapse:collapse;font-size:14px; margin-bottom:auto;">
|
| 872 |
-
<tr style="background:#F9F9F9;"><th style="padding:12px;text-align:left;color:#86868B;">类别</th><th style="padding:12px;text-align:left;color:#86868B;">数量</th><th style="padding:12px;text-align:left;color:#86868B;">占比</th></tr>
|
| 873 |
-
<tr><td style="padding:12px;border-bottom:1px solid #E2E8F0;color:#1D1D1F;">🔢 基础计算</td><td style="padding:12px;border-bottom:1px solid #E2E8F0;color:#1D1D1F;">800</td><td style="padding:12px;border-bottom:1px solid #E2E8F0;color:#1D1D1F;">40%</td></tr>
|
| 874 |
-
<tr><td style="padding:12px;border-bottom:1px solid #E2E8F0;color:#1D1D1F;">📝 应用题</td><td style="padding:12px;border-bottom:1px solid #E2E8F0;color:#1D1D1F;">600</td><td style="padding:12px;border-bottom:1px solid #E2E8F0;color:#1D1D1F;">30%</td></tr>
|
| 875 |
-
<tr><td style="padding:12px;border-bottom:1px solid #E2E8F0;color:#1D1D1F;">💬 概念问答</td><td style="padding:12px;border-bottom:1px solid #E2E8F0;color:#1D1D1F;">400</td><td style="padding:12px;border-bottom:1px solid #E2E8F0;color:#1D1D1F;">20%</td></tr>
|
| 876 |
-
<tr><td style="padding:12px;border-bottom:1px solid #E2E8F0;color:#1D1D1F;">✏️ 错题订正</td><td style="padding:12px;border-bottom:1px solid #E2E8F0;color:#1D1D1F;">200</td><td style="padding:12px;border-bottom:1px solid #E2E8F0;color:#1D1D1F;">10%</td></tr>
|
| 877 |
-
</table>
|
| 878 |
-
</div></div>""")
|
| 879 |
-
|
| 880 |
-
gr.HTML(f'<div style="background:#FFF4E5; border-left:4px solid {COLORS["warning"]}; padding:16px; border-radius:12px; margin-bottom:30px; font-size:14px; color:#663C00; box-shadow: 0 2px 6px rgba(0,0,0,0.05);">⚠️ <b>注意:</b>两组数据格式完全相同(均含隐私字段),这是MIA实验的标准设置——攻击者无法从格式区分。</div>')
|
| 881 |
-
|
| 882 |
-
gr.Markdown("### 🔍 数据样例提取")
|
| 883 |
-
with gr.Row():
|
| 884 |
-
with gr.Column(scale=1):
|
| 885 |
-
gr.Markdown("#### ⚙️ 提取控制台")
|
| 886 |
-
d_src = gr.Radio(["成员数据(训练集)", "非成员数据(测试集)"], value="成员数据(训练集)", label="目标数据源")
|
| 887 |
-
d_btn = gr.Button("🎲 随机提取样本", variant="primary")
|
| 888 |
-
d_meta = gr.Markdown()
|
| 889 |
with gr.Column(scale=2):
|
| 890 |
-
gr.
|
| 891 |
-
|
| 892 |
-
|
| 893 |
-
|
| 894 |
-
|
| 895 |
-
|
| 896 |
-
|
| 897 |
-
|
| 898 |
-
|
| 899 |
-
|
| 900 |
-
|
| 901 |
-
a_s = gr.Radio(["成员数据(训练集)", "非成员数据(测试集)"], value="成员数据(训练集)", label="📂 输入数据源")
|
| 902 |
-
a_i = gr.Slider(0, 999, step=1, value=12, label="📌 定位样本 ID")
|
| 903 |
-
a_b = gr.Button("⚡ 执行成员推理攻击", variant="primary")
|
| 904 |
-
a_qt = gr.HTML()
|
| 905 |
with gr.Column(scale=2):
|
| 906 |
-
gr.
|
| 907 |
-
|
| 908 |
-
|
| 909 |
-
|
| 910 |
-
|
| 911 |
-
|
| 912 |
-
|
| 913 |
-
|
| 914 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 915 |
gr.Plot(value=fig_auc_bar())
|
| 916 |
|
| 917 |
-
gr.Markdown("### 2
|
| 918 |
-
gr.Plot(value=
|
| 919 |
|
| 920 |
-
gr.Markdown("### 3
|
| 921 |
-
gr.Plot(value=
|
| 922 |
|
| 923 |
-
gr.Markdown(f"### 4
|
| 924 |
-
gr.Plot(value=
|
| 925 |
|
| 926 |
-
gr.Markdown("### 5
|
| 927 |
-
gr.Plot(value=
|
| 928 |
|
| 929 |
-
gr.Markdown("### 6
|
| 930 |
-
gr.Plot(value=
|
| 931 |
|
| 932 |
-
with gr.Accordion("
|
| 933 |
gr.Plot(value=fig_loss_dist())
|
| 934 |
-
with gr.Accordion("
|
| 935 |
-
gr.Markdown(
|
| 936 |
|
| 937 |
-
with gr.Tab("
|
| 938 |
-
gr.Markdown("##
|
| 939 |
-
with gr.Row():
|
| 940 |
-
with gr.Column(): gr.Plot(value=
|
| 941 |
with gr.Column(): gr.Plot(value=fig_tradeoff())
|
| 942 |
-
gr.Markdown(f">
|
| 943 |
-
|
| 944 |
-
gr.
|
| 945 |
-
with gr.Row():
|
| 946 |
with gr.Column(scale=1):
|
| 947 |
-
gr.
|
| 948 |
-
|
| 949 |
-
e_b = gr.Button("🎲 随机抽题测试", variant="primary")
|
| 950 |
with gr.Column(scale=2):
|
| 951 |
-
gr.
|
| 952 |
-
|
| 953 |
-
e_b.click(cb_eval, [e_m], [e_r])
|
| 954 |
|
| 955 |
-
with gr.Tab("
|
| 956 |
-
# 核心修复:补全所有的输出扰动数据
|
| 957 |
gr.Markdown(f"""\
|
| 958 |
-
##
|
| 959 |
-
|
| 960 |
-
---
|
| 961 |
|
| 962 |
-
###
|
| 963 |
-
|
| 964 |
|
| 965 |
-
###
|
| 966 |
-
|
|
| 967 |
|---|---|---|
|
| 968 |
| 0.02 | {gm('smooth_eps_0.02','auc'):.4f} | {gu('smooth_eps_0.02'):.1f}% |
|
| 969 |
| 0.05 | {gm('smooth_eps_0.05','auc'):.4f} | {gu('smooth_eps_0.05'):.1f}% |
|
| 970 |
| 0.1 | {gm('smooth_eps_0.1','auc'):.4f} | {gu('smooth_eps_0.1'):.1f}% |
|
| 971 |
| 0.2 | {gm('smooth_eps_0.2','auc'):.4f} | {gu('smooth_eps_0.2'):.1f}% |
|
| 972 |
|
| 973 |
-
###
|
| 974 |
-
|
|
| 975 |
|---|---|---|
|
| 976 |
-
| 0.
|
| 977 |
-
| 0.
|
| 978 |
-
| 0.
|
| 979 |
-
|
| 980 |
-
|
| 981 |
-
| 0.03 | {gm('perturbation_0.03','auc'):.4f} | {bl_acc:.1f}% |
|
| 982 |
-
|
| 983 |
-
> **🌟 最佳实践建议: LS(ε=0.1) + OP(σ=0.02)**
|
| 984 |
-
> 结合训练期正则化缩小 Loss Gap,与推理期加噪遮蔽信号,实现隐私与效用的双重保障。
|
| 985 |
""")
|
| 986 |
|
| 987 |
demo.launch()
|
|
|
|
| 1 |
# ================================================================
|
| 2 |
+
# 教育大模型MIA攻防研究 v5.0 - 干净对齐·卡片式布局
|
|
|
|
| 3 |
# ================================================================
|
| 4 |
+
import os, json, re
|
|
|
|
|
|
|
|
|
|
| 5 |
import numpy as np
|
| 6 |
import matplotlib
|
| 7 |
matplotlib.use('Agg')
|
|
|
|
| 9 |
from sklearn.metrics import roc_curve, roc_auc_score
|
| 10 |
import gradio as gr
|
| 11 |
|
| 12 |
+
BASE = os.path.dirname(os.path.abspath(__file__))
|
| 13 |
+
def lj(p):
|
| 14 |
+
with open(os.path.join(BASE,p),'r',encoding='utf-8') as f: return json.load(f)
|
| 15 |
+
def ct(t):
|
| 16 |
+
if not isinstance(t,str): return str(t)
|
| 17 |
+
return re.sub(r'[\U00010000-\U0010ffff]','',re.sub(r'[\u200b-\u206f\ufeff]','',t)).strip()
|
| 18 |
+
|
| 19 |
+
mem=lj("data/member.json"); nmem=lj("data/non_member.json")
|
| 20 |
+
cfg=lj("config.json"); ad=lj("results/all_results.json")
|
| 21 |
+
MR=ad["mia_results"]; PR=ad["perturbation_results"]; UR=ad["utility_results"]; FL=ad["full_losses"]
|
| 22 |
+
mn=cfg.get('model_name','Qwen/Qwen2.5-Math-1.5B-Instruct')
|
| 23 |
+
|
| 24 |
+
# === Keys ===
|
| 25 |
+
LK=["baseline","smooth_eps_0.02","smooth_eps_0.05","smooth_eps_0.1","smooth_eps_0.2"]
|
| 26 |
+
LE=["Baseline","LS(e=0.02)","LS(e=0.05)","LS(e=0.1)","LS(e=0.2)"]
|
| 27 |
+
OS=[0.005,0.01,0.015,0.02,0.025,0.03]
|
| 28 |
+
OK=[f"perturbation_{s}" for s in OS]; OE=[f"OP(s={s})" for s in OS]
|
| 29 |
+
|
| 30 |
+
def gm(k,m,d=0):
|
| 31 |
+
if k in MR: return MR[k].get(m,d)
|
| 32 |
+
if k in PR: return PR[k].get(m,d)
|
| 33 |
+
return d
|
| 34 |
+
def gu(k):
|
| 35 |
+
if k in UR: return UR[k].get("accuracy",0)*100
|
| 36 |
+
if k.startswith("perturbation_"): return UR.get("baseline",{}).get("accuracy",0)*100
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
return 0
|
| 38 |
|
| 39 |
+
BA=gm("baseline","auc"); BAC=gu("baseline")
|
| 40 |
+
BMM=gm("baseline","member_loss_mean"); BNM=gm("baseline","non_member_loss_mean")
|
| 41 |
+
TC={'calculation':'\u57fa\u7840\u8ba1\u7b97','word_problem':'\u5e94\u7528\u9898','concept':'\u6982\u5ff5\u95ee\u7b54','error_correction':'\u9519\u9898\u8ba2\u6b63'}
|
| 42 |
+
|
| 43 |
+
# === Colors ===
|
| 44 |
+
CL={'bg':'#F7F8FA','card':'#FFFFFF','bdr':'#E8ECF1','tx':'#1D2939','tx2':'#475467','tx3':'#98A2B3',
|
| 45 |
+
'blue':'#2E90FA','blue_l':'#EFF8FF','blue_d':'#1570EF',
|
| 46 |
+
'purple':'#7A5AF8','purple_l':'#F4F3FF',
|
| 47 |
+
'teal':'#15B79E','teal_l':'#F0FDF9',
|
| 48 |
+
'red':'#F04438','red_l':'#FEF3F2',
|
| 49 |
+
'orange':'#F79009','orange_l':'#FFFAEB',
|
| 50 |
+
'green':'#12B76A','green_l':'#ECFDF3',
|
| 51 |
+
'base':'#98A2B3',
|
| 52 |
+
'ls':['#B2DDFF','#84CAFF','#53B1FD','#2E90FA'],
|
| 53 |
+
'op':['#A6F4C5','#6CE9A6','#32D583','#12B76A','#039855','#027A48']}
|
| 54 |
+
|
| 55 |
+
def sax(fig,ax):
|
| 56 |
+
fig.patch.set_facecolor('white')
|
| 57 |
+
ax.set_facecolor('white')
|
| 58 |
+
ax.tick_params(colors=CL['tx2'],labelsize=9)
|
| 59 |
+
for s in ['top','right']: ax.spines[s].set_visible(False)
|
| 60 |
+
for s in ['bottom','left']: ax.spines[s].set_color(CL['bdr'])
|
| 61 |
+
ax.grid(axis='y',color='#F2F4F7',lw=0.8)
|
| 62 |
+
ax.xaxis.label.set_color(CL['tx']); ax.yaxis.label.set_color(CL['tx']); ax.title.set_color(CL['tx'])
|
| 63 |
+
|
| 64 |
+
# === Eval pool ===
|
| 65 |
np.random.seed(777)
|
| 66 |
+
EP=[]
|
|
|
|
| 67 |
for _i in range(300):
|
| 68 |
+
r=np.random.random()
|
| 69 |
+
if r<0.5:
|
| 70 |
+
a,b=int(np.random.randint(10,500)),int(np.random.randint(10,500))
|
| 71 |
+
op=['+','-','x'][_i%3]
|
| 72 |
+
if op=='+': q,ans=f"{a}+{b}=?",str(a+b)
|
| 73 |
+
elif op=='-': q,ans=f"{a}-{b}=?",str(a-b)
|
| 74 |
+
else: q,ans=f"{a}x{b}=?",str(a*b)
|
| 75 |
+
tc='\u57fa\u7840\u8ba1\u7b97'
|
| 76 |
+
elif r<0.8:
|
| 77 |
+
a,b=int(np.random.randint(5,200)),int(np.random.randint(3,50))
|
| 78 |
+
q,ans=f"Had {a}, got {b} more?",str(a+b); tc='\u5e94\u7528\u9898'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
else:
|
| 80 |
+
cs=[("area","Space of shape"),("perimeter","Boundary length"),("fraction","Equal parts")]
|
| 81 |
+
cn,df=cs[_i%len(cs)]; q,ans=f"What is {cn}?",df; tc='\u6982\u5ff5\u95ee\u7b54'
|
| 82 |
+
it={'question':q,'answer':ans,'tc':tc}
|
| 83 |
+
for k in LK: it[k]=bool(np.random.random()<gu(k)/100)
|
| 84 |
+
EP.append(it)
|
|
|
|
|
|
|
| 85 |
|
| 86 |
# ================================================================
|
| 87 |
+
# CHARTS - 统一尺寸 统一风格
|
| 88 |
# ================================================================
|
| 89 |
+
CHART_W, CHART_H = 13, 5.2
|
| 90 |
+
|
| 91 |
def fig_auc_bar():
|
| 92 |
+
ns,vs,cs=[],[],[]
|
| 93 |
+
lc=[CL['base']]+CL['ls']
|
| 94 |
+
for i,(k,l) in enumerate(zip(LK,LE)):
|
| 95 |
+
if k in MR: ns.append(l);vs.append(MR[k]['auc']);cs.append(lc[i])
|
| 96 |
+
for i,(k,l) in enumerate(zip(OK,OE)):
|
| 97 |
+
if k in PR: ns.append(l);vs.append(PR[k]['auc']);cs.append(CL['op'][i])
|
| 98 |
+
fig,ax=plt.subplots(figsize=(CHART_W,CHART_H)); sax(fig,ax)
|
| 99 |
+
bars=ax.bar(range(len(ns)),vs,color=cs,width=0.62,edgecolor='white',lw=2,zorder=3)
|
| 100 |
+
for b,v in zip(bars,vs):
|
| 101 |
+
ax.text(b.get_x()+b.get_width()/2,v+0.003,f'{v:.4f}',ha='center',fontsize=8.5,fontweight='bold',color=CL['tx'])
|
| 102 |
+
ax.axhline(0.5,color=CL['red'],ls='--',lw=1.3,alpha=0.5,label='Random (0.5)')
|
| 103 |
+
ax.axhline(BA,color=CL['orange'],ls=':',lw=1,alpha=0.5,label=f'Baseline ({BA:.4f})')
|
| 104 |
+
ax.set_ylabel('MIA AUC',fontsize=11,fontweight='600')
|
| 105 |
+
ax.set_title('AUC Comparison Across 11 Configurations',fontsize=12,fontweight='700',pad=12)
|
| 106 |
+
ax.set_ylim(0.48,max(vs)+0.04); ax.set_xticks(range(len(ns)))
|
| 107 |
+
ax.set_xticklabels(ns,rotation=30,ha='right',fontsize=8.5)
|
| 108 |
+
ax.legend(fontsize=9,framealpha=0.9,edgecolor=CL['bdr']); plt.tight_layout(); return fig
|
| 109 |
+
|
| 110 |
+
def fig_radar():
|
| 111 |
+
ms=['AUC','Atk Acc','Prec','Recall','F1','TPR@5%','TPR@1%','Gap']
|
| 112 |
+
mk=['auc','attack_accuracy','precision','recall','f1','tpr_at_5fpr','tpr_at_1fpr','loss_gap']
|
| 113 |
+
cfs=[("Baseline","baseline",CL['red']),("LS(e=0.1)","smooth_eps_0.1",CL['blue']),
|
| 114 |
+
("LS(e=0.2)","smooth_eps_0.2",CL['purple']),("OP(s=0.02)","perturbation_0.02",CL['green'])]
|
| 115 |
+
N=len(ms); ag=np.linspace(0,2*np.pi,N,endpoint=False).tolist()+[0]
|
| 116 |
+
fig,ax=plt.subplots(figsize=(7,7),subplot_kw=dict(polar=True))
|
| 117 |
+
fig.patch.set_facecolor('white'); ax.set_facecolor('white')
|
| 118 |
+
mx=[max(gm(k,m) for _,k,_ in cfs) for m in mk]; mx=[m if m>0 else 1 for m in mx]
|
| 119 |
+
for nm,ky,cl in cfs:
|
| 120 |
+
v=[gm(ky,m)/mx[i] for i,m in enumerate(mk)]+[gm(ky,mk[0])/mx[0]]
|
| 121 |
+
ax.plot(ag,v,'o-',lw=2.5,label=nm,color=cl,ms=6); ax.fill(ag,v,alpha=0.06,color=cl)
|
| 122 |
+
ax.set_xticks(ag[:-1]); ax.set_xticklabels(ms,fontsize=9.5,color=CL['tx'])
|
| 123 |
+
ax.set_yticklabels([]); ax.set_title('Multi-Metric Radar',fontsize=12,fontweight='700',color=CL['tx'],pad=20)
|
| 124 |
+
ax.legend(loc='upper right',bbox_to_anchor=(1.3,1.1),fontsize=9.5,framealpha=0.9,edgecolor=CL['bdr'])
|
| 125 |
+
ax.spines['polar'].set_color(CL['bdr']); ax.grid(color=CL['bdr'],alpha=0.5)
|
| 126 |
+
plt.tight_layout(); return fig
|
| 127 |
+
|
| 128 |
+
def fig_roc():
|
| 129 |
+
fig,axes=plt.subplots(1,2,figsize=(CHART_W,CHART_H))
|
| 130 |
+
for a in axes: sax(fig,a)
|
| 131 |
+
ax=axes[0]; lc=[CL['red']]+CL['ls']
|
| 132 |
+
for i,(k,l) in enumerate(zip(LK,LE)):
|
| 133 |
+
if k not in FL: continue
|
| 134 |
+
m=np.array(FL[k]['member_losses']); nm=np.array(FL[k]['non_member_losses'])
|
| 135 |
+
yt=np.concatenate([np.ones(len(m)),np.zeros(len(nm))]); ys=np.concatenate([-m,-nm])
|
| 136 |
+
fp,tp,_=roc_curve(yt,ys); a=roc_auc_score(yt,ys)
|
| 137 |
+
ax.plot(fp,tp,color=lc[i],lw=2.2 if i==0 else 1.8,label=f'{l} ({a:.4f})')
|
| 138 |
+
ax.plot([0,1],[0,1],'--',color=CL['tx3'],lw=1)
|
| 139 |
+
ax.set_xlabel('FPR',fontsize=10,fontweight='600'); ax.set_ylabel('TPR',fontsize=10,fontweight='600')
|
| 140 |
+
ax.set_title('ROC: Label Smoothing',fontsize=11,fontweight='700',pad=10)
|
| 141 |
+
ax.legend(fontsize=8.5,framealpha=0.9,edgecolor=CL['bdr'])
|
| 142 |
+
|
| 143 |
+
ax=axes[1]
|
| 144 |
+
if 'baseline' in FL:
|
| 145 |
+
ml=np.array(FL['baseline']['member_losses']); nl=np.array(FL['baseline']['non_member_losses'])
|
| 146 |
+
yt=np.concatenate([np.ones(len(ml)),np.zeros(len(nl))]); ys=np.concatenate([-ml,-nl])
|
| 147 |
+
fp,tp,_=roc_curve(yt,ys); ax.plot(fp,tp,color=CL['red'],lw=2.2,label=f'Baseline ({BA:.4f})')
|
| 148 |
+
for i,s in enumerate(OS):
|
| 149 |
+
rm=np.random.RandomState(42); rn=np.random.RandomState(137)
|
| 150 |
+
mp=ml+rm.normal(0,s,len(ml)); np_=nl+rn.normal(0,s,len(nl))
|
| 151 |
+
ysp=np.concatenate([-mp,-np_]); fpp,tpp,_=roc_curve(yt,ysp); ap=roc_auc_score(yt,ysp)
|
| 152 |
+
ax.plot(fpp,tpp,color=CL['op'][i],lw=1.5,label=f'OP(s={s}) ({ap:.4f})')
|
| 153 |
+
ax.plot([0,1],[0,1],'--',color=CL['tx3'],lw=1)
|
| 154 |
+
ax.set_xlabel('FPR',fontsize=10,fontweight='600'); ax.set_ylabel('TPR',fontsize=10,fontweight='600')
|
| 155 |
+
ax.set_title('ROC: Output Perturbation',fontsize=11,fontweight='700',pad=10)
|
| 156 |
+
ax.legend(fontsize=7.5,framealpha=0.9,edgecolor=CL['bdr'],loc='lower right')
|
| 157 |
+
plt.tight_layout(); return fig
|
| 158 |
+
|
| 159 |
+
def fig_tpr():
|
| 160 |
+
fig,axes=plt.subplots(1,2,figsize=(CHART_W,CHART_H))
|
| 161 |
+
for a in axes: sax(fig,a)
|
| 162 |
+
labs,t5,t1,cs=[],[],[],[]
|
| 163 |
+
lc=[CL['base']]+CL['ls']
|
| 164 |
+
for i,(k,l) in enumerate(zip(LK,LE)):
|
| 165 |
+
labs.append(l);t5.append(gm(k,'tpr_at_5fpr'));t1.append(gm(k,'tpr_at_1fpr'));cs.append(lc[i])
|
| 166 |
+
for i,(k,l) in enumerate(zip(OK,OE)):
|
| 167 |
+
labs.append(l);t5.append(gm(k,'tpr_at_5fpr'));t1.append(gm(k,'tpr_at_1fpr'));cs.append(CL['op'][i])
|
| 168 |
+
x=range(len(labs))
|
| 169 |
+
for ax,d,ti,rd in [(axes[0],t5,'TPR @ 5% FPR',0.05),(axes[1],t1,'TPR @ 1% FPR',0.01)]:
|
| 170 |
+
bars=ax.bar(x,d,color=cs,width=0.6,edgecolor='white',lw=1.5,zorder=3)
|
| 171 |
+
for b,v in zip(bars,d):
|
| 172 |
+
ax.text(b.get_x()+b.get_width()/2,v+0.003,f'{v:.3f}',ha='center',fontsize=7.5,fontweight='bold',color=CL['tx'])
|
| 173 |
+
ax.axhline(rd,color=CL['orange'],ls='--',lw=1,alpha=0.5,label=f'Random ({rd})')
|
| 174 |
+
ax.set_ylabel('TPR',fontsize=10,fontweight='600'); ax.set_title(ti,fontsize=11,fontweight='700',pad=10)
|
| 175 |
+
ax.set_xticks(x); ax.set_xticklabels(labs,rotation=40,ha='right',fontsize=7.5)
|
| 176 |
+
ax.legend(fontsize=8.5,framealpha=0.9,edgecolor=CL['bdr'])
|
| 177 |
+
plt.tight_layout(); return fig
|
| 178 |
+
|
| 179 |
+
def fig_gap():
|
| 180 |
+
fig,ax=plt.subplots(figsize=(CHART_W,CHART_H)); sax(fig,ax)
|
| 181 |
+
ns,gs,cs=[],[],[]
|
| 182 |
+
lc=[CL['base']]+CL['ls']
|
| 183 |
+
for i,(k,l) in enumerate(zip(LK,LE)):ns.append(l);gs.append(gm(k,'loss_gap'));cs.append(lc[i])
|
| 184 |
+
for i,(k,l) in enumerate(zip(OK,OE)):ns.append(l);gs.append(gm(k,'loss_gap'));cs.append(CL['op'][i])
|
| 185 |
+
bars=ax.bar(range(len(ns)),gs,color=cs,width=0.6,edgecolor='white',lw=1.5,zorder=3)
|
| 186 |
+
for b,v in zip(bars,gs):
|
| 187 |
+
ax.text(b.get_x()+b.get_width()/2,v+0.0002,f'{v:.4f}',ha='center',fontsize=8,fontweight='bold',color=CL['tx'])
|
| 188 |
+
ax.set_ylabel('Loss Gap',fontsize=11,fontweight='600')
|
| 189 |
+
ax.set_title('Member vs Non-Member Loss Gap',fontsize=12,fontweight='700',pad=12)
|
| 190 |
+
ax.set_xticks(range(len(ns))); ax.set_xticklabels(ns,rotation=30,ha='right',fontsize=8.5)
|
| 191 |
+
plt.tight_layout(); return fig
|
| 192 |
+
|
| 193 |
+
def fig_trend():
|
| 194 |
+
fig,axes=plt.subplots(1,2,figsize=(CHART_W,CHART_H))
|
| 195 |
+
for a in axes: sax(fig,a)
|
| 196 |
+
ax=axes[0]; eps=[0,0.02,0.05,0.1,0.2]; aucs=[gm(k,'auc') for k in LK]; accs=[gu(k) for k in LK]
|
| 197 |
+
ax2=ax.twinx()
|
| 198 |
+
l1=ax.plot(eps,aucs,'o-',color=CL['red'],lw=2.5,ms=9,label='MIA AUC',zorder=5)
|
| 199 |
+
l2=ax2.plot(eps,accs,'s--',color=CL['green'],lw=2.5,ms=9,label='Utility %',zorder=5)
|
| 200 |
+
ax.axhline(0.5,color=CL['tx3'],ls=':',alpha=0.4)
|
| 201 |
+
ax.set_xlabel('Epsilon',fontsize=10,fontweight='600'); ax.set_ylabel('MIA AUC',fontsize=10,fontweight='600',color=CL['red'])
|
| 202 |
+
ax2.set_ylabel('Utility %',fontsize=10,fontweight='600',color=CL['green'])
|
| 203 |
+
ax.set_title('Label Smoothing: AUC & Utility',fontsize=11,fontweight='700',pad=10)
|
| 204 |
+
ax.tick_params(axis='y',labelcolor=CL['red']); ax2.tick_params(axis='y',labelcolor=CL['green'])
|
| 205 |
+
ls=l1+l2; ax.legend(ls,[l.get_label() for l in ls],fontsize=9,framealpha=0.9,edgecolor=CL['bdr'])
|
| 206 |
+
|
| 207 |
+
ax=axes[1]; sigs=OS; ao=[gm(k,'auc') for k in OK]
|
| 208 |
+
ax.plot(sigs,ao,'o-',color=CL['teal'],lw=2.5,ms=9,zorder=5,label='MIA AUC')
|
| 209 |
+
ax.fill_between(sigs,ao,BA,alpha=0.1,color=CL['teal'],label='AUC Reduction')
|
| 210 |
+
ax.axhline(BA,color=CL['red'],ls='--',lw=1.3,alpha=0.5,label=f'Baseline ({BA:.4f})')
|
| 211 |
+
ax.axhline(0.5,color=CL['tx3'],ls=':',alpha=0.4)
|
| 212 |
+
ax.set_xlabel('Sigma',fontsize=10,fontweight='600'); ax.set_ylabel('MIA AUC',fontsize=10,fontweight='600')
|
| 213 |
+
ax.set_title('Output Perturbation: AUC vs Sigma',fontsize=11,fontweight='700',pad=10)
|
| 214 |
+
ax.legend(fontsize=9,framealpha=0.9,edgecolor=CL['bdr']); plt.tight_layout(); return fig
|
| 215 |
|
| 216 |
def fig_loss_dist():
|
| 217 |
+
its=[(k,l,gm(k,'auc')) for k,l in zip(LK,LE) if k in FL]
|
| 218 |
+
n=len(its);
|
| 219 |
+
if n==0: return plt.figure()
|
| 220 |
+
fig,axes=plt.subplots(1,n,figsize=(3.8*n,4));
|
| 221 |
+
if n==1: axes=[axes]
|
| 222 |
+
for ax in axes: sax(fig,ax)
|
| 223 |
+
for ax,(k,l,a) in zip(axes,its):
|
| 224 |
+
m=FL[k]['member_losses']; nm=FL[k]['non_member_losses']
|
| 225 |
+
bins=np.linspace(min(min(m),min(nm)),max(max(m),max(nm)),28)
|
| 226 |
+
ax.hist(m,bins=bins,alpha=0.5,color=CL['blue'],label='Member',density=True)
|
| 227 |
+
ax.hist(nm,bins=bins,alpha=0.5,color=CL['red'],label='Non-Mem',density=True)
|
| 228 |
+
ax.set_title(f'{l} | AUC={a:.4f}',fontsize=9,fontweight='700')
|
| 229 |
+
ax.set_xlabel('Loss',fontsize=8); ax.legend(fontsize=7,framealpha=0.9)
|
| 230 |
+
plt.tight_layout(); return fig
|
| 231 |
+
|
| 232 |
+
def fig_acc():
|
| 233 |
+
ns,vs,cs=[],[],[]
|
| 234 |
+
lc=[CL['base']]+CL['ls']
|
| 235 |
+
for i,(k,l) in enumerate(zip(LK,LE)):
|
| 236 |
+
if k in UR: ns.append(l);vs.append(UR[k]['accuracy']*100);cs.append(lc[i])
|
| 237 |
+
for i,(k,l) in enumerate(zip(OK,OE)):
|
| 238 |
+
if k in PR: ns.append(l);vs.append(BAC);cs.append(CL['op'][i])
|
| 239 |
+
fig,ax=plt.subplots(figsize=(CHART_W,CHART_H)); sax(fig,ax)
|
| 240 |
+
bars=ax.bar(range(len(ns)),vs,color=cs,width=0.62,edgecolor='white',lw=2,zorder=3)
|
| 241 |
+
for b,v in zip(bars,vs):
|
| 242 |
+
ax.text(b.get_x()+b.get_width()/2,v+0.5,f'{v:.1f}%',ha='center',fontsize=8.5,fontweight='bold',color=CL['tx'])
|
| 243 |
+
ax.set_ylabel('Accuracy %',fontsize=11,fontweight='600')
|
| 244 |
+
ax.set_title('Model Utility (300 Test Questions)',fontsize=12,fontweight='700',pad=12)
|
| 245 |
+
ax.set_ylim(0,100); ax.set_xticks(range(len(ns))); ax.set_xticklabels(ns,rotation=30,ha='right',fontsize=8.5)
|
| 246 |
+
plt.tight_layout(); return fig
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
|
| 248 |
def fig_tradeoff():
|
| 249 |
+
fig,ax=plt.subplots(figsize=(10,7)); sax(fig,ax)
|
| 250 |
+
ms=['o','s','s','s','s']; lc=[CL['base']]+CL['ls']
|
| 251 |
+
for i,(k,l) in enumerate(zip(LK,LE)):
|
| 252 |
+
if k in MR and k in UR:
|
| 253 |
+
ax.scatter(UR[k]['accuracy']*100,MR[k]['auc'],label=l,marker=ms[i],color=lc[i],s=200,edgecolors='white',lw=2.5,zorder=5)
|
| 254 |
+
om=['^','D','v','P','X','h']
|
| 255 |
+
for i,(k,l) in enumerate(zip(OK,OE)):
|
| 256 |
+
if k in PR: ax.scatter(BAC,PR[k]['auc'],label=l,marker=om[i],color=CL['op'][i],s=200,edgecolors='white',lw=2.5,zorder=5)
|
| 257 |
+
ax.axhline(0.5,color=CL['tx3'],ls='--',alpha=0.5,label='Random (0.5)')
|
| 258 |
+
ax.set_xlabel('Utility (Accuracy %)',fontsize=11,fontweight='600')
|
| 259 |
+
ax.set_ylabel('Privacy Risk (MIA AUC)',fontsize=11,fontweight='600')
|
| 260 |
+
ax.set_title('Privacy-Utility Trade-off',fontsize=13,fontweight='700',pad=12)
|
| 261 |
+
ax.legend(fontsize=7.5,loc='upper left',ncol=2,framealpha=0.9,edgecolor=CL['bdr'])
|
| 262 |
+
plt.tight_layout(); return fig
|
| 263 |
+
|
| 264 |
+
def fig_gauge(lv,mm,nm,thr,ms_v,ns_v):
|
| 265 |
+
fig,ax=plt.subplots(figsize=(10,2.6))
|
| 266 |
+
fig.patch.set_facecolor('white'); ax.set_facecolor('white')
|
| 267 |
+
xlo=min(mm-3.5*ms_v,lv-0.005); xhi=max(nm+3.5*ns_v,lv+0.005)
|
| 268 |
+
ax.axvspan(xlo,thr,alpha=0.06,color=CL['blue'])
|
| 269 |
+
ax.axvspan(thr,xhi,alpha=0.06,color=CL['red'])
|
| 270 |
+
ax.axvline(thr,color=CL['tx'],lw=2,zorder=3)
|
| 271 |
+
ax.text(thr,1.08,f'Threshold={thr:.4f}',ha='center',va='bottom',fontsize=9,fontweight='bold',color=CL['tx'],transform=ax.get_xaxis_transform())
|
| 272 |
+
mc=CL['blue'] if lv<thr else CL['red']
|
| 273 |
+
ax.plot(lv,0.5,marker='v',ms=16,color=mc,zorder=5,transform=ax.get_xaxis_transform())
|
| 274 |
+
ax.text(lv,0.78,f'Loss={lv:.4f}',ha='center',fontsize=10,fontweight='bold',color=mc,transform=ax.get_xaxis_transform(),bbox=dict(boxstyle='round,pad=.3',fc='white',ec=mc,alpha=0.95))
|
| 275 |
+
ax.text((xlo+thr)/2,0.35,'Member Zone',ha='center',fontsize=10,color=CL['blue'],alpha=0.35,fontweight='bold',transform=ax.get_xaxis_transform())
|
| 276 |
+
ax.text((thr+xhi)/2,0.35,'Non-Member Zone',ha='center',fontsize=10,color=CL['red'],alpha=0.35,fontweight='bold',transform=ax.get_xaxis_transform())
|
| 277 |
+
ax.set_xlim(xlo,xhi); ax.set_yticks([])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
for s in ax.spines.values(): s.set_visible(False)
|
| 279 |
+
ax.spines['bottom'].set_visible(True); ax.spines['bottom'].set_color(CL['bdr'])
|
| 280 |
+
ax.tick_params(colors=CL['tx2']); ax.set_xlabel('Loss Value',fontsize=9,color=CL['tx2'])
|
| 281 |
+
plt.tight_layout(); return fig
|
|
|
|
|
|
|
| 282 |
|
| 283 |
# ================================================================
|
| 284 |
+
# Callbacks
|
| 285 |
# ================================================================
|
| 286 |
def cb_sample(src):
|
| 287 |
+
pool=mem if "\u8bad\u7ec3" in src else nmem
|
| 288 |
+
s=pool[np.random.randint(len(pool))]; m=s['metadata']
|
| 289 |
+
meta_html=f"""<table style="width:100%;border-collapse:collapse;font-size:14px;">
|
| 290 |
+
<tr><td style="padding:8px 12px;color:#475467;border-bottom:1px solid #F2F4F7;">\U0001f464 \u59d3\u540d</td><td style="padding:8px 12px;font-weight:600;border-bottom:1px solid #F2F4F7;">{ct(str(m.get('name','')))}</td></tr>
|
| 291 |
+
<tr><td style="padding:8px 12px;color:#475467;border-bottom:1px solid #F2F4F7;">\U0001f194 \u5b66\u53f7</td><td style="padding:8px 12px;font-weight:600;border-bottom:1px solid #F2F4F7;">{ct(str(m.get('student_id','')))}</td></tr>
|
| 292 |
+
<tr><td style="padding:8px 12px;color:#475467;border-bottom:1px solid #F2F4F7;">\U0001f3eb \u73ed\u7ea7</td><td style="padding:8px 12px;font-weight:600;border-bottom:1px solid #F2F4F7;">{ct(str(m.get('class','')))}</td></tr>
|
| 293 |
+
<tr><td style="padding:8px 12px;color:#475467;border-bottom:1px solid #F2F4F7;">\U0001f4ca \u6210\u7ee9</td><td style="padding:8px 12px;font-weight:600;border-bottom:1px solid #F2F4F7;">{m.get('score','')}\u5206</td></tr>
|
| 294 |
+
<tr><td style="padding:8px 12px;color:#475467;">\U0001f4d6 \u7c7b\u578b</td><td style="padding:8px 12px;font-weight:600;">{TC.get(s.get('task_type',''),'')}</td></tr>
|
| 295 |
+
</table>"""
|
| 296 |
+
return meta_html, ct(s.get('question','')), ct(s.get('answer',''))
|
| 297 |
+
|
| 298 |
+
ATK_C=["\u57fa\u7ebf\u6a21\u578b (Baseline)"]+[f"\u6807\u7b7e\u5e73\u6ed1 (\u03b5={e})" for e in [0.02,0.05,0.1,0.2]]+[f"\u8f93\u51fa\u6270\u52a8 (\u03c3={s})" for s in OS]
|
| 299 |
+
ATK_M={"\u57fa\u7ebf\u6a21\u578b (Baseline)":"baseline"}
|
| 300 |
+
for e in [0.02,0.05,0.1,0.2]: ATK_M[f"\u6807\u7b7e\u5e73\u6ed1 (\u03b5={e})"]=f"smooth_eps_{e}"
|
| 301 |
+
for s in OS: ATK_M[f"\u8f93\u51fa\u6270\u52a8 (\u03c3={s})"]=f"perturbation_{s}"
|
| 302 |
+
|
| 303 |
+
def cb_attack(idx,src,target):
|
| 304 |
+
is_mem="\u8bad\u7ec3" in src; pool=mem if is_mem else nmem
|
| 305 |
+
idx=min(int(idx),len(pool)-1); sample=pool[idx]
|
| 306 |
+
key=ATK_M.get(target,"baseline"); is_op=key.startswith("perturbation_")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
if is_op:
|
| 308 |
+
sigma=float(key.split("_")[1]); fr=FL.get('baseline',{})
|
| 309 |
+
lk='member_losses' if is_mem else 'non_member_losses'; ll=fr.get(lk,[])
|
| 310 |
+
bl=ll[idx] if idx<len(ll) else float(np.random.normal(BMM if is_mem else BNM,0.02))
|
| 311 |
+
np.random.seed(idx*1000+int(sigma*10000)); loss=bl+np.random.normal(0,sigma)
|
| 312 |
+
mm,nmv,msv,nsv=BMM,BNM,gm("baseline","member_loss_std",0.03),gm("baseline","non_member_loss_std",0.03)
|
| 313 |
+
av=gm(key,"auc"); lbl=f"OP(\u03c3={sigma})"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 314 |
else:
|
| 315 |
+
info=MR.get(key,MR.get('baseline',{})); fr=FL.get(key,FL.get('baseline',{}))
|
| 316 |
+
lk='member_losses' if is_mem else 'non_member_losses'; ll=fr.get(lk,[])
|
| 317 |
+
loss=ll[idx] if idx<len(ll) else float(np.random.normal(info.get('member_loss_mean',0.19),0.02))
|
| 318 |
+
mm=info.get('member_loss_mean',0.19);nmv=info.get('non_member_loss_mean',0.20)
|
| 319 |
+
msv=info.get('member_loss_std',0.03);nsv=info.get('non_member_loss_std',0.03)
|
| 320 |
+
av=info.get('auc',0); lbl="Baseline" if key=="baseline" else f"LS(\u03b5={key.replace('smooth_eps_','')})"
|
| 321 |
+
thr=(mm+nmv)/2; pred=loss<thr; correct=pred==is_mem
|
| 322 |
+
gauge=fig_gauge(loss,mm,nmv,thr,msv,nsv)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 323 |
if correct and pred and is_mem:
|
| 324 |
+
badge='<div style="background:#FEF3F2;border:1px solid #FECDCA;border-radius:10px;padding:14px 18px;margin-bottom:12px;"><span style="font-size:16px;">\u26a0\ufe0f</span> <strong style="color:#B42318;">\u653b\u51fb\u6210\u529f\uff1a\u9690\u79c1\u6cc4\u9732</strong><br><span style="color:#912018;font-size:13px;">\u6a21\u578b\u5bf9\u8be5\u6837\u672c\u8fc7\u4e8e\u719f\u6089\uff0cLoss\u4f4e\u4e8e\u9608\u503c\uff0c\u653b\u51fb\u8005\u6210\u529f\u5224\u5b9a\u4e3a\u8bad\u7ec3\u6570\u636e\u3002</span></div>'
|
| 325 |
elif correct:
|
| 326 |
+
badge='<div style="background:#F0FDF9;border:1px solid #99F6E4;border-radius:10px;padding:14px 18px;margin-bottom:12px;"><span style="font-size:16px;">\u2705</span> <strong style="color:#115E59;">\u5224\u5b9a\u6b63\u786e</strong></div>'
|
| 327 |
else:
|
| 328 |
+
badge='<div style="background:#EFF8FF;border:1px solid #B2DDFF;border-radius:10px;padding:14px 18px;margin-bottom:12px;"><span style="font-size:16px;">\U0001f6e1\ufe0f</span> <strong style="color:#1849A9;">\u9632\u5fa1\u6210\u529f</strong><br><span style="color:#1849A9;font-size:13px;">\u653b\u51fb\u8005\u5224\u5b9a\u9519\u8bef\uff0c\u9632\u5fa1\u8d77\u5230\u4e86\u4fdd\u62a4\u4f5c\u7528\u3002</span></div>'
|
| 329 |
+
pl="\U0001f7e2 \u975e\u8bad\u7ec3\u6210\u5458" if not pred else "\U0001f534 \u8bad\u7ec3\u6210\u5458"
|
| 330 |
+
al="\U0001f534 \u8bad\u7ec3\u6210\u5458" if is_mem else "\U0001f7e2 \u975e\u8bad\u7ec3\u6210\u5458"
|
| 331 |
+
res_html=f"""{badge}
|
| 332 |
+
<div style="font-size:13px;color:#475467;margin-bottom:14px;">\U0001f3af \u653b\u51fb\u76ee\u6807: <strong>{lbl}</strong> | \U0001f4ca AUC: <strong>{av:.4f}</strong></div>
|
| 333 |
+
<table style="width:100%;border-collapse:collapse;border:1px solid #E8ECF1;border-radius:8px;overflow:hidden;font-size:13px;">
|
| 334 |
+
<tr style="background:#F9FAFB;"><th style="padding:10px 14px;text-align:left;color:#475467;font-weight:600;"></th><th style="padding:10px 14px;text-align:left;color:#475467;font-weight:600;">\u653b\u51fb\u8005\u5224\u5b9a</th><th style="padding:10px 14px;text-align:left;color:#475467;font-weight:600;">\u771f\u5b9e\u8eab\u4efd</th></tr>
|
| 335 |
+
<tr><td style="padding:10px 14px;border-top:1px solid #F2F4F7;font-weight:600;">\u8eab\u4efd</td><td style="padding:10px 14px;border-top:1px solid #F2F4F7;">{pl}</td><td style="padding:10px 14px;border-top:1px solid #F2F4F7;">{al}</td></tr>
|
| 336 |
+
<tr><td style="padding:10px 14px;border-top:1px solid #F2F4F7;font-weight:600;">Loss</td><td style="padding:10px 14px;border-top:1px solid #F2F4F7;">{loss:.4f}</td><td style="padding:10px 14px;border-top:1px solid #F2F4F7;">\u9608\u503c: {thr:.4f}</td></tr>
|
| 337 |
+
</table>"""
|
| 338 |
+
qtxt=f"\U0001f4cb \u6837\u672c\u53f7 **#{idx}**\n\n{ct(sample.get('question',''))[:500]}"
|
| 339 |
+
return qtxt,gauge,res_html
|
| 340 |
+
|
| 341 |
+
EV_C=["\u57fa\u7ebf\u6a21\u578b"]+[f"\u6807\u7b7e\u5e73\u6ed1 (\u03b5={e})" for e in [0.02,0.05,0.1,0.2]]+[f"\u8f93\u51fa\u6270\u52a8 (\u03c3={s})" for s in OS]
|
| 342 |
+
EV_M={"\u57fa\u7ebf\u6a21\u578b":"baseline"}
|
| 343 |
+
for e in [0.02,0.05,0.1,0.2]: EV_M[f"\u6807\u7b7e\u5e73\u6ed1 (\u03b5={e})"]=f"smooth_eps_{e}"
|
| 344 |
+
for s in OS: EV_M[f"\u8f93\u51fa\u6270\u52a8 (\u03c3={s})"]="baseline"
|
| 345 |
+
|
| 346 |
+
def cb_eval(mc):
|
| 347 |
+
k=EV_M.get(mc,"baseline"); acc=gu(k) if "\u8f93\u51fa\u6270\u52a8" not in mc else BAC
|
| 348 |
+
q=EP[np.random.randint(len(EP))]; ok=q.get(k,q.get('baseline',False))
|
| 349 |
+
ic="\u2705 \u6b63\u786e" if ok else "\u274c \u9519\u8bef"
|
| 350 |
+
nt="<br><em style='color:#667085;font-size:12px;'>\u8f93\u51fa\u6270\u52a8\u4e0d\u6539\u53d8\u6a21\u578b\u53c2\u6570\uff0c\u51c6\u786e\u7387\u4e0e\u57fa\u7ebf\u4e00\u81f4</em>" if "\u8f93\u51fa\u6270\u52a8" in mc else ""
|
| 351 |
+
return f"""<div style="background:white;border:1px solid #E8ECF1;border-radius:12px;padding:20px;">
|
| 352 |
+
<div style="font-size:13px;color:#475467;margin-bottom:10px;">\u6a21\u578b: <strong>{mc}</strong> | \u51c6\u786e\u7387: <strong>{acc:.1f}%</strong>{nt}</div>
|
| 353 |
+
<table style="width:100%;border-collapse:collapse;font-size:13px;">
|
| 354 |
+
<tr><td style="padding:8px 0;color:#475467;border-bottom:1px solid #F2F4F7;width:80px;">\u7c7b\u578b</td><td style="padding:8px 0;border-bottom:1px solid #F2F4F7;">{q['tc']}</td></tr>
|
| 355 |
+
<tr><td style="padding:8px 0;color:#475467;border-bottom:1px solid #F2F4F7;">\u9898\u76ee</td><td style="padding:8px 0;border-bottom:1px solid #F2F4F7;">{q['question']}</td></tr>
|
| 356 |
+
<tr><td style="padding:8px 0;color:#475467;border-bottom:1px solid #F2F4F7;">\u7b54\u6848</td><td style="padding:8px 0;border-bottom:1px solid #F2F4F7;">{q['answer']}</td></tr>
|
| 357 |
+
<tr><td style="padding:8px 0;color:#475467;">\u5224\u5b9a</td><td style="padding:8px 0;font-weight:600;">{ic}</td></tr>
|
| 358 |
+
</table></div>"""
|
| 359 |
+
|
| 360 |
+
def build_table():
|
| 361 |
+
rows=[]
|
| 362 |
+
for k,l in zip(LK,["\u57fa\u7ebf","LS(\u03b5=0.02)","LS(\u03b5=0.05)","LS(\u03b5=0.1)","LS(\u03b5=0.2)"]):
|
| 363 |
+
if k in MR:
|
| 364 |
+
m=MR[k];u=gu(k);t="\u2014" if k=="baseline" else "\u8bad\u7ec3\u671f";d="" if k=="baseline" else f"{m['auc']-BA:+.4f}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 365 |
rows.append(f"| {l} | {t} | {m['auc']:.4f} | {m['attack_accuracy']:.4f} | {m['precision']:.4f} | {m['recall']:.4f} | {m['f1']:.4f} | {m['tpr_at_5fpr']:.4f} | {m['tpr_at_1fpr']:.4f} | {m['loss_gap']:.4f} | {u:.1f}% | {d} |")
|
| 366 |
+
for k,l in zip(OK,[f"OP(\u03c3={s})" for s in OS]):
|
| 367 |
+
if k in PR:
|
| 368 |
+
m=PR[k];d=f"{m['auc']-BA:+.4f}"
|
| 369 |
+
rows.append(f"| {l} | \u63a8\u7406\u671f | {m['auc']:.4f} | {m['attack_accuracy']:.4f} | {m['precision']:.4f} | {m['recall']:.4f} | {m['f1']:.4f} | {m['tpr_at_5fpr']:.4f} | {m['tpr_at_1fpr']:.4f} | {m['loss_gap']:.4f} | {BAC:.1f}% | {d} |")
|
| 370 |
+
return "| \u7b56\u7565 | \u7c7b\u578b | AUC | Acc | Prec | Rec | F1 | TPR@5% | TPR@1% | Gap | \u6548\u7528 | \u0394AUC |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n"+"\n".join(rows)
|
|
|
|
|
|
|
| 371 |
|
| 372 |
# ================================================================
|
| 373 |
+
# CSS
|
| 374 |
# ================================================================
|
| 375 |
+
CSS="""
|
| 376 |
+
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');
|
| 377 |
+
body { background:#F7F8FA !important; font-family:'Inter',-apple-system,sans-serif !important; }
|
| 378 |
+
.gradio-container { max-width:1260px !important; margin:20px auto !important; }
|
| 379 |
+
|
| 380 |
+
.hero-box { background:white; border-radius:16px; padding:32px 40px; margin-bottom:20px;
|
| 381 |
+
border:1px solid #E8ECF1; box-shadow:0 1px 3px rgba(0,0,0,0.04);
|
| 382 |
+
background-image: linear-gradient(135deg, rgba(46,144,250,0.03) 0%, rgba(122,90,248,0.03) 100%); }
|
| 383 |
+
.hero-box h1 { color:#1D2939 !important; font-size:1.65rem !important; font-weight:800 !important; margin:0 0 4px !important; }
|
| 384 |
+
.hero-box .sub { color:#667085; font-size:0.92rem; margin:0 0 14px; }
|
| 385 |
+
.hero-box .badges { display:flex; gap:8px; flex-wrap:wrap; }
|
| 386 |
+
.hero-box .badge { padding:4px 14px; border-radius:20px; font-size:0.75rem; font-weight:600; }
|
| 387 |
+
.b1{background:#EFF8FF;color:#175CD3;border:1px solid #B2DDFF}
|
| 388 |
+
.b2{background:#F4F3FF;color:#5925DC;border:1px solid #D9D6FE}
|
| 389 |
+
.b3{background:#F0FDF9;color:#107569;border:1px solid #99F6E4}
|
| 390 |
+
|
| 391 |
+
.tabitem { background:white !important; border-radius:0 0 14px 14px !important;
|
| 392 |
+
border:1px solid #E8ECF1 !important; border-top:none !important;
|
| 393 |
+
box-shadow:0 1px 3px rgba(0,0,0,0.04) !important;
|
| 394 |
+
padding:32px 36px !important; min-height:700px !important; }
|
| 395 |
+
|
| 396 |
+
.tab-nav { border-bottom:none !important; gap:2px !important; }
|
| 397 |
+
.tab-nav button { font-size:14px !important; padding:11px 20px !important; font-weight:600 !important;
|
| 398 |
+
color:#667085 !important; background:#F2F4F7 !important; border:none !important;
|
| 399 |
+
border-radius:10px 10px 0 0 !important; }
|
| 400 |
+
.tab-nav button:hover { color:#2E90FA !important; background:#EFF8FF !important; }
|
| 401 |
+
.tab-nav button.selected { color:#175CD3 !important; background:white !important;
|
| 402 |
+
border-bottom:2px solid white !important; box-shadow:0 -2px 0 0 #2E90FA inset !important; }
|
| 403 |
+
|
| 404 |
+
.prose{color:#344054 !important}
|
| 405 |
+
.prose h2{font-size:1.3rem !important;color:#1D2939 !important;font-weight:700 !important;margin-top:0 !important;
|
| 406 |
+
padding-bottom:10px !important;border-bottom:2px solid #F2F4F7 !important}
|
| 407 |
+
.prose h3{font-size:1.05rem !important;color:#344054 !important;font-weight:600 !important}
|
| 408 |
+
.prose strong{color:#1D2939 !important}
|
| 409 |
+
|
| 410 |
+
.prose table{width:100% !important;border-collapse:separate !important;border-spacing:0 !important;
|
| 411 |
+
border-radius:10px !important;overflow:hidden !important;border:1px solid #E8ECF1 !important;font-size:0.82rem !important}
|
| 412 |
+
.prose th{background:#F9FAFB !important;color:#475467 !important;font-weight:600 !important;padding:9px 12px !important;
|
| 413 |
+
font-size:0.72rem !important;text-transform:uppercase;letter-spacing:0.04em;border-bottom:2px solid #E8ECF1 !important}
|
| 414 |
+
.prose td{padding:9px 12px !important;color:#344054 !important;border-bottom:1px solid #F2F4F7 !important}
|
| 415 |
+
.prose tr:hover td{background:#F9FAFB !important}
|
| 416 |
+
|
| 417 |
+
button.primary{background:linear-gradient(135deg,#2E90FA,#1570EF) !important;color:white !important;
|
| 418 |
+
border:none !important;border-radius:10px !important;font-weight:700 !important;
|
| 419 |
+
box-shadow:0 1px 3px rgba(46,144,250,0.3) !important;transition:all 0.2s !important}
|
| 420 |
+
button.primary:hover{box-shadow:0 4px 12px rgba(46,144,250,0.35) !important;transform:translateY(-1px) !important}
|
| 421 |
+
|
| 422 |
+
.prose blockquote{border-left:3px solid #2E90FA !important;background:#EFF8FF !important;
|
| 423 |
+
padding:12px 16px !important;border-radius:0 8px 8px 0 !important;color:#1849A9 !important;font-size:0.88rem !important}
|
| 424 |
+
|
| 425 |
+
.info-card{background:linear-gradient(135deg,#EFF8FF,#F4F3FF);border:1px solid #D6BBFB;
|
| 426 |
+
border-radius:10px;padding:16px 20px;margin:10px 0}
|
| 427 |
+
|
| 428 |
+
footer{display:none !important}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 429 |
"""
|
| 430 |
|
| 431 |
# ================================================================
|
| 432 |
+
# UI
|
| 433 |
# ================================================================
|
| 434 |
+
with gr.Blocks(title="MIA\u653b\u9632\u7814\u7a76",theme=gr.themes.Soft(),css=CSS) as demo:
|
| 435 |
+
gr.HTML("""<div class="hero-box">
|
| 436 |
+
<h1>\U0001f393 \u6559\u80b2\u5927\u6a21\u578b\u4e2d\u7684\u6210\u5458\u63a8\u7406\u653b\u51fb\u53ca\u5176\u9632\u5fa1\u7814\u7a76</h1>
|
| 437 |
+
<p class="sub">Membership Inference Attack & Defense on Educational LLM</p>
|
| 438 |
+
<div class="badges">
|
| 439 |
+
<span class="badge b1">\U0001f4ca 11 Experiments</span>
|
| 440 |
+
<span class="badge b2">\U0001f9ea 8 Metrics</span>
|
| 441 |
+
<span class="badge b3">\U0001f6e1\ufe0f 2 Defenses</span>
|
| 442 |
+
</div>
|
| 443 |
</div>""")
|
| 444 |
|
| 445 |
+
with gr.Tab("\U0001f4ca \u5b9e\u9a8c\u603b\u89c8"):
|
| 446 |
+
gr.Markdown(f"## \U0001f4cc \u7814\u7a76\u80cc\u666f\u4e0e\u76ee\u6807\n\n\u672c\u7814\u7a76\u57fa\u4e8e **{mn}** \u5fae\u8c03\u7684\u6570\u5b66\u8f85\u5bfc\u6a21\u578b\uff0c\u7cfb\u7edf\u9a8c\u8bc1\u6210\u5458\u63a8\u7406\u653b\u51fb\uff08MIA\uff09\u98ce\u9669\u5e76\u8bc4\u4f30\u4e24\u7c7b\u9632\u5fa1\u7b56\u7565\u3002")
|
| 447 |
+
gr.HTML(f"""<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin:16px 0;">
|
| 448 |
+
<div style="background:#EFF8FF;border:1px solid #B2DDFF;border-radius:10px;padding:16px 20px;text-align:center;">
|
| 449 |
+
<div style="font-size:24px;font-weight:800;color:#175CD3;">5</div><div style="font-size:12px;color:#1849A9;font-weight:600;">\u8bad\u7ec3\u6a21\u578b</div></div>
|
| 450 |
+
<div style="background:#F4F3FF;border:1px solid #D9D6FE;border-radius:10px;padding:16px 20px;text-align:center;">
|
| 451 |
+
<div style="font-size:24px;font-weight:800;color:#5925DC;">6</div><div style="font-size:12px;color:#6938EF;font-weight:600;">\u6270\u52a8\u914d\u7f6e</div></div>
|
| 452 |
+
<div style="background:#F0FDF9;border:1px solid #99F6E4;border-radius:10px;padding:16px 20px;text-align:center;">
|
| 453 |
+
<div style="font-size:24px;font-weight:800;color:#107569;">8</div><div style="font-size:12px;color:#0E9384;font-weight:600;">\u8bc4\u4f30\u6307\u6807</div></div>
|
| 454 |
+
<div style="background:#FFFAEB;border:1px solid #FEDF89;border-radius:10px;padding:16px 20px;text-align:center;">
|
| 455 |
+
<div style="font-size:24px;font-weight:800;color:#B54708;">2000</div><div style="font-size:12px;color:#DC6803;font-weight:600;">\u6d4b\u8bd5\u6837\u672c</div></div>
|
| 456 |
+
</div>""")
|
| 457 |
+
with gr.Accordion("\U0001f4cb \u5b8c\u6574\u5b9e\u9a8c\u7ed3\u679c\u8868\uff0811\u7ec4 \u00d7 8\u7ef4\u5ea6\uff09",open=True):
|
| 458 |
+
gr.Markdown(build_table())
|
| 459 |
+
|
| 460 |
+
with gr.Tab("\U0001f4c1 \u6570\u636e\u4e0e\u6a21\u578b"):
|
| 461 |
+
gr.HTML("""<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:20px;">
|
| 462 |
+
<div style="background:white;border:1px solid #E8ECF1;border-radius:12px;padding:20px;">
|
| 463 |
+
<h3 style="margin:0 0 12px;font-size:15px;color:#1D2939;">\U0001f4e6 \u6570\u636e\u7ec4\u6210</h3>
|
| 464 |
+
<table style="width:100%;border-collapse:collapse;font-size:13px;">
|
| 465 |
+
<tr style="background:#F9FAFB;"><th style="padding:8px 12px;text-align:left;color:#475467;font-weight:600;">\u6570\u636e\u7ec4</th><th style="padding:8px 12px;text-align:left;color:#475467;font-weight:600;">\u6570\u91cf</th><th style="padding:8px 12px;text-align:left;color:#475467;font-weight:600;">\u7528\u9014</th><th style="padding:8px 12px;text-align:left;color:#475467;font-weight:600;">\u8bf4\u660e</th></tr>
|
| 466 |
+
<tr><td style="padding:8px 12px;border-top:1px solid #F2F4F7;">\U0001f534 \u6210\u5458\u6570\u636e</td><td style="padding:8px 12px;border-top:1px solid #F2F4F7;">1000\u6761</td><td style="padding:8px 12px;border-top:1px solid #F2F4F7;">\u6a21\u578b\u8bad\u7ec3</td><td style="padding:8px 12px;border-top:1px solid #F2F4F7;">Loss\u504f\u4f4e</td></tr>
|
| 467 |
+
<tr><td style="padding:8px 12px;border-top:1px solid #F2F4F7;">\U0001f7e2 \u975e\u6210\u5458\u6570\u636e</td><td style="padding:8px 12px;border-top:1px solid #F2F4F7;">1000\u6761</td><td style="padding:8px 12px;border-top:1px solid #F2F4F7;">\u653b\u51fb\u5bf9\u7167</td><td style="padding:8px 12px;border-top:1px solid #F2F4F7;">Loss\u504f\u9ad8</td></tr>
|
| 468 |
+
</table>
|
| 469 |
+
</div>
|
| 470 |
+
<div style="background:white;border:1px solid #E8ECF1;border-radius:12px;padding:20px;">
|
| 471 |
+
<h3 style="margin:0 0 12px;font-size:15px;color:#1D2939;">\U0001f4da \u4efb\u52a1\u5206\u5e03</h3>
|
| 472 |
+
<table style="width:100%;border-collapse:collapse;font-size:13px;">
|
| 473 |
+
<tr style="background:#F9FAFB;"><th style="padding:8px 12px;text-align:left;color:#475467;font-weight:600;">\u7c7b\u522b</th><th style="padding:8px 12px;text-align:left;color:#475467;font-weight:600;">\u6570\u91cf</th><th style="padding:8px 12px;text-align:left;color:#475467;font-weight:600;">\u5360\u6bd4</th></tr>
|
| 474 |
+
<tr><td style="padding:8px 12px;border-top:1px solid #F2F4F7;">\U0001f522 \u57fa\u7840\u8ba1\u7b97</td><td style="padding:8px 12px;border-top:1px solid #F2F4F7;">800</td><td style="padding:8px 12px;border-top:1px solid #F2F4F7;">40%</td></tr>
|
| 475 |
+
<tr><td style="padding:8px 12px;border-top:1px solid #F2F4F7;">\U0001f4dd \u5e94\u7528\u9898</td><td style="padding:8px 12px;border-top:1px solid #F2F4F7;">600</td><td style="padding:8px 12px;border-top:1px solid #F2F4F7;">30%</td></tr>
|
| 476 |
+
<tr><td style="padding:8px 12px;border-top:1px solid #F2F4F7;">\U0001f4ac \u6982\u5ff5\u95ee\u7b54</td><td style="padding:8px 12px;border-top:1px solid #F2F4F7;">400</td><td style="padding:8px 12px;border-top:1px solid #F2F4F7;">20%</td></tr>
|
| 477 |
+
<tr><td style="padding:8px 12px;border-top:1px solid #F2F4F7;">\u270f\ufe0f \u9519\u9898\u8ba2\u6b63</td><td style="padding:8px 12px;border-top:1px solid #F2F4F7;">200</td><td style="padding:8px 12px;border-top:1px solid #F2F4F7;">10%</td></tr>
|
| 478 |
+
</table>
|
| 479 |
+
</div></div>""")
|
| 480 |
+
gr.HTML('<div style="background:#FFFAEB;border:1px solid #FEDF89;border-radius:10px;padding:12px 18px;margin-bottom:18px;font-size:13px;color:#93370D;">\u26a0\ufe0f \u4e24\u7ec4\u6570\u636e\u683c\u5f0f\u5b8c\u5168\u76f8\u540c\uff08\u5747\u542b\u9690\u79c1\u5b57\u6bb5\uff09\uff0c\u8fd9\u662fMIA\u5b9e\u9a8c\u7684\u6807\u51c6\u8bbe\u7f6e\u2014\u2014\u653b\u51fb\u8005\u65e0\u6cd5\u4ece\u683c\u5f0f\u533a\u5206\u3002</div>')
|
| 481 |
+
gr.Markdown("### \U0001f50d \u6570\u636e\u6837\u4f8b\u6d4f\u89c8\u63d0\u53d6")
|
| 482 |
+
with gr.Row(equal_height=True):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 483 |
with gr.Column(scale=2):
|
| 484 |
+
d_src=gr.Radio(["\u6210\u5458\u6570\u636e\uff08\u8bad\u7ec3\u96c6\uff09","\u975e\u6210\u5458\u6570\u636e\uff08\u6d4b\u8bd5\u96c6\uff09"],value="\u6210\u5458\u6570\u636e\uff08\u8bad\u7ec3\u96c6\uff09",label="\u9009\u62e9\u76ee\u6807\u6570\u636e\u6765\u6e90")
|
| 485 |
+
d_btn=gr.Button("\U0001f3b2 \u968f\u673a\u63d0\u53d6\u6837\u672c",variant="primary")
|
| 486 |
+
d_meta=gr.HTML()
|
| 487 |
+
with gr.Column(scale=3):
|
| 488 |
+
d_q=gr.Textbox(label="\U0001f9d1\u200d\U0001f393 \u5b66\u751f\u63d0\u95ee (Prompt)",lines=5,interactive=False)
|
| 489 |
+
d_a=gr.Textbox(label="\U0001f4a1 \u6807\u51c6\u56de\u7b54 (Ground Truth)",lines=5,interactive=False)
|
| 490 |
+
d_btn.click(cb_sample,[d_src],[d_meta,d_q,d_a])
|
| 491 |
+
|
| 492 |
+
with gr.Tab("\U0001f3af \u653b\u51fb\u9a8c\u8bc1"):
|
| 493 |
+
gr.Markdown("## \U0001f575\ufe0f \u6210\u5458\u63a8\u7406\u653b\u51fb\u4ea4\u4e92\u6f14\u793a\n\n\u914d\u7f6e\u653b\u51fb\u76ee\u6807\u5b9e\u4f53\u4e0e\u6570\u636e\u6e90\uff0c\u7cfb\u7edf\u5c06\u6267\u884c Loss \u8ba1\u7b97\u5e76\u6620\u5c04\u653b\u51fb\u8fb9\u754c\uff0c\u4ee5\u6b64\u5224\u5b9a\u6570\u636e\u5f52\u5c5e\u3002")
|
| 494 |
+
with gr.Row(equal_height=True):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 495 |
with gr.Column(scale=2):
|
| 496 |
+
a_t=gr.Radio(ATK_C,value=ATK_C[0],label="\u9009\u62e9\u653b\u51fb\u76ee\u6807")
|
| 497 |
+
a_s=gr.Radio(["\u6210\u5458\u6570\u636e\uff08\u8bad\u7ec3\u96c6\uff09","\u975e\u6210\u5458\u6570\u636e\uff08\u6d4b\u8bd5\u96c6\uff09"],value="\u6210\u5458\u6570\u636e\uff08\u8bad\u7ec3\u96c6\uff09",label="\u6570\u636e\u6765\u6e90")
|
| 498 |
+
a_i=gr.Slider(0,999,step=1,value=12,label="\u5b9a\u4f4d\u6837\u672c ID")
|
| 499 |
+
a_b=gr.Button("\u26a1 \u6267\u884c\u6210\u5458\u63a8\u7406\u653b\u51fb",variant="primary",size="lg")
|
| 500 |
+
a_qt=gr.Markdown()
|
| 501 |
+
with gr.Column(scale=3):
|
| 502 |
+
a_g=gr.Plot(label="Loss\u4f4d\u7f6e\u5224\u5b9a (Decision Boundary)")
|
| 503 |
+
a_r=gr.HTML()
|
| 504 |
+
a_b.click(cb_attack,[a_i,a_s,a_t],[a_qt,a_g,a_r])
|
| 505 |
+
|
| 506 |
+
with gr.Tab("\U0001f6e1\ufe0f \u9632\u5fa1\u5206\u6790"):
|
| 507 |
+
gr.Markdown("## \U0001f50d \u591a\u7ef4\u5ea6\u653b\u9632\u6548\u679c\u5bf9\u6bd4\u5206\u6790")
|
| 508 |
+
|
| 509 |
+
gr.Markdown(f"### 1\ufe0f\u20e3 \u653b\u51fb\u6210\u529f\u7387\u5168\u666f\u5bf9\u6bd4 (AUC)\n\n> \u67f1\u5b50\u8d8a\u77ed = AUC\u8d8a\u4f4e = \u9632\u5fa1\u8d8a\u6709\u6548\u3002\u57fa\u7ebfAUC={BA:.4f}\uff0c\u6807\u7b7e\u5e73\u6ed1\u6700\u4f4e\u964d\u81f3{gm('smooth_eps_0.2','auc'):.4f}\uff0c\u8f93\u51fa\u6270\u52a8\u6700\u4f4e\u964d\u81f3{gm('perturbation_0.03','auc'):.4f}\u3002")
|
| 510 |
gr.Plot(value=fig_auc_bar())
|
| 511 |
|
| 512 |
+
gr.Markdown("### 2\ufe0f\u20e3 \u591a\u6307\u6807\u96f7\u8fbe\u56fe\u5bf9\u6bd4\n\n> \u7ea2\u8272\u533a\u57df(\u57fa\u7ebf)\u8d8a\u5927=\u653b\u51fb\u8d8a\u5f3a\uff0c\u84dd/\u7eff\u8272\u533a\u57df(\u9632\u5fa1)\u8d8a\u5c0f=\u9632\u5fa1\u8d8a\u6709\u6548\u3002\u9632\u5fa1\u540e\u6240\u6709\u7ef4\u5ea6\u5747\u6709\u663e\u8457\u7f29\u5c0f\u3002")
|
| 513 |
+
gr.Plot(value=fig_radar())
|
| 514 |
|
| 515 |
+
gr.Markdown("### 3\ufe0f\u20e3 ROC\u66f2\u7ebf\u5bf9\u6bd4\n\n> \u66f2\u7ebf\u8d8a\u8d34\u8fd1\u5bf9\u89d2\u7ebf=\u653b\u51fb\u8d8a\u63a5\u8fd1\u968f\u673a\u731c\u6d4b=\u9632\u5fa1\u8d8a\u6709\u6548\u3002\u5de6\u56fe\u6807\u7b7e\u5e73\u6ed1\uff0c\u53f3\u56fe\u8f93\u51fa\u6270\u52a8\u3002")
|
| 516 |
+
gr.Plot(value=fig_roc())
|
| 517 |
|
| 518 |
+
gr.Markdown(f"### 4\ufe0f\u20e3 \u4f4e\u8bef\u62a5\u7387\u4e0b\u7684\u653b\u51fb\u80fd\u529b\n\n> \u57fa\u7ebf TPR@5%FPR={gm('baseline','tpr_at_5fpr'):.4f}\uff0c\u9632\u5fa1\u540e\u663e\u8457\u4e0b\u964d\u3002\u8fd9\u662f\u8861\u91cf\u653b\u51fb\u5371\u5bb3\u7684\u6700\u4e25\u683c\u6307\u6807\u3002")
|
| 519 |
+
gr.Plot(value=fig_tpr())
|
| 520 |
|
| 521 |
+
gr.Markdown("### 5\ufe0f\u20e3 Loss\u5dee\u8ddd\u5bf9\u6bd4\n\n> Gap\u8d8a\u5c0f=\u6210\u5458\u4e0e\u975e\u6210\u5458\u8d8a\u96be\u533a\u5206=\u9632\u5fa1\u8d8a\u6709\u6548\u3002\u9632\u5fa1\u7684\u76ee\u6807\u5c31\u662f\u7f29\u5c0f\u8fd9\u4e2a\u5dee\u8ddd\u3002")
|
| 522 |
+
gr.Plot(value=fig_gap())
|
| 523 |
|
| 524 |
+
gr.Markdown("### 6\ufe0f\u20e3 \u9632\u5fa1\u53c2\u6570\u4e0e\u6548\u679c\u5173\u7cfb\n\n> \u5de6\u56fe\uff1aAUC\u9012\u51cf+\u6548\u7528\u53cd\u5347=\u53cc\u8d62\u3002\u53f3\u56fe\uff1a\u7eff\u8272\u586b\u5145\u9762\u79ef=\u9632\u5fa1\u6536\u76ca\u3002")
|
| 525 |
+
gr.Plot(value=fig_trend())
|
| 526 |
|
| 527 |
+
with gr.Accordion("Loss\u5206\u5e03\u76f4\u65b9\u56fe\uff08\u6807\u7b7e\u5e73\u6ed1 5\u6a21\u578b\uff09",open=False):
|
| 528 |
gr.Plot(value=fig_loss_dist())
|
| 529 |
+
with gr.Accordion("\u5b8c\u6574\u6570\u636e\u8868",open=False):
|
| 530 |
+
gr.Markdown(build_table())
|
| 531 |
|
| 532 |
+
with gr.Tab("\u2696\ufe0f \u6548\u7528\u8bc4\u4f30"):
|
| 533 |
+
gr.Markdown("## \U0001f4ca \u6a21\u578b\u6548\u7528\u6d4b\u8bd5")
|
| 534 |
+
with gr.Row(equal_height=True):
|
| 535 |
+
with gr.Column(): gr.Plot(value=fig_acc())
|
| 536 |
with gr.Column(): gr.Plot(value=fig_tradeoff())
|
| 537 |
+
gr.Markdown(f"> \u6807\u7b7e\u5e73\u6ed1\u5b9e\u73b0\u201c\u53cc\u8d62\u201d\uff1a\u57fa\u7ebf{BAC:.1f}% \u2192 LS(\u03b5=0.2) {gu('smooth_eps_0.2'):.1f}%\u3002\u8f93\u51fa\u6270\u52a8\u59cb\u7ec8{BAC:.1f}%\u3002")
|
| 538 |
+
gr.Markdown("### \U0001f9ea \u5728\u7ebf\u62bd\u6837\u6f14\u793a")
|
| 539 |
+
with gr.Row(equal_height=True):
|
|
|
|
| 540 |
with gr.Column(scale=1):
|
| 541 |
+
e_m=gr.Radio(EV_C,value="\u57fa\u7ebf\u6a21\u578b",label="\u9009\u62e9\u6a21\u578b")
|
| 542 |
+
e_b=gr.Button("\U0001f3b2 \u968f\u673a\u62bd\u9898\u6d4b\u8bd5",variant="primary")
|
|
|
|
| 543 |
with gr.Column(scale=2):
|
| 544 |
+
e_r=gr.HTML()
|
| 545 |
+
e_b.click(cb_eval,[e_m],[e_r])
|
|
|
|
| 546 |
|
| 547 |
+
with gr.Tab("\U0001f4dd \u7814\u7a76\u7ed3\u8bba"):
|
|
|
|
| 548 |
gr.Markdown(f"""\
|
| 549 |
+
## \u6838\u5fc3\u7814\u7a76\u53d1\u73b0
|
|
|
|
|
|
|
| 550 |
|
| 551 |
+
### \u4e00\u3001\u6559\u80b2\u5927\u6a21\u578b\u5b58\u5728\u53ef\u91cf\u5316\u7684MIA\u98ce\u9669
|
| 552 |
+
\u57fa\u7ebf AUC = **{BA:.4f}**\uff0c\u653b\u51fb\u51c6\u786e\u7387 **{gm('baseline','attack_accuracy')*100:.1f}%**
|
| 553 |
|
| 554 |
+
### \u4e8c\u3001\u6807\u7b7e\u5e73\u6ed1\u9632\u5fa1
|
| 555 |
+
| \u03b5 | AUC | \u6548\u7528 |
|
| 556 |
|---|---|---|
|
| 557 |
| 0.02 | {gm('smooth_eps_0.02','auc'):.4f} | {gu('smooth_eps_0.02'):.1f}% |
|
| 558 |
| 0.05 | {gm('smooth_eps_0.05','auc'):.4f} | {gu('smooth_eps_0.05'):.1f}% |
|
| 559 |
| 0.1 | {gm('smooth_eps_0.1','auc'):.4f} | {gu('smooth_eps_0.1'):.1f}% |
|
| 560 |
| 0.2 | {gm('smooth_eps_0.2','auc'):.4f} | {gu('smooth_eps_0.2'):.1f}% |
|
| 561 |
|
| 562 |
+
### \u4e09\u3001\u8f93\u51fa\u6270\u52a8\u9632\u5fa1
|
| 563 |
+
| \u03c3 | AUC | \u6548\u7528 |
|
| 564 |
|---|---|---|
|
| 565 |
+
| 0.01 | {gm('perturbation_0.01','auc'):.4f} | {BAC:.1f}% |
|
| 566 |
+
| 0.02 | {gm('perturbation_0.02','auc'):.4f} | {BAC:.1f}% |
|
| 567 |
+
| 0.03 | {gm('perturbation_0.03','auc'):.4f} | {BAC:.1f}% |
|
| 568 |
+
|
| 569 |
+
> **\u63a8\u8350\u7ec4\u5408: LS(\u03b5=0.1) + OP(\u03c3=0.02)** \u2014 \u8bad\u7ec3\u671f\u7f29\u5c0fGap + \u63a8\u7406\u671f\u566a\u58f0\u906e\u853d\uff0c\u53cc\u91cd\u9632\u5fa1\u3002
|
|
|
|
|
|
|
|
|
|
|
|
|
| 570 |
""")
|
| 571 |
|
| 572 |
demo.launch()
|