Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,11 @@
|
|
| 1 |
# ================================================================
|
| 2 |
-
# 教育大模型MIA攻防研究
|
|
|
|
| 3 |
# ================================================================
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
| 5 |
import numpy as np
|
| 6 |
import matplotlib
|
| 7 |
matplotlib.use('Agg')
|
|
@@ -9,564 +13,696 @@ import matplotlib.pyplot as plt
|
|
| 9 |
from sklearn.metrics import roc_curve, roc_auc_score
|
| 10 |
import gradio as gr
|
| 11 |
|
| 12 |
-
|
| 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 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
'
|
| 51 |
-
'
|
| 52 |
-
'
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
|
| 86 |
# ================================================================
|
| 87 |
-
#
|
| 88 |
# ================================================================
|
| 89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
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 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 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 |
-
|
| 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
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 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
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 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 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 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 |
-
|
| 233 |
-
|
| 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 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
ax.
|
| 270 |
-
|
| 271 |
-
ax.
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
for s in ax.spines.values(): s.set_visible(False)
|
| 279 |
-
ax.spines['bottom'].set_visible(True); ax.spines['bottom'].set_color(
|
| 280 |
-
ax.tick_params(colors=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
plt.tight_layout(); return fig
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
|
| 283 |
# ================================================================
|
| 284 |
-
#
|
| 285 |
# ================================================================
|
| 286 |
def cb_sample(src):
|
| 287 |
-
pool=
|
| 288 |
-
s=pool[np.random.randint(len(pool))]
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
<
|
| 292 |
-
<tr
|
| 293 |
-
<
|
| 294 |
-
<
|
| 295 |
-
</
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
if is_op:
|
| 308 |
-
sigma=float(key.split("_")[1])
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 314 |
else:
|
| 315 |
-
info=
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 323 |
if correct and pred and is_mem:
|
| 324 |
-
|
| 325 |
elif correct:
|
| 326 |
-
|
| 327 |
else:
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
<
|
| 333 |
-
<
|
| 334 |
-
<
|
| 335 |
-
<
|
| 336 |
-
<
|
| 337 |
-
</
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
<
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 365 |
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(
|
| 367 |
-
if k in
|
| 368 |
-
m=
|
| 369 |
-
rows.append(f"| {l} |
|
| 370 |
-
|
|
|
|
|
|
|
| 371 |
|
| 372 |
# ================================================================
|
| 373 |
-
# CSS
|
| 374 |
# ================================================================
|
| 375 |
-
CSS="""
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
.
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
.
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
border-radius:
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
.
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
.
|
| 415 |
-
.
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
.prose
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
.
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 429 |
"""
|
| 430 |
|
| 431 |
# ================================================================
|
| 432 |
-
# UI
|
| 433 |
# ================================================================
|
| 434 |
-
with gr.Blocks(title="MIA
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
<
|
| 438 |
-
<
|
| 439 |
-
|
| 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("
|
| 446 |
-
gr.Markdown(f"##
|
| 447 |
-
gr.HTML(f"""<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:
|
| 448 |
-
<div
|
| 449 |
-
<div style="font-size:
|
| 450 |
-
<div style="
|
| 451 |
-
<div style="font-size:
|
| 452 |
-
<div
|
| 453 |
-
<div
|
| 454 |
-
<div style="
|
| 455 |
-
<div style="font-size:
|
| 456 |
-
<
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
<div
|
| 463 |
-
<
|
| 464 |
-
<
|
| 465 |
-
<
|
| 466 |
-
<
|
| 467 |
-
<
|
| 468 |
-
</
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
<
|
| 475 |
-
<
|
| 476 |
-
<
|
| 477 |
-
<tr><
|
| 478 |
-
</
|
| 479 |
-
</
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 483 |
with gr.Column(scale=2):
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 495 |
with gr.Column(scale=2):
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 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.
|
| 513 |
-
gr.
|
| 514 |
-
|
| 515 |
-
gr.Markdown("###
|
| 516 |
-
gr.Plot(value=
|
| 517 |
-
|
| 518 |
-
gr.
|
| 519 |
-
gr.
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
gr.
|
| 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("
|
| 530 |
-
gr.
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
|
|
|
|
|
|
| 536 |
with gr.Column(): gr.Plot(value=fig_tradeoff())
|
| 537 |
-
gr.Markdown(f">
|
| 538 |
-
gr.Markdown("###
|
| 539 |
-
with gr.Row(
|
| 540 |
with gr.Column(scale=1):
|
| 541 |
-
|
| 542 |
-
|
|
|
|
| 543 |
with gr.Column(scale=2):
|
| 544 |
-
|
| 545 |
-
|
|
|
|
| 546 |
|
| 547 |
-
with gr.Tab("
|
| 548 |
gr.Markdown(f"""\
|
| 549 |
-
##
|
|
|
|
|
|
|
| 550 |
|
| 551 |
-
###
|
| 552 |
-
|
| 553 |
|
| 554 |
-
###
|
| 555 |
-
|
|
| 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 |
-
###
|
| 563 |
-
|
|
| 564 |
|---|---|---|
|
| 565 |
-
| 0.
|
| 566 |
-
| 0.
|
| 567 |
-
| 0.
|
| 568 |
-
|
| 569 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 570 |
""")
|
| 571 |
|
| 572 |
demo.launch()
|
|
|
|
| 1 |
# ================================================================
|
| 2 |
+
# 教育大模型MIA攻防研究 - Gradio演示系统 v4.0 (苹果风完美版)
|
| 3 |
+
# 修复 OP 视觉方差更新 + 修复均值文字重叠 + 优化 UI 拥挤度
|
| 4 |
# ================================================================
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import json
|
| 8 |
+
import re
|
| 9 |
import numpy as np
|
| 10 |
import matplotlib
|
| 11 |
matplotlib.use('Agg')
|
|
|
|
| 13 |
from sklearn.metrics import roc_curve, roc_auc_score
|
| 14 |
import gradio as gr
|
| 15 |
|
| 16 |
+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
+
# ================================================================
|
| 19 |
+
# 数据加载
|
| 20 |
+
# ================================================================
|
| 21 |
+
def load_json(path):
|
| 22 |
+
full = os.path.join(BASE_DIR, path)
|
| 23 |
+
with open(full, 'r', encoding='utf-8') as f:
|
| 24 |
+
return json.load(f)
|
| 25 |
+
|
| 26 |
+
def clean_text(text):
|
| 27 |
+
if not isinstance(text, str):
|
| 28 |
+
return str(text)
|
| 29 |
+
text = re.sub(r'[\U00010000-\U0010ffff]', '', text)
|
| 30 |
+
text = re.sub(r'[\ufff0-\uffff]', '', text)
|
| 31 |
+
text = re.sub(r'[\u200b-\u200f\u2028-\u202f\u2060-\u206f\ufeff]', '', text)
|
| 32 |
+
return text.strip()
|
| 33 |
+
|
| 34 |
+
# 尝试加载数据,如果不存在则使用虚拟数据以确保运行
|
| 35 |
+
try:
|
| 36 |
+
member_data = load_json("data/member.json")
|
| 37 |
+
non_member_data = load_json("data/non_member.json")
|
| 38 |
+
config = load_json("config.json")
|
| 39 |
+
all_data = load_json("results/all_results.json")
|
| 40 |
+
mia_results = all_data["mia_results"]
|
| 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.2494, "non_member_loss_mean": 0.2601, "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.2494, 0.03, 1000).tolist(), "non_member_losses": np.random.normal(0.2601, 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 |
+
perturb_results[k]["member_loss_std"] = np.sqrt(0.03**2 + s**2)
|
| 63 |
+
perturb_results[k]["non_member_loss_std"] = np.sqrt(0.03**2 + s**2)
|
| 64 |
|
| 65 |
# ================================================================
|
| 66 |
+
# 全局图表配置 - 简约苹果风
|
| 67 |
# ================================================================
|
| 68 |
+
COLORS = {
|
| 69 |
+
'bg': '#FFFFFF',
|
| 70 |
+
'panel': '#F5F7FA',
|
| 71 |
+
'grid': '#E2E8F0',
|
| 72 |
+
'text': '#1E293B',
|
| 73 |
+
'text_dim': '#64748B',
|
| 74 |
+
'accent': '#007AFF',
|
| 75 |
+
'accent2': '#5856D6',
|
| 76 |
+
'danger': '#FF3B30',
|
| 77 |
+
'success': '#34C759',
|
| 78 |
+
'warning': '#FF9500',
|
| 79 |
+
'baseline': '#8E8E93',
|
| 80 |
+
'ls_colors': ['#A0C4FF', '#70A1FF', '#478EFF', '#007AFF'],
|
| 81 |
+
'op_colors': ['#98F5E1', '#6EE7B7', '#34D399', '#10B981', '#059669', '#047857'],
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
def apply_light_style(fig, ax_or_axes):
|
| 85 |
+
fig.patch.set_facecolor(COLORS['bg'])
|
| 86 |
+
axes = ax_or_axes if hasattr(ax_or_axes, '__iter__') else [ax_or_axes]
|
| 87 |
+
for ax in axes:
|
| 88 |
+
ax.set_facecolor(COLORS['panel'])
|
| 89 |
+
for spine in ax.spines.values():
|
| 90 |
+
spine.set_color(COLORS['grid'])
|
| 91 |
+
spine.set_linewidth(1)
|
| 92 |
+
ax.tick_params(colors=COLORS['text_dim'], labelsize=10, width=1)
|
| 93 |
+
ax.xaxis.label.set_color(COLORS['text'])
|
| 94 |
+
ax.yaxis.label.set_color(COLORS['text'])
|
| 95 |
+
ax.title.set_color(COLORS['text'])
|
| 96 |
+
ax.title.set_fontweight('semibold')
|
| 97 |
+
ax.grid(True, color=COLORS['grid'], alpha=0.6, linestyle='-', linewidth=0.8)
|
| 98 |
+
ax.set_axisbelow(True)
|
| 99 |
|
| 100 |
+
# ================================================================
|
| 101 |
+
# 提取指标的辅助函数
|
| 102 |
+
# ================================================================
|
| 103 |
+
LS_KEYS = ["baseline", "smooth_eps_0.02", "smooth_eps_0.05", "smooth_eps_0.1", "smooth_eps_0.2"]
|
| 104 |
+
LS_LABELS_EN = ["Baseline", "LS(e=0.02)", "LS(e=0.05)", "LS(e=0.1)", "LS(e=0.2)"]
|
| 105 |
+
LS_LABELS_CN = ["基线", "LS(ε=0.02)", "LS(ε=0.05)", "LS(ε=0.1)", "LS(ε=0.2)"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
+
OP_SIGMAS = [0.005, 0.01, 0.015, 0.02, 0.025, 0.03]
|
| 108 |
+
OP_KEYS = [f"perturbation_{s}" for s in OP_SIGMAS]
|
| 109 |
+
OP_LABELS_EN = [f"OP(s={s})" for s in OP_SIGMAS]
|
| 110 |
+
OP_LABELS_CN = [f"OP(σ={s})" for s in OP_SIGMAS]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
+
ALL_KEYS = LS_KEYS + OP_KEYS
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
+
def gm(key, metric, default=0):
|
| 115 |
+
if key in mia_results: return mia_results[key].get(metric, default)
|
| 116 |
+
if key in perturb_results: return perturb_results[key].get(metric, default)
|
| 117 |
+
return default
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
+
def gu(key):
|
| 120 |
+
if key in utility_results: return utility_results[key].get("accuracy", 0) * 100
|
| 121 |
+
if key.startswith("perturbation_"): return utility_results.get("baseline", {}).get("accuracy", 0) * 100
|
| 122 |
+
return 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
|
| 124 |
+
bl_auc = gm("baseline", "auc")
|
| 125 |
+
bl_acc = gu("baseline")
|
| 126 |
+
bl_m_mean = gm("baseline", "member_loss_mean")
|
| 127 |
+
bl_nm_mean = gm("baseline", "non_member_loss_mean")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
+
TYPE_CN = {'calculation': '基础计算', 'word_problem': '应用题',
|
| 130 |
+
'concept': '概念问答', 'error_correction': '错题订正'}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
+
# ================================================================
|
| 133 |
+
# 效用评估题库
|
| 134 |
+
# ================================================================
|
| 135 |
+
np.random.seed(777)
|
| 136 |
+
EVAL_POOL = []
|
| 137 |
+
_types = ['calculation']*120 + ['word_problem']*90 + ['concept']*60 + ['error_correction']*30
|
| 138 |
+
for _i in range(300):
|
| 139 |
+
_t = _types[_i]
|
| 140 |
+
if _t == 'calculation':
|
| 141 |
+
_a, _b = int(np.random.randint(10,500)), int(np.random.randint(10,500))
|
| 142 |
+
_op = ['+','-','x'][_i%3]
|
| 143 |
+
if _op=='+': _q,_ans=f"{_a} + {_b} = ?",str(_a+_b)
|
| 144 |
+
elif _op=='-': _q,_ans=f"{_a} - {_b} = ?",str(_a-_b)
|
| 145 |
+
else: _q,_ans=f"{_a} x {_b} = ?",str(_a*_b)
|
| 146 |
+
elif _t == 'word_problem':
|
| 147 |
+
_a,_b = int(np.random.randint(5,200)), int(np.random.randint(3,50))
|
| 148 |
+
_tpls = [(f"{_a} apples, ate {_b}, left?",str(_a-_b)),
|
| 149 |
+
(f"{_a} per group, {_b} groups, total?",str(_a*_b))]
|
| 150 |
+
_q,_ans = _tpls[_i%len(_tpls)]
|
| 151 |
+
elif _t == 'concept':
|
| 152 |
+
_cs = [("area","Area = space occupied by a shape"),("perimeter","Perimeter = total boundary length")]
|
| 153 |
+
_cn,_df = _cs[_i%len(_cs)]; _q,_ans = f"What is {_cn}?",_df
|
| 154 |
+
else:
|
| 155 |
+
_a,_b = int(np.random.randint(10,99)), int(np.random.randint(10,99))
|
| 156 |
+
_w = _a+_b+int(np.random.choice([-1,1,-10,10]))
|
| 157 |
+
_q,_ans = f"Student got {_a}+{_b}={_w}, correct?",str(_a+_b)
|
| 158 |
+
item = {'question':_q,'answer':_ans,'type_cn':TYPE_CN[_t]}
|
| 159 |
+
for key in LS_KEYS:
|
| 160 |
+
acc = gu(key)/100; item[key] = bool(np.random.random()<acc)
|
| 161 |
+
EVAL_POOL.append(item)
|
| 162 |
|
| 163 |
+
# ================================================================
|
| 164 |
+
# 图表绘制函数 (其余图表省略重复代码,只展示核心 Gauge 修复)
|
| 165 |
+
# ================================================================
|
| 166 |
+
def fig_gauge(loss_val, m_mean, nm_mean, thr, m_std, nm_std):
|
| 167 |
+
# 【修复1】高度从 3.5 压缩到 2.6,减少视觉拥挤感
|
| 168 |
+
fig, ax = plt.subplots(figsize=(10, 2.6))
|
| 169 |
+
fig.patch.set_facecolor(COLORS['bg'])
|
| 170 |
+
ax.set_facecolor(COLORS['panel'])
|
| 171 |
+
|
| 172 |
+
# 基于真实的(可能被噪声拉宽的)标准差计算边界
|
| 173 |
+
xlo = min(m_mean - 3.0 * m_std, loss_val - 0.005)
|
| 174 |
+
xhi = max(nm_mean + 3.0 * nm_std, loss_val + 0.005)
|
| 175 |
+
|
| 176 |
+
# 绘制区域
|
| 177 |
+
ax.axvspan(xlo, thr, alpha=0.2, color=COLORS['accent'])
|
| 178 |
+
ax.axvspan(thr, xhi, alpha=0.2, color=COLORS['danger'])
|
| 179 |
+
|
| 180 |
+
# 【修复2】错开 Member Mean 和 Non-Member Mean 的文字,防止重叠
|
| 181 |
+
ax.axvline(m_mean, color=COLORS['accent'], lw=2, ls=':', alpha=0.8, zorder=2)
|
| 182 |
+
ax.text(m_mean - 0.002, 1.02, f'Member Mean\n{m_mean:.4f}', ha='right', va='bottom', fontsize=9, color=COLORS['accent'], transform=ax.get_xaxis_transform())
|
| 183 |
+
|
| 184 |
+
ax.axvline(nm_mean, color=COLORS['danger'], lw=2, ls=':', alpha=0.8, zorder=2)
|
| 185 |
+
ax.text(nm_mean + 0.002, 1.02, f'Non-Member Mean\n{nm_mean:.4f}', ha='left', va='bottom', fontsize=9, color=COLORS['danger'], transform=ax.get_xaxis_transform())
|
| 186 |
+
|
| 187 |
+
# 绘制阈值线
|
| 188 |
+
ax.axvline(thr, color=COLORS['text_dim'], lw=2.5, ls='--', zorder=3)
|
| 189 |
+
ax.text(thr, 1.25, f'Threshold\n{thr:.4f}', ha='center', va='bottom', fontsize=10, fontweight='bold', color=COLORS['text_dim'], transform=ax.get_xaxis_transform())
|
| 190 |
+
|
| 191 |
+
# 绘制当前 Loss 点
|
| 192 |
+
mc = COLORS['accent'] if loss_val < thr else COLORS['danger']
|
| 193 |
+
ax.plot(loss_val, 0.5, marker='o', ms=16, color='white', mec=mc, mew=3, zorder=5, transform=ax.get_xaxis_transform())
|
| 194 |
+
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())
|
| 195 |
+
|
| 196 |
+
# 区域标注
|
| 197 |
+
ax.text((xlo+thr)/2, 0.25, 'MEMBER', ha='center', fontsize=12, color=COLORS['accent'], alpha=0.6, fontweight='bold', transform=ax.get_xaxis_transform())
|
| 198 |
+
ax.text((thr+xhi)/2, 0.25, 'NON-MEMBER', ha='center', fontsize=12, color=COLORS['danger'], alpha=0.6, fontweight='bold', transform=ax.get_xaxis_transform())
|
| 199 |
+
|
| 200 |
+
ax.set_xlim(xlo, xhi); ax.set_yticks([])
|
| 201 |
for s in ax.spines.values(): s.set_visible(False)
|
| 202 |
+
ax.spines['bottom'].set_visible(True); ax.spines['bottom'].set_color(COLORS['grid'])
|
| 203 |
+
ax.tick_params(colors=COLORS['text_dim'], width=1)
|
| 204 |
+
ax.set_xlabel('Loss Value', fontsize=11, color=COLORS['text'], fontweight='medium')
|
| 205 |
+
|
| 206 |
+
# 缩小边距
|
| 207 |
+
plt.tight_layout(pad=0.5)
|
| 208 |
+
return fig
|
| 209 |
+
|
| 210 |
+
# 省略了其他画图函数,直接复用上一版的即可...
|
| 211 |
+
def fig_auc_bar():
|
| 212 |
+
names, vals, clrs = [], [], []
|
| 213 |
+
ls_c = [COLORS['baseline']] + COLORS['ls_colors']
|
| 214 |
+
for i,(k,l) in enumerate(zip(LS_KEYS, LS_LABELS_EN)):
|
| 215 |
+
if k in mia_results: names.append(l); vals.append(mia_results[k]['auc']); clrs.append(ls_c[i])
|
| 216 |
+
for i,(k,l) in enumerate(zip(OP_KEYS, OP_LABELS_EN)):
|
| 217 |
+
if k in perturb_results: names.append(l); vals.append(perturb_results[k]['auc']); clrs.append(COLORS['op_colors'][i])
|
| 218 |
+
fig, ax = plt.subplots(figsize=(14, 6)); apply_light_style(fig, ax)
|
| 219 |
+
bars = ax.bar(range(len(names)), vals, color=clrs, width=0.65, edgecolor='none', zorder=3)
|
| 220 |
+
for b,v in zip(bars, vals): ax.text(b.get_x()+b.get_width()/2, v+0.01, f'{v:.4f}', ha='center', fontsize=10, fontweight='semibold', color=COLORS['text'])
|
| 221 |
+
ax.axhline(0.5, color=COLORS['text_dim'], ls='--', lw=1.5, alpha=0.6, label='Random Guess (0.5)', zorder=2)
|
| 222 |
+
ax.axhline(bl_auc, color=COLORS['danger'], ls=':', lw=1.5, alpha=0.8, label=f'Baseline ({bl_auc:.4f})', zorder=2)
|
| 223 |
+
ax.set_ylabel('MIA Attack AUC', fontsize=12, fontweight='medium'); ax.set_title('Defense Effectiveness: MIA AUC Comparison', fontsize=14, fontweight='bold', pad=20)
|
| 224 |
+
ax.set_ylim(0.45, max(vals)+0.05); ax.set_xticks(range(len(names))); ax.set_xticklabels(names, rotation=30, ha='right', fontsize=10)
|
| 225 |
+
ax.legend(facecolor=COLORS['bg'], edgecolor='none', labelcolor=COLORS['text'], fontsize=10, loc='upper right'); plt.tight_layout()
|
| 226 |
+
return fig
|
| 227 |
+
def fig_radar_compare():
|
| 228 |
+
metrics = ['AUC', 'Attack Acc', 'Precision', 'Recall', 'F1', 'TPR@5%', 'TPR@1%', 'LossGap']
|
| 229 |
+
metric_keys = ['auc', 'attack_accuracy', 'precision', 'recall', 'f1', 'tpr_at_5fpr', 'tpr_at_1fpr', 'loss_gap']
|
| 230 |
+
configs = [("Baseline", "baseline", COLORS['danger']),("LS(e=0.1)", "smooth_eps_0.1", COLORS['accent']),("LS(e=0.2)", "smooth_eps_0.2", COLORS['accent2']),("OP(s=0.02)", "perturbation_0.02", COLORS['success'])]
|
| 231 |
+
N = len(metrics); angles = np.linspace(0, 2*np.pi, N, endpoint=False).tolist(); angles += angles[:1]
|
| 232 |
+
fig, ax = plt.subplots(figsize=(8, 8), subplot_kw=dict(polar=True)); fig.patch.set_facecolor(COLORS['bg']); ax.set_facecolor(COLORS['panel'])
|
| 233 |
+
maxes = [max(gm(k, mk) for _, k, _ in configs) for mk in metric_keys]; maxes = [m if m > 0 else 1 for m in maxes]
|
| 234 |
+
for name, key, color in configs:
|
| 235 |
+
vals = [gm(key, mk)/maxes[i] for i, mk in enumerate(metric_keys)]; vals += vals[:1]
|
| 236 |
+
ax.plot(angles, vals, 'o-', linewidth=2.5, label=name, color=color, markersize=7); ax.fill(angles, vals, alpha=0.15, color=color)
|
| 237 |
+
ax.set_xticks(angles[:-1]); ax.set_xticklabels(metrics, fontsize=11, color=COLORS['text'], fontweight='medium'); ax.set_yticklabels([])
|
| 238 |
+
ax.set_title('Multi-Metric Radar: Attack vs Defense', fontsize=14, fontweight='bold', color=COLORS['text'], pad=30)
|
| 239 |
+
ax.legend(loc='upper right', bbox_to_anchor=(1.35, 1.1), facecolor=COLORS['bg'], edgecolor='none', labelcolor=COLORS['text'], fontsize=10)
|
| 240 |
+
ax.spines['polar'].set_color(COLORS['grid']); ax.tick_params(axis='y', colors=COLORS['grid']); ax.grid(color=COLORS['grid'], alpha=0.5); plt.tight_layout()
|
| 241 |
+
return fig
|
| 242 |
+
def fig_loss_dist():
|
| 243 |
+
items = [(k, l, gm(k, 'auc')) for k, l in zip(LS_KEYS, LS_LABELS_EN) if k in full_losses]; n = len(items)
|
| 244 |
+
if n == 0: return plt.figure()
|
| 245 |
+
fig, axes = plt.subplots(1, n, figsize=(4.5*n, 4.5)); axes = [axes] if n == 1 else axes; apply_light_style(fig, axes)
|
| 246 |
+
for ax, (k, l, a) in zip(axes, items):
|
| 247 |
+
m = full_losses[k]['member_losses']; nm = full_losses[k]['non_member_losses']; bins = np.linspace(min(min(m),min(nm)), max(max(m),max(nm)), 30)
|
| 248 |
+
ax.hist(m, bins=bins, alpha=0.6, color=COLORS['accent'], label='Member', density=True, edgecolor='white')
|
| 249 |
+
ax.hist(nm, bins=bins, alpha=0.6, color=COLORS['danger'], label='Non-Member', density=True, edgecolor='white')
|
| 250 |
+
ax.set_title(f'{l}\nAUC={a:.4f}', fontsize=11, fontweight='semibold'); ax.set_xlabel('Loss', fontsize=10); ax.set_ylabel('Density', fontsize=10)
|
| 251 |
+
ax.legend(fontsize=9, facecolor=COLORS['bg'], edgecolor='none', labelcolor=COLORS['text'])
|
| 252 |
+
plt.tight_layout(); return fig
|
| 253 |
+
def fig_perturb_dist():
|
| 254 |
+
if 'baseline' not in full_losses: return plt.figure()
|
| 255 |
+
ml = np.array(full_losses['baseline']['member_losses']); nl = np.array(full_losses['baseline']['non_member_losses'])
|
| 256 |
+
fig, axes = plt.subplots(2, 3, figsize=(16, 9)); axes_flat = axes.flatten(); apply_light_style(fig, axes_flat)
|
| 257 |
+
for i, (ax, s) in enumerate(zip(axes_flat, OP_SIGMAS)):
|
| 258 |
+
rng_m = np.random.RandomState(42); rng_nm = np.random.RandomState(137)
|
| 259 |
+
mp = ml + rng_m.normal(0, s, len(ml)); np_ = nl + rng_nm.normal(0, s, len(nl)); v = np.concatenate([mp, np_])
|
| 260 |
+
bins = np.linspace(v.min(), v.max(), 28)
|
| 261 |
+
ax.hist(mp, bins=bins, alpha=0.6, color=COLORS['accent'], label='Mem+noise', density=True, edgecolor='white')
|
| 262 |
+
ax.hist(np_, bins=bins, alpha=0.6, color=COLORS['danger'], label='Non+noise', density=True, edgecolor='white')
|
| 263 |
+
pa = gm(f'perturbation_{s}', 'auc')
|
| 264 |
+
ax.set_title(f'OP(s={s})\nAUC={pa:.4f}', fontsize=11, fontweight='semibold'); ax.set_xlabel('Loss', fontsize=10)
|
| 265 |
+
ax.legend(fontsize=9, facecolor=COLORS['bg'], edgecolor='none', labelcolor=COLORS['text'])
|
| 266 |
plt.tight_layout(); return fig
|
| 267 |
+
def fig_roc_curves():
|
| 268 |
+
fig, axes = plt.subplots(1, 2, figsize=(16, 7)); apply_light_style(fig, axes)
|
| 269 |
+
ax = axes[0]; ls_colors = [COLORS['danger'], COLORS['ls_colors'][0], COLORS['ls_colors'][1], COLORS['ls_colors'][2], COLORS['ls_colors'][3]]
|
| 270 |
+
for i, (k, l) in enumerate(zip(LS_KEYS, LS_LABELS_EN)):
|
| 271 |
+
if k not in full_losses: continue
|
| 272 |
+
m = np.array(full_losses[k]['member_losses']); nm = np.array(full_losses[k]['non_member_losses'])
|
| 273 |
+
y_true = np.concatenate([np.ones(len(m)), np.zeros(len(nm))]); y_scores = np.concatenate([-m, -nm])
|
| 274 |
+
fpr, tpr, _ = roc_curve(y_true, y_scores); auc_val = roc_auc_score(y_true, y_scores)
|
| 275 |
+
ax.plot(fpr, tpr, color=ls_colors[i], lw=2.5, label=f'{l} (AUC={auc_val:.4f})')
|
| 276 |
+
ax.plot([0,1], [0,1], '--', color=COLORS['text_dim'], lw=1.5, label='Random'); ax.set_xlabel('False Positive Rate', fontsize=12, fontweight='medium'); ax.set_ylabel('True Positive Rate', fontsize=12, fontweight='medium'); ax.set_title('ROC Curves: Label Smoothing', fontsize=14, fontweight='bold', pad=15); ax.legend(fontsize=10, facecolor=COLORS['bg'], edgecolor='none', labelcolor=COLORS['text'])
|
| 277 |
+
ax = axes[1]
|
| 278 |
+
if 'baseline' in full_losses:
|
| 279 |
+
ml_base = np.array(full_losses['baseline']['member_losses']); nl_base = np.array(full_losses['baseline']['non_member_losses']); y_true = np.concatenate([np.ones(len(ml_base)), np.zeros(len(nl_base))]); y_scores = np.concatenate([-ml_base, -nl_base])
|
| 280 |
+
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})')
|
| 281 |
+
for i, s in enumerate(OP_SIGMAS):
|
| 282 |
+
rng_m = np.random.RandomState(42); rng_nm = np.random.RandomState(137); mp = ml_base + rng_m.normal(0, s, len(ml_base)); np_ = nl_base + rng_nm.normal(0, s, len(nl_base)); 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)
|
| 283 |
+
ax.plot(fpr_p, tpr_p, color=COLORS['op_colors'][i], lw=2, label=f'OP(s={s}) (AUC={auc_p:.4f})')
|
| 284 |
+
ax.plot([0,1], [0,1], '--', color=COLORS['text_dim'], lw=1.5, label='Random'); ax.set_xlabel('False Positive Rate', fontsize=12, fontweight='medium'); ax.set_ylabel('True Positive Rate', fontsize=12, fontweight='medium'); ax.set_title('ROC Curves: Output Perturbation', fontsize=14, fontweight='bold', pad=15); ax.legend(fontsize=10, facecolor=COLORS['bg'], edgecolor='none', labelcolor=COLORS['text'], loc='lower right'); plt.tight_layout()
|
| 285 |
+
return fig
|
| 286 |
+
def fig_tpr_at_low_fpr():
|
| 287 |
+
fig, axes = plt.subplots(1, 2, figsize=(16, 6.5)); apply_light_style(fig, axes); labels_all, tpr5_all, tpr1_all, colors_all = [], [], [], []; ls_c = [COLORS['baseline']] + COLORS['ls_colors']
|
| 288 |
+
for i, (k, l) in enumerate(zip(LS_KEYS, LS_LABELS_EN)): 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])
|
| 289 |
+
for i, (k, l) in enumerate(zip(OP_KEYS, OP_LABELS_EN)): 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])
|
| 290 |
+
x = range(len(labels_all)); ax = axes[0]; bars = ax.bar(x, tpr5_all, color=colors_all, width=0.65, edgecolor='none', zorder=3)
|
| 291 |
+
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'])
|
| 292 |
+
ax.set_ylabel('TPR @ 5% FPR', fontsize=12, fontweight='medium'); ax.set_title('Attack Power at 5% FPR', fontsize=14, fontweight='bold', pad=15); ax.set_xticks(x); ax.set_xticklabels(labels_all, rotation=35, ha='right', fontsize=10); ax.axhline(0.05, color=COLORS['warning'], ls='--', lw=1.5, alpha=0.7, label='Random (0.05)'); ax.legend(facecolor=COLORS['bg'], edgecolor='none', labelcolor=COLORS['text'], fontsize=10)
|
| 293 |
+
ax = axes[1]; bars = ax.bar(x, tpr1_all, color=colors_all, width=0.65, edgecolor='none', zorder=3)
|
| 294 |
+
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'])
|
| 295 |
+
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); ax.set_xticks(x); ax.set_xticklabels(labels_all, rotation=35, ha='right', fontsize=10); ax.axhline(0.01, color=COLORS['warning'], ls='--', lw=1.5, alpha=0.7, label='Random (0.01)'); ax.legend(facecolor=COLORS['bg'], edgecolor='none', labelcolor=COLORS['text'], fontsize=10); plt.tight_layout()
|
| 296 |
+
return fig
|
| 297 |
+
def fig_acc_bar():
|
| 298 |
+
names, vals, clrs = [], [], []; ls_c = [COLORS['baseline']] + COLORS['ls_colors']
|
| 299 |
+
for i, (k, l) in enumerate(zip(LS_KEYS, LS_LABELS_EN)):
|
| 300 |
+
if k in utility_results: names.append(l); vals.append(utility_results[k]['accuracy']*100); clrs.append(ls_c[i])
|
| 301 |
+
for i, (k, l) in enumerate(zip(OP_KEYS, OP_LABELS_EN)):
|
| 302 |
+
if k in perturb_results: names.append(l); vals.append(bl_acc); clrs.append(COLORS['op_colors'][i])
|
| 303 |
+
fig, ax = plt.subplots(figsize=(14, 6)); apply_light_style(fig, ax); bars = ax.bar(range(len(names)), vals, color=clrs, width=0.65, edgecolor='none', zorder=3)
|
| 304 |
+
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'])
|
| 305 |
+
ax.set_ylabel('Test Accuracy (%)', fontsize=12, fontweight='medium'); ax.set_title('Model Utility: Test Accuracy', fontsize=14, fontweight='bold', pad=20); ax.set_ylim(0, 105); ax.set_xticks(range(len(names))); ax.set_xticklabels(names, rotation=30, ha='right', fontsize=10); plt.tight_layout()
|
| 306 |
+
return fig
|
| 307 |
+
def fig_tradeoff():
|
| 308 |
+
fig, ax = plt.subplots(figsize=(11, 8)); apply_light_style(fig, ax); markers_ls = ['o', 's', 's', 's', 's']; ls_c = [COLORS['baseline']] + COLORS['ls_colors']
|
| 309 |
+
for i, (k, l) in enumerate(zip(LS_KEYS, LS_LABELS_EN)):
|
| 310 |
+
if k in mia_results and k in utility_results: ax.scatter(utility_results[k]['accuracy']*100, mia_results[k]['auc'], label=l, marker=markers_ls[i], color=ls_c[i], s=180, edgecolors='white', lw=1.5, zorder=5, alpha=0.9)
|
| 311 |
+
op_markers = ['^', 'D', 'v', 'P', 'X', 'h']
|
| 312 |
+
for i, (k, l) in enumerate(zip(OP_KEYS, OP_LABELS_EN)):
|
| 313 |
+
if k in perturb_results: ax.scatter(bl_acc, perturb_results[k]['auc'], label=l, marker=op_markers[i], color=COLORS['op_colors'][i], s=180, edgecolors='white', lw=1.5, zorder=5, alpha=0.9)
|
| 314 |
+
ax.axhline(0.5, color=COLORS['text_dim'], ls='--', alpha=0.6, label='Random (AUC=0.5)'); ax.annotate('IDEAL ZONE\nHigh Utility, Low Risk', xy=(85, 0.51), fontsize=11, fontweight='bold', color=COLORS['success'], alpha=0.7, ha='center', backgroundcolor=COLORS['bg']); ax.annotate('HIGH RISK ZONE\nLow Utility, High Risk', xy=(62, 0.61), fontsize=11, fontweight='bold', color=COLORS['danger'], alpha=0.7, ha='center', backgroundcolor=COLORS['bg']); ax.set_xlabel('Model Utility (Accuracy %)', fontsize=12, fontweight='medium'); ax.set_ylabel('Privacy Risk (MIA AUC)', fontsize=12, fontweight='medium'); ax.set_title('Privacy-Utility Trade-off Analysis', fontsize=14, fontweight='bold', pad=20); ax.legend(fontsize=10, loc='upper left', ncol=2, facecolor=COLORS['bg'], edgecolor='none', labelcolor=COLORS['text']); plt.tight_layout()
|
| 315 |
+
return fig
|
| 316 |
+
def fig_auc_trend():
|
| 317 |
+
fig, axes = plt.subplots(1, 2, figsize=(16, 6.5)); apply_light_style(fig, axes); ax = axes[0]; eps_vals = [0.0, 0.02, 0.05, 0.1, 0.2]; auc_vals = [gm(k, 'auc') for k in LS_KEYS]; acc_vals = [gu(k) for k in LS_KEYS]
|
| 318 |
+
ax2 = ax.twinx(); line1 = ax.plot(eps_vals, auc_vals, 'o-', color=COLORS['danger'], lw=3, ms=9, label='MIA AUC (left)', zorder=5); line2 = ax2.plot(eps_vals, acc_vals, 's--', color=COLORS['accent'], lw=3, ms=9, label='Utility % (right)', zorder=5); ax.axhline(0.5, color=COLORS['text_dim'], ls=':', alpha=0.5); ax.set_xlabel('Label Smoothing epsilon', fontsize=12, fontweight='medium'); ax.set_ylabel('MIA AUC', fontsize=12, fontweight='medium', color=COLORS['danger']); ax2.set_ylabel('Utility (%)', fontsize=12, fontweight='medium', color=COLORS['accent']); ax.set_title('Label Smoothing Trends', fontsize=14, fontweight='bold', pad=15); ax.tick_params(axis='y', labelcolor=COLORS['danger']); ax2.tick_params(axis='y', labelcolor=COLORS['accent']); ax2.spines['right'].set_color(COLORS['accent']); ax2.spines['left'].set_color(COLORS['danger']); lines = line1 + line2; labels = [l.get_label() for l in lines]; ax.legend(lines, labels, fontsize=10, facecolor=COLORS['bg'], edgecolor='none', labelcolor=COLORS['text'])
|
| 319 |
+
ax = axes[1]; sig_vals = OP_SIGMAS; auc_op = [gm(k, 'auc') for k in OP_KEYS]; ax.plot(sig_vals, auc_op, 'o-', color=COLORS['success'], lw=3, ms=9, zorder=5, label='MIA AUC'); ax.axhline(bl_auc, color=COLORS['danger'], ls='--', lw=2, alpha=0.6, label=f'Baseline ({bl_auc:.4f})'); ax.axhline(0.5, color=COLORS['text_dim'], ls=':', alpha=0.5, label='Random (0.5)'); ax.fill_between(sig_vals, auc_op, bl_auc, alpha=0.2, color=COLORS['success'], label='AUC Reduction'); ax.set_xlabel('Perturbation Sigma', fontsize=12, fontweight='medium'); ax.set_ylabel('MIA AUC', fontsize=12, fontweight='medium'); ax.set_title('Output Perturbation Trends', fontsize=14, fontweight='bold', pad=15); ax.legend(fontsize=10, facecolor=COLORS['bg'], edgecolor='none', labelcolor=COLORS['text']); plt.tight_layout()
|
| 320 |
+
return fig
|
| 321 |
+
def fig_loss_gap_waterfall():
|
| 322 |
+
fig, ax = plt.subplots(figsize=(14, 6.5)); apply_light_style(fig, ax); names, gaps, clrs = [], [], []; ls_c = [COLORS['baseline']] + COLORS['ls_colors']
|
| 323 |
+
for i, (k, l) in enumerate(zip(LS_KEYS, LS_LABELS_EN)): names.append(l); gaps.append(gm(k, 'loss_gap')); clrs.append(ls_c[i])
|
| 324 |
+
for i, (k, l) in enumerate(zip(OP_KEYS, OP_LABELS_EN)): names.append(l); gaps.append(gm(k, 'loss_gap')); clrs.append(COLORS['op_colors'][i])
|
| 325 |
+
bars = ax.bar(range(len(names)), gaps, color=clrs, width=0.65, edgecolor='none', zorder=3)
|
| 326 |
+
for b, v in zip(bars, gaps): ax.text(b.get_x()+b.get_width()/2, v+0.0005, f'{v:.4f}', ha='center', fontsize=10, fontweight='semibold', color=COLORS['text'])
|
| 327 |
+
ax.set_ylabel('Loss Gap', fontsize=12, fontweight='medium'); ax.set_title('Member vs Non-Member Loss Gap', fontsize=14, fontweight='bold', pad=20); ax.set_xticks(range(len(names))); ax.set_xticklabels(names, rotation=30, ha='right', fontsize=10); 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)); plt.tight_layout()
|
| 328 |
+
return fig
|
| 329 |
|
| 330 |
# ================================================================
|
| 331 |
+
# 回调函数
|
| 332 |
# ================================================================
|
| 333 |
def cb_sample(src):
|
| 334 |
+
pool = member_data if "训练集" in src else non_member_data
|
| 335 |
+
s = pool[np.random.randint(len(pool))]
|
| 336 |
+
m = s['metadata']
|
| 337 |
+
md = f"""
|
| 338 |
+
<table style="width:100%; border-collapse: collapse; border: 1px solid #E2E8F0; border-radius: 8px; overflow: hidden;">
|
| 339 |
+
<tr style="background-color: #F9F9F9;">
|
| 340 |
+
<th style="padding: 10px; text-align: left; color: #86868B; font-weight: 600; border-bottom: 1px solid #E2E8F0;">字段</th>
|
| 341 |
+
<th style="padding: 10px; text-align: left; color: #86868B; font-weight: 600; border-bottom: 1px solid #E2E8F0;">值</th>
|
| 342 |
+
</tr>
|
| 343 |
+
<tr><td style="padding: 10px; color: #1D1D1F; border-bottom: 1px solid #E2E8F0;">姓名</td><td style="padding: 10px; color: #1D1D1F; border-bottom: 1px solid #E2E8F0;">{clean_text(str(m.get('name','')))}</td></tr>
|
| 344 |
+
<tr><td style="padding: 10px; color: #1D1D1F; border-bottom: 1px solid #E2E8F0;">学号</td><td style="padding: 10px; color: #1D1D1F; border-bottom: 1px solid #E2E8F0;">{clean_text(str(m.get('student_id','')))}</td></tr>
|
| 345 |
+
<tr><td style="padding: 10px; color: #1D1D1F; border-bottom: 1px solid #E2E8F0;">班级</td><td style="padding: 10px; color: #1D1D1F; border-bottom: 1px solid #E2E8F0;">{clean_text(str(m.get('class','')))}</td></tr>
|
| 346 |
+
<tr><td style="padding: 10px; color: #1D1D1F; border-bottom: 1px solid #E2E8F0;">成绩</td><td style="padding: 10px; color: #1D1D1F; border-bottom: 1px solid #E2E8F0;">{clean_text(str(m.get('score','')))} 分</td></tr>
|
| 347 |
+
<tr><td style="padding: 10px; color: #1D1D1F;">类型</td><td style="padding: 10px; color: #1D1D1F;">{TYPE_CN.get(s.get('task_type',''), '')}</td></tr>
|
| 348 |
+
</table>
|
| 349 |
+
"""
|
| 350 |
+
return md, clean_text(s.get('question', '')), clean_text(s.get('answer', ''))
|
| 351 |
+
|
| 352 |
+
ATK_CHOICES = (
|
| 353 |
+
["基线模型 (Baseline)"] +
|
| 354 |
+
[f"标签平滑 (ε={e})" for e in [0.02, 0.05, 0.1, 0.2]] +
|
| 355 |
+
[f"输出扰动 (σ={s})" for s in OP_SIGMAS]
|
| 356 |
+
)
|
| 357 |
+
ATK_MAP = {"基线模型 (Baseline)": "baseline"}
|
| 358 |
+
for e in [0.02, 0.05, 0.1, 0.2]: ATK_MAP[f"标签平滑 (ε={e})"] = f"smooth_eps_{e}"
|
| 359 |
+
for s in OP_SIGMAS: ATK_MAP[f"输出扰动 (σ={s})"] = f"perturbation_{s}"
|
| 360 |
+
|
| 361 |
+
def cb_attack(idx, src, target):
|
| 362 |
+
is_mem = "训练集" in src
|
| 363 |
+
pool = member_data if is_mem else non_member_data
|
| 364 |
+
idx = min(int(idx), len(pool)-1)
|
| 365 |
+
sample = pool[idx]
|
| 366 |
+
key = ATK_MAP.get(target, "baseline")
|
| 367 |
+
is_op = key.startswith("perturbation_")
|
| 368 |
+
|
| 369 |
+
# 【核心修复1】:强制读取对应参数的方差,让 OP 的背景色块真正“变宽”
|
| 370 |
if is_op:
|
| 371 |
+
sigma = float(key.split("_")[1])
|
| 372 |
+
fr = full_losses.get('baseline', {})
|
| 373 |
+
lk = 'member_losses' if is_mem else 'non_member_losses'
|
| 374 |
+
ll = fr.get(lk, [])
|
| 375 |
+
base_loss = ll[idx] if idx < len(ll) else float(np.random.normal(bl_m_mean if is_mem else bl_nm_mean, 0.02))
|
| 376 |
+
np.random.seed(idx*1000 + int(sigma*10000))
|
| 377 |
+
loss = base_loss + np.random.normal(0, sigma)
|
| 378 |
+
|
| 379 |
+
# 强制读取 perturb_results 中被噪声放大后的 STD,而不是写死 baseline
|
| 380 |
+
mm = gm(key, "member_loss_mean", 0.19)
|
| 381 |
+
nm_m = gm(key, "non_member_loss_mean", 0.20)
|
| 382 |
+
ms = gm(key, "member_loss_std", np.sqrt(0.03**2 + sigma**2))
|
| 383 |
+
ns = gm(key, "non_member_loss_std", np.sqrt(0.03**2 + sigma**2))
|
| 384 |
+
auc_v = gm(key, "auc")
|
| 385 |
+
lbl = f"OP(σ={sigma})"
|
| 386 |
else:
|
| 387 |
+
info = mia_results.get(key, mia_results.get('baseline', {}))
|
| 388 |
+
fr = full_losses.get(key, full_losses.get('baseline', {}))
|
| 389 |
+
lk = 'member_losses' if is_mem else 'non_member_losses'
|
| 390 |
+
ll = fr.get(lk, [])
|
| 391 |
+
loss = ll[idx] if idx < len(ll) else float(np.random.normal(info.get('member_loss_mean',0.19), 0.02))
|
| 392 |
+
mm = info.get('member_loss_mean', 0.19); nm_m = info.get('non_member_loss_mean', 0.20)
|
| 393 |
+
ms = info.get('member_loss_std', 0.03); ns = info.get('non_member_loss_std', 0.03)
|
| 394 |
+
auc_v = info.get('auc', 0)
|
| 395 |
+
lbl = "Baseline" if key == "baseline" else f"LS(ε={key.replace('smooth_eps_','')})"
|
| 396 |
+
|
| 397 |
+
thr = (mm + nm_m) / 2
|
| 398 |
+
pred = loss < thr
|
| 399 |
+
correct = pred == is_mem
|
| 400 |
+
gauge = fig_gauge(loss, mm, nm_m, thr, ms, ns)
|
| 401 |
+
|
| 402 |
+
pl = "🔴 训练成员" if pred else "🟢 非训练成员"
|
| 403 |
+
al = "🔴 训练成员" if is_mem else "🟢 非训练成员"
|
| 404 |
+
|
| 405 |
+
# 【核心修复3】:移除外层多余的换行,让卡片上移紧贴图表
|
| 406 |
if correct and pred and is_mem:
|
| 407 |
+
v = f"<div style='background-color: #FFEBEE; border-left: 4px solid {COLORS['danger']}; padding: 12px; border-radius: 8px; color: {COLORS['danger']}; box-shadow: 0 2px 5px rgba(0,0,0,0.05); margin-top: 0px;'>⚠️ <b>攻击成功:隐私泄露</b><br><span style='font-size: 0.9em; color: #B71C1C;'>模型对该样本过于熟悉(Loss < 阈值),攻击者成功判定为训练数据。</span></div>"
|
| 408 |
elif correct:
|
| 409 |
+
v = f"<div style='background-color: #E8F5E9; border-left: 4px solid {COLORS['success']}; padding: 12px; border-radius: 8px; color: {COLORS['success']}; box-shadow: 0 2px 5px rgba(0,0,0,0.05); margin-top: 0px;'>✅ <b>判定正确</b><br><span style='font-size: 0.9em; color: #1B5E20;'>攻击者判定与真实身份一致。</span></div>"
|
| 410 |
else:
|
| 411 |
+
v = f"<div style='background-color: #E3F2FD; border-left: 4px solid {COLORS['accent']}; padding: 12px; border-radius: 8px; color: {COLORS['accent']}; box-shadow: 0 2px 5px rgba(0,0,0,0.05); margin-top: 0px;'>🛡️ <b>防御成功</b><br><span style='font-size: 0.9em; color: #0D47A1;'>攻击者判定错误,防御起到了保护作用。</span></div>"
|
| 412 |
+
|
| 413 |
+
table_html = f"""
|
| 414 |
+
<table style="width:100%; border-collapse: collapse; margin-top: 10px; border: 1px solid #E2E8F0; border-radius: 8px; overflow: hidden;">
|
| 415 |
+
<thead style="background-color: #F9F9F9;">
|
| 416 |
+
<tr>
|
| 417 |
+
<th style="padding: 10px; text-align: left; color: #86868B; font-weight: 600; border-bottom: 1px solid #E2E8F0;">项目</th>
|
| 418 |
+
<th style="padding: 10px; text-align: left; color: #86868B; font-weight: 600; border-bottom: 1px solid #E2E8F0;">攻击者判定</th>
|
| 419 |
+
<th style="padding: 10px; text-align: left; color: #86868B; font-weight: 600; border-bottom: 1px solid #E2E8F0;">真实身份</th>
|
| 420 |
+
</tr>
|
| 421 |
+
</thead>
|
| 422 |
+
<tbody>
|
| 423 |
+
<tr>
|
| 424 |
+
<td style="padding: 10px; color: #1D1D1F; border-bottom: 1px solid #E2E8F0;">身份</td>
|
| 425 |
+
<td style="padding: 10px; color: #1D1D1F; border-bottom: 1px solid #E2E8F0;">{pl}</td>
|
| 426 |
+
<td style="padding: 10px; color: #1D1D1F; border-bottom: 1px solid #E2E8F0;">{al}</td>
|
| 427 |
+
</tr>
|
| 428 |
+
<tr>
|
| 429 |
+
<td style="padding: 10px; color: #1D1D1F;">Loss / 阈值</td>
|
| 430 |
+
<td style="padding: 10px; color: #1D1D1F;">Loss: {loss:.4f}</td>
|
| 431 |
+
<td style="padding: 10px; color: #1D1D1F;">阈值: {thr:.4f}</td>
|
| 432 |
+
</tr>
|
| 433 |
+
</tbody>
|
| 434 |
+
</table>
|
| 435 |
+
"""
|
| 436 |
+
|
| 437 |
+
# 移除 \n\n 改用 div 控制间距
|
| 438 |
+
res = v + f"<div style='font-weight: 600; margin: 12px 0 8px 0;'>🎯 攻击目标: {lbl} <span style='margin-left: 20px; color: #86868B;'>📊 AUC: {auc_v:.4f}</span></div>" + table_html
|
| 439 |
+
qtxt = f"**样本 #{idx}**\n\n" + clean_text(sample.get('question',''))[:500]
|
| 440 |
+
return qtxt, gauge, res
|
| 441 |
+
|
| 442 |
+
EVAL_CHOICES = (
|
| 443 |
+
["基线模型"] +
|
| 444 |
+
[f"标签平滑 (ε={e})" for e in [0.02, 0.05, 0.1, 0.2]] +
|
| 445 |
+
[f"输出扰动 (σ={s})" for s in OP_SIGMAS]
|
| 446 |
+
)
|
| 447 |
+
EVAL_KEY_MAP = {"基线模型": "baseline"}
|
| 448 |
+
for e in [0.02, 0.05, 0.1, 0.2]: EVAL_KEY_MAP[f"标签平滑 (ε={e})"] = f"smooth_eps_{e}"
|
| 449 |
+
for s in OP_SIGMAS: EVAL_KEY_MAP[f"输出扰动 (σ={s})"] = "baseline"
|
| 450 |
+
|
| 451 |
+
def cb_eval(model_choice):
|
| 452 |
+
k = EVAL_KEY_MAP.get(model_choice, "baseline")
|
| 453 |
+
acc = gu(k) if "输出扰动" not in model_choice else bl_acc
|
| 454 |
+
q = EVAL_POOL[np.random.randint(len(EVAL_POOL))]
|
| 455 |
+
ok = q.get(k, q.get('baseline', False))
|
| 456 |
+
ic = "✅ 正确" if ok else "❌ 错误"
|
| 457 |
+
note = "\n\n> 输出扰动不改变模型参数,准确率与基线一致。" if "输出扰动" in model_choice else ""
|
| 458 |
+
table_html = f"""
|
| 459 |
+
<table style="width:100%; border-collapse: collapse; margin-top: 15px; border: 1px solid #E2E8F0; border-radius: 8px; overflow: hidden;">
|
| 460 |
+
<tbody>
|
| 461 |
+
<tr><td style="padding: 12px; color: #86868B; font-weight: 600; border-bottom: 1px solid #E2E8F0; width: 100px;">类型</td><td style="padding: 12px; color: #1D1D1F; border-bottom: 1px solid #E2E8F0;">{q['type_cn']}</td></tr>
|
| 462 |
+
<tr><td style="padding: 12px; color: #86868B; font-weight: 600; border-bottom: 1px solid #E2E8F0;">题目</td><td style="padding: 12px; color: #1D1D1F; border-bottom: 1px solid #E2E8F0;">{q['question']}</td></tr>
|
| 463 |
+
<tr><td style="padding: 12px; color: #86868B; font-weight: 600; border-bottom: 1px solid #E2E8F0;">正确答案</td><td style="padding: 12px; color: #1D1D1F; border-bottom: 1px solid #E2E8F0;">{q['answer']}</td></tr>
|
| 464 |
+
<tr><td style="padding: 12px; color: #86868B; font-weight: 600;">判定</td><td style="padding: 12px; color: #1D1D1F;">{ic}</td></tr>
|
| 465 |
+
</tbody>
|
| 466 |
+
</table>
|
| 467 |
+
"""
|
| 468 |
+
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)
|
| 469 |
+
|
| 470 |
+
def build_full_table():
|
| 471 |
+
rows = []
|
| 472 |
+
for k, l in zip(LS_KEYS, LS_LABELS_CN):
|
| 473 |
+
if k in mia_results:
|
| 474 |
+
m = mia_results[k]; u = gu(k)
|
| 475 |
+
t = "—" if k == "baseline" else "训练期"; d = "" if k == "baseline" else f"{m['auc']-bl_auc:+.4f}"
|
| 476 |
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} |")
|
| 477 |
+
for k, l in zip(OP_KEYS, OP_LABELS_CN):
|
| 478 |
+
if k in perturb_results:
|
| 479 |
+
m = perturb_results[k]; d = f"{m['auc']-bl_auc:+.4f}"
|
| 480 |
+
rows.append(f"| {l} | 推理期 | {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} | {bl_acc:.1f}% | {d} |")
|
| 481 |
+
header = ("| 策略 | 类型 | AUC | Acc | Prec | Rec | F1 | TPR@5% | TPR@1% | LossGap | 效用 | ΔAUC |\n"
|
| 482 |
+
"|---|---|---|---|---|---|---|---|---|---|---|---|")
|
| 483 |
+
return header + "\n" + "\n".join(rows)
|
| 484 |
|
| 485 |
# ================================================================
|
| 486 |
+
# CSS - 简约苹果风
|
| 487 |
# ================================================================
|
| 488 |
+
CSS = """
|
| 489 |
+
:root {
|
| 490 |
+
--primary-blue: #007AFF;
|
| 491 |
+
--bg-light: #F5F5F7;
|
| 492 |
+
--card-bg: #FFFFFF;
|
| 493 |
+
--text-dark: #1D1D1F;
|
| 494 |
+
--text-gray: #86868B;
|
| 495 |
+
--border-color: #D2D2D7;
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
body {
|
| 499 |
+
background-color: var(--bg-light) !important;
|
| 500 |
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif !important;
|
| 501 |
+
color: var(--text-dark) !important;
|
| 502 |
+
}
|
| 503 |
+
|
| 504 |
+
.gradio-container {
|
| 505 |
+
max-width: 1350px !important;
|
| 506 |
+
margin: 40px auto !important;
|
| 507 |
+
}
|
| 508 |
+
|
| 509 |
+
.title-area {
|
| 510 |
+
background-color: var(--card-bg);
|
| 511 |
+
padding: 32px 40px;
|
| 512 |
+
border-radius: 18px;
|
| 513 |
+
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
|
| 514 |
+
margin-bottom: 30px;
|
| 515 |
+
text-align: center;
|
| 516 |
+
}
|
| 517 |
+
|
| 518 |
+
.title-area h1 {
|
| 519 |
+
color: var(--text-dark) !important;
|
| 520 |
+
font-size: 2.2rem !important;
|
| 521 |
+
font-weight: 700 !important;
|
| 522 |
+
margin-bottom: 10px !important;
|
| 523 |
+
letter-spacing: -0.5px;
|
| 524 |
+
}
|
| 525 |
+
|
| 526 |
+
.title-area p { color: var(--text-gray) !important; font-size: 1.1rem !important; margin-bottom: 15px !important; }
|
| 527 |
+
.title-area .badge { display: inline-block; background-color: #E5F1FF; color: var(--primary-blue); padding: 6px 16px; border-radius: 20px; font-size: 0.9rem; font-weight: 600; }
|
| 528 |
+
.tabitem { background-color: var(--card-bg) !important; border-radius: 18px !important; border: none !important; box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08) !important; padding: 40px !important; margin-top: 20px !important; }
|
| 529 |
+
.tab-nav { border-bottom: none !important; gap: 10px !important; background: transparent !important; padding-bottom: 5px !important; }
|
| 530 |
+
.tab-nav button { font-size: 15px !important; padding: 10px 20px !important; font-weight: 500 !important; color: var(--text-gray) !important; background: rgba(0,0,0,0.03) !important; border: none !important; border-radius: 12px !important; transition: all 0.2s ease !important; }
|
| 531 |
+
.tab-nav button:hover { background: rgba(0,0,0,0.06) !important; color: var(--text-dark) !important; }
|
| 532 |
+
.tab-nav button.selected { color: var(--primary-blue) !important; background: #E5F1FF !important; font-weight: 600 !important; }
|
| 533 |
+
.prose { color: var(--text-dark) !important; }
|
| 534 |
+
.prose h2 { color: var(--text-dark) !important; font-weight: 700 !important; border-bottom: 1px solid var(--border-color) !important; padding-bottom: 12px !important; margin-top: 30px !important; }
|
| 535 |
+
.prose h3 { color: var(--text-dark) !important; font-weight: 600 !important; margin-top: 24px !important; }
|
| 536 |
+
.prose h4 { color: var(--text-gray) !important; font-weight: 600 !important; margin-bottom: 12px !important; }
|
| 537 |
+
.prose table { border-collapse: separate !important; border-spacing: 0 !important; width: 100% !important; border: 1px solid var(--border-color) !important; border-radius: 12px !important; overflow: hidden !important; box-shadow: 0 2px 8px rgba(0,0,0,0.04) !important; }
|
| 538 |
+
.prose th { background: #F9F9F9 !important; color: var(--text-gray) !important; font-weight: 600 !important; padding: 14px 18px !important; text-align: left !important; border-bottom: 1px solid var(--border-color) !important; white-space: nowrap !important; }
|
| 539 |
+
.prose td { padding: 14px 18px !important; color: var(--text-dark) !important; border-bottom: 1px solid var(--border-color) !important; background: var(--card-bg) !important; white-space: nowrap !important; }
|
| 540 |
+
.prose tr:last-child td { border-bottom: none !important; }
|
| 541 |
+
.prose tr:hover td { background: #F5F7FA !important; }
|
| 542 |
+
button.primary { background-color: var(--primary-blue) !important; color: white !important; border: none !important; border-radius: 10px !important; font-weight: 600 !important; padding: 12px 24px !important; box-shadow: 0 2px 6px rgba(0, 122, 255, 0.25) !important; transition: all 0.2s !important; }
|
| 543 |
+
button.primary:hover { background-color: #0062CC !important; box-shadow: 0 4px 10px rgba(0, 122, 255, 0.35) !important; transform: translateY(-1px) !important; }
|
| 544 |
+
.card-wrap { background: var(--card-bg) !important; border: 1px solid var(--border-color) !important; border-radius: 14px !important; padding: 24px !important; box-shadow: 0 2px 8px rgba(0,0,0,0.04) !important; }
|
| 545 |
+
.block.svelte-12cmxck { border-radius: 12px !important; border-color: var(--border-color) !important; }
|
| 546 |
+
.input-label { color: var(--text-gray) !important; font-weight: 500 !important; }
|
| 547 |
+
footer { display: none !important; }
|
| 548 |
"""
|
| 549 |
|
| 550 |
# ================================================================
|
| 551 |
+
# UI 布局
|
| 552 |
# ================================================================
|
| 553 |
+
with gr.Blocks(title="MIA攻防研究", theme=gr.themes.Soft(), css=CSS) as demo:
|
| 554 |
+
|
| 555 |
+
gr.HTML("""<div class="title-area">
|
| 556 |
+
<h1>🎓 教育大模型中的成员推理攻击及其防御研究</h1>
|
| 557 |
+
<p>Membership Inference Attack & Defense on Educational LLM</p>
|
| 558 |
+
<div class="badge">✨ 11组实验 × 8维指标 × 2种策略</div>
|
|
|
|
|
|
|
|
|
|
| 559 |
</div>""")
|
| 560 |
|
| 561 |
+
with gr.Tab("📊 实验总览"):
|
| 562 |
+
gr.Markdown(f"## 📌 研究背景与目标\n\n本研究基于 **{model_name}** 微调的数��辅导模型,系统验证成员推理攻击(MIA)风险并评估两类防御策略。")
|
| 563 |
+
gr.HTML(f"""<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:20px;margin:30px 0;">
|
| 564 |
+
<div class="card-wrap" style="text-align:center;">
|
| 565 |
+
<div style="font-size:32px;font-weight:700;color:{COLORS['accent']};margin-bottom:8px;">5</div>
|
| 566 |
+
<div style="font-size:14px;color:{COLORS['text_dim']};font-weight:600;">训练模型</div>
|
| 567 |
+
<div style="font-size:30px;margin-top:10px;">🤖</div>
|
| 568 |
+
</div>
|
| 569 |
+
<div class="card-wrap" style="text-align:center;">
|
| 570 |
+
<div style="font-size:32px;font-weight:700;color:{COLORS['accent2']};margin-bottom:8px;">6</div>
|
| 571 |
+
<div style="font-size:14px;color:{COLORS['text_dim']};font-weight:600;">扰动配置</div>
|
| 572 |
+
<div style="font-size:30px;margin-top:10px;">🎛️</div>
|
| 573 |
+
</div>
|
| 574 |
+
<div class="card-wrap" style="text-align:center;">
|
| 575 |
+
<div style="font-size:32px;font-weight:700;color:{COLORS['success']};margin-bottom:8px;">8</div>
|
| 576 |
+
<div style="font-size:14px;color:{COLORS['text_dim']};font-weight:600;">评估指标</div>
|
| 577 |
+
<div style="font-size:30px;margin-top:10px;">📈</div>
|
| 578 |
+
</div>
|
| 579 |
+
<div class="card-wrap" style="text-align:center;">
|
| 580 |
+
<div style="font-size:32px;font-weight:700;color:{COLORS['warning']};margin-bottom:8px;">2000</div>
|
| 581 |
+
<div style="font-size:14px;color:{COLORS['text_dim']};font-weight:600;">测试样本</div>
|
| 582 |
+
<div style="font-size:30px;margin-top:10px;">📄</div>
|
| 583 |
+
</div>
|
| 584 |
+
</div>""")
|
| 585 |
+
with gr.Accordion("📋 完整实验结果表(11组 × 8维度)", open=True):
|
| 586 |
+
gr.Markdown(build_full_table())
|
| 587 |
+
|
| 588 |
+
with gr.Tab("📁 数据与模型"):
|
| 589 |
+
gr.HTML("""<div style="display:flex; flex-direction:row; gap:25px; margin-bottom:30px; align-items:stretch;">
|
| 590 |
+
<div class="card-wrap" style="flex:1; display:flex; flex-direction:column;">
|
| 591 |
+
<h3 style="margin:0 0 15px;font-size:18px;color:#1D1D1F;">📦 数据组成</h3>
|
| 592 |
+
<table style="width:100%;border-collapse:collapse;font-size:14px; margin-bottom:auto;">
|
| 593 |
+
<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><th style="padding:12px;text-align:left;color:#86868B;">说明</th></tr>
|
| 594 |
+
<tr><td style="padding:12px;border-bottom:1px solid #E2E8F0;color:#1D1D1F;">🔴 成员数据</td><td style="padding:12px;border-bottom:1px solid #E2E8F0;color:#1D1D1F;">1000条</td><td style="padding:12px;border-bottom:1px solid #E2E8F0;color:#1D1D1F;">模型训练</td><td style="padding:12px;border-bottom:1px solid #E2E8F0;color:#1D1D1F;">Loss偏低</td></tr>
|
| 595 |
+
<tr><td style="padding:12px;border-bottom:1px solid #E2E8F0;color:#1D1D1F;">🟢 非成员数据</td><td style="padding:12px;border-bottom:1px solid #E2E8F0;color:#1D1D1F;">1000条</td><td style="padding:12px;border-bottom:1px solid #E2E8F0;color:#1D1D1F;">攻击对照</td><td style="padding:12px;border-bottom:1px solid #E2E8F0;color:#1D1D1F;">Loss偏高</td></tr>
|
| 596 |
+
</table>
|
| 597 |
+
</div>
|
| 598 |
+
<div class="card-wrap" style="flex:1; display:flex; flex-direction:column;">
|
| 599 |
+
<h3 style="margin:0 0 15px;font-size:18px;color:#1D1D1F;">📚 任务分布</h3>
|
| 600 |
+
<table style="width:100%;border-collapse:collapse;font-size:14px; margin-bottom:auto;">
|
| 601 |
+
<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>
|
| 602 |
+
<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>
|
| 603 |
+
<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>
|
| 604 |
+
<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>
|
| 605 |
+
<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>
|
| 606 |
+
</table>
|
| 607 |
+
</div></div>""")
|
| 608 |
+
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>')
|
| 609 |
+
gr.Markdown("### 🔍 数据样例提取")
|
| 610 |
+
with gr.Row():
|
| 611 |
+
with gr.Column(scale=1):
|
| 612 |
+
gr.Markdown("#### ⚙️ 提取控制台")
|
| 613 |
+
d_src = gr.Radio(["成员数据(训练集)", "非成员数据(测试集)"], value="成员数据(训练集)", label="目标数据源")
|
| 614 |
+
d_btn = gr.Button("🎲 随机提取样本", variant="primary")
|
| 615 |
+
d_meta = gr.HTML()
|
| 616 |
with gr.Column(scale=2):
|
| 617 |
+
gr.Markdown("#### 📄 样本详情")
|
| 618 |
+
d_q = gr.Textbox(label="🧑🎓 学生提问 (Prompt)", lines=6, interactive=False)
|
| 619 |
+
d_a = gr.Textbox(label="💡 标准回答 (Ground Truth)", lines=6, interactive=False)
|
| 620 |
+
d_btn.click(cb_sample, [d_src], [d_meta, d_q, d_a])
|
| 621 |
+
|
| 622 |
+
with gr.Tab("🎯 攻击验证"):
|
| 623 |
+
gr.Markdown("## 🕵️ 成员推理攻击交互演示\n\n配置攻击目标与数据源,系统将执行 Loss 计算并映射判定边界。")
|
| 624 |
+
with gr.Row():
|
| 625 |
+
with gr.Column(scale=1):
|
| 626 |
+
gr.Markdown("#### ⚙️ 攻击配置台")
|
| 627 |
+
a_t = gr.Dropdown(choices=ATK_CHOICES, value=ATK_CHOICES[0], label="🎯 选择被攻击模型", interactive=True)
|
| 628 |
+
a_s = gr.Radio(["成员数据(训练集)", "非成员数据(测试集)"], value="成员数据(训练集)", label="📂 输入数据源")
|
| 629 |
+
a_i = gr.Slider(0, 999, step=1, value=12, label="📌 定位样本 ID")
|
| 630 |
+
a_b = gr.Button("⚡ 执行成员推理攻击", variant="primary")
|
| 631 |
+
a_qt = gr.Markdown()
|
| 632 |
with gr.Column(scale=2):
|
| 633 |
+
gr.Markdown("#### 📉 攻击结果与 Loss 边界")
|
| 634 |
+
a_g = gr.Plot(label="Loss位置判定 (Decision Boundary)")
|
| 635 |
+
a_r = gr.HTML()
|
| 636 |
+
a_b.click(cb_attack, [a_i, a_s, a_t], [a_qt, a_g, a_r])
|
| 637 |
+
|
| 638 |
+
with gr.Tab("🛡️ 防御分析"):
|
| 639 |
+
gr.Markdown("## 🔍 多维度攻防效果对比分析")
|
| 640 |
+
gr.Markdown(f"### 1️⃣ 攻击成功率全景对比 (AUC)\n\n> 柱子越短 = AUC越低 = 防御越有效。基线AUC={bl_auc:.4f},标签平滑最低降至{gm('smooth_eps_0.2','auc'):.4f},输出扰动最低降至{gm('perturbation_0.03','auc'):.4f}。")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 641 |
gr.Plot(value=fig_auc_bar())
|
| 642 |
+
gr.Markdown("### 2️⃣ 多指标雷达图对比\n\n> 红色区域(基线)越大=攻击越强,青/绿色区域(防御)越小=防御越有效。防御后所有维度均有显著缩小。")
|
| 643 |
+
gr.Plot(value=fig_radar_compare())
|
| 644 |
+
gr.Markdown("### 3️⃣ ROC曲线对比\n\n> 曲线越贴近对角线=攻击越接近随机猜测=防御越有效。左图标签平滑,右图输出扰动。")
|
| 645 |
+
gr.Plot(value=fig_roc_curves())
|
| 646 |
+
gr.Markdown(f"### 4️⃣ 低误报率下的攻击能力\n\n> 基线 TPR@5%FPR={gm('baseline','tpr_at_5fpr'):.4f},防御后显著下降。这是衡量攻击危害的最严格指标。")
|
| 647 |
+
gr.Plot(value=fig_tpr_at_low_fpr())
|
| 648 |
+
gr.Markdown("### 5️⃣ Loss差距对比\n\n> Gap越小=成员与非成员越难区分=防御越有效。防御的目标就是缩小这个差距。")
|
| 649 |
+
gr.Plot(value=fig_loss_gap_waterfall())
|
| 650 |
+
gr.Markdown("### 6️⃣ 防御参数与效果关系\n\n> 左图:AUC递减+效用反升=双赢。右图:绿色填充面积=防御收益。")
|
| 651 |
+
gr.Plot(value=fig_auc_trend())
|
| 652 |
+
|
| 653 |
+
with gr.Accordion("📉 Loss分布直方图(标签平滑 5模型)", open=False):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 654 |
gr.Plot(value=fig_loss_dist())
|
| 655 |
+
with gr.Accordion("📉 Loss分布直方图(输出扰动 6组)", open=False):
|
| 656 |
+
gr.Plot(value=fig_perturb_dist())
|
| 657 |
+
with gr.Accordion("📋 完整数据表", open=False):
|
| 658 |
+
gr.Markdown(build_full_table())
|
| 659 |
+
|
| 660 |
+
with gr.Tab("⚖️ 效用评估"):
|
| 661 |
+
gr.Markdown("## 📊 模型效用测试")
|
| 662 |
+
with gr.Row():
|
| 663 |
+
with gr.Column(): gr.Plot(value=fig_acc_bar())
|
| 664 |
with gr.Column(): gr.Plot(value=fig_tradeoff())
|
| 665 |
+
gr.Markdown(f"> 标签平滑实现“双赢”:基线{bl_acc:.1f}% → LS(ε=0.2) {gu('smooth_eps_0.2'):.1f}%。输出扰动始终保持{bl_acc:.1f}%。")
|
| 666 |
+
gr.Markdown("### 🧪 在线抽题演示")
|
| 667 |
+
with gr.Row():
|
| 668 |
with gr.Column(scale=1):
|
| 669 |
+
gr.Markdown("#### ⚙️ 测试配置")
|
| 670 |
+
e_m = gr.Dropdown(choices=EVAL_CHOICES, value="基线模型", label="🤖 选择测试模型", interactive=True)
|
| 671 |
+
e_b = gr.Button("🎲 随机抽题测试", variant="primary")
|
| 672 |
with gr.Column(scale=2):
|
| 673 |
+
gr.Markdown("#### 📝 模型作答结果")
|
| 674 |
+
e_r = gr.HTML()
|
| 675 |
+
e_b.click(cb_eval, [e_m], [e_r])
|
| 676 |
|
| 677 |
+
with gr.Tab("📝 研究结论"):
|
| 678 |
gr.Markdown(f"""\
|
| 679 |
+
## 核心研究发现
|
| 680 |
+
|
| 681 |
+
---
|
| 682 |
|
| 683 |
+
### 一、教育大模型存在可量化的MIA风险
|
| 684 |
+
基线 AUC = **{bl_auc:.4f}**,攻击准确率 **{gm('baseline','attack_accuracy')*100:.1f}%**
|
| 685 |
|
| 686 |
+
### 二、标签平滑防御 (训练期)
|
| 687 |
+
| ε 参数 | AUC | 效用准确率 |
|
| 688 |
|---|---|---|
|
| 689 |
| 0.02 | {gm('smooth_eps_0.02','auc'):.4f} | {gu('smooth_eps_0.02'):.1f}% |
|
| 690 |
| 0.05 | {gm('smooth_eps_0.05','auc'):.4f} | {gu('smooth_eps_0.05'):.1f}% |
|
| 691 |
| 0.1 | {gm('smooth_eps_0.1','auc'):.4f} | {gu('smooth_eps_0.1'):.1f}% |
|
| 692 |
| 0.2 | {gm('smooth_eps_0.2','auc'):.4f} | {gu('smooth_eps_0.2'):.1f}% |
|
| 693 |
|
| 694 |
+
### 三、输出扰动防御 (推理期)
|
| 695 |
+
| σ 参数 | AUC | 效用准确率 |
|
| 696 |
|---|---|---|
|
| 697 |
+
| 0.005 | {gm('perturbation_0.005','auc'):.4f} | {bl_acc:.1f}% |
|
| 698 |
+
| 0.01 | {gm('perturbation_0.01','auc'):.4f} | {bl_acc:.1f}% |
|
| 699 |
+
| 0.015 | {gm('perturbation_0.015','auc'):.4f} | {bl_acc:.1f}% |
|
| 700 |
+
| 0.02 | {gm('perturbation_0.02','auc'):.4f} | {bl_acc:.1f}% |
|
| 701 |
+
| 0.025 | {gm('perturbation_0.025','auc'):.4f} | {bl_acc:.1f}% |
|
| 702 |
+
| 0.03 | {gm('perturbation_0.03','auc'):.4f} | {bl_acc:.1f}% |
|
| 703 |
+
|
| 704 |
+
> **🌟 最佳实践建议: LS(ε=0.1) + OP(σ=0.02)**
|
| 705 |
+
> 结合训练期正则化缩小 Loss Gap,与推理期加噪遮蔽信号,实现隐私与效用的双重保障。
|
| 706 |
""")
|
| 707 |
|
| 708 |
demo.launch()
|