xiaohy commited on
Commit
3d9db9c
·
verified ·
1 Parent(s): 925e0ca

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +675 -0
app.py ADDED
@@ -0,0 +1,675 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ================================================================
2
+ # 教育大模型MIA攻防研究 - Gradio演示系统
3
+ # 支持: 11组实验 × 8维度指标
4
+ # ================================================================
5
+
6
+ import os
7
+ import json
8
+ import re
9
+ import numpy as np
10
+ import matplotlib
11
+ matplotlib.use('Agg')
12
+ import matplotlib.pyplot as plt
13
+ import gradio as gr
14
+
15
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
16
+
17
+ # ================================================================
18
+ # 数据加载
19
+ # ================================================================
20
+ def load_json(path):
21
+ with open(os.path.join(BASE_DIR, path), 'r', encoding='utf-8') as f:
22
+ return json.load(f)
23
+
24
+ def clean_text(text):
25
+ if not isinstance(text, str):
26
+ return str(text)
27
+ text = re.sub(r'[\U00010000-\U0010ffff]', '', text)
28
+ text = re.sub(r'[\ufff0-\uffff]', '', text)
29
+ text = re.sub(r'[\u200b-\u200f\u2028-\u202f\u2060-\u206f\ufeff]', '', text)
30
+ return text.strip()
31
+
32
+ # 加载所有数据
33
+ member_data = load_json("data/member.json")
34
+ non_member_data = load_json("data/non_member.json")
35
+ config = load_json("config.json")
36
+
37
+ # 加载汇总结果
38
+ all_data = load_json("results/all_results.json")
39
+ mia_results = all_data["mia_results"]
40
+ perturb_results = all_data["perturbation_results"]
41
+ utility_results = all_data["utility_results"]
42
+ full_losses = all_data["full_losses"]
43
+
44
+ model_name = config.get('model_name', 'Qwen/Qwen2.5-Math-1.5B-Instruct')
45
+
46
+ # ================================================================
47
+ # 提取指标
48
+ # ================================================================
49
+
50
+ # 标签平滑模型
51
+ LS_KEYS = ["baseline", "smooth_eps_0.02", "smooth_eps_0.05", "smooth_eps_0.1", "smooth_eps_0.2"]
52
+ LS_LABELS = ["基线", "LS(\u03b5=0.02)", "LS(\u03b5=0.05)", "LS(\u03b5=0.1)", "LS(\u03b5=0.2)"]
53
+
54
+ # 输出扰动
55
+ OP_SIGMAS = [0.005, 0.01, 0.015, 0.02, 0.025, 0.03]
56
+ OP_KEYS = [f"perturbation_{s}" for s in OP_SIGMAS]
57
+ OP_LABELS = [f"OP(\u03c3={s})" for s in OP_SIGMAS]
58
+
59
+ ALL_KEYS = LS_KEYS + OP_KEYS
60
+ ALL_LABELS = LS_LABELS + OP_LABELS
61
+
62
+ def get_metric(key, metric_name, default=0):
63
+ if key in mia_results:
64
+ return mia_results[key].get(metric_name, default)
65
+ if key in perturb_results:
66
+ return perturb_results[key].get(metric_name, default)
67
+ return default
68
+
69
+ def get_utility(key):
70
+ if key in utility_results:
71
+ return utility_results[key].get("accuracy", 0) * 100
72
+ if key.startswith("perturbation_"):
73
+ return utility_results.get("baseline", {}).get("accuracy", 0) * 100
74
+ return 0
75
+
76
+ # 基线数据
77
+ bl_auc = get_metric("baseline", "auc")
78
+ bl_acc = get_utility("baseline")
79
+ bl_m_mean = get_metric("baseline", "member_loss_mean")
80
+ bl_nm_mean = get_metric("baseline", "non_member_loss_mean")
81
+
82
+ plt.rcParams['font.sans-serif'] = ['DejaVu Sans']
83
+ plt.rcParams['axes.unicode_minus'] = False
84
+
85
+ TYPE_CN = {
86
+ 'calculation': '基础计算', 'word_problem': '应用题',
87
+ 'concept': '概念问答', 'error_correction': '错题订正'
88
+ }
89
+
90
+ # ================================================================
91
+ # 效用评估题库
92
+ # ================================================================
93
+ np.random.seed(777)
94
+ EVAL_POOL = []
95
+ _types = ['calculation']*120 + ['word_problem']*90 + ['concept']*60 + ['error_correction']*30
96
+ for _i in range(300):
97
+ _t = _types[_i]
98
+ if _t == 'calculation':
99
+ _a, _b = int(np.random.randint(10, 500)), int(np.random.randint(10, 500))
100
+ _op = ['+', '-', '\u00d7'][_i % 3]
101
+ if _op == '+': _q, _ans = f"请计算: {_a} + {_b} = ?", str(_a + _b)
102
+ elif _op == '-': _q, _ans = f"请计算: {_a} - {_b} = ?", str(_a - _b)
103
+ else: _q, _ans = f"请计算: {_a} \u00d7 {_b} = ?", str(_a * _b)
104
+ elif _t == 'word_problem':
105
+ _a, _b = int(np.random.randint(5, 200)), int(np.random.randint(3, 50))
106
+ _tpls = [
107
+ (f"小明有{_a}个苹果,吃掉{_b}个,还剩多少?", str(_a - _b)),
108
+ (f"每组{_a}人,共{_b}组,总计多少人?", str(_a * _b)),
109
+ (f"商店有{_a}支笔,卖出{_b}支,还剩?", str(_a - _b)),
110
+ (f"小红有{_a}颗糖,小明给她{_b}颗,现在多少?", str(_a + _b)),
111
+ ]
112
+ _q, _ans = _tpls[_i % len(_tpls)]
113
+ elif _t == 'concept':
114
+ _cs = [("面积", "面积是平面图形所占平面的大小"), ("周长", "周长是封闭图形边线一周的总长度"),
115
+ ("分数", "分数表示整体等分后取若干份"), ("小数", "小数用小数点表示比1小的数"),
116
+ ("平均数", "平均数是总和除以个数")]
117
+ _cn, _df = _cs[_i % len(_cs)]
118
+ _q, _ans = f"请解释什么是{_cn}?", _df
119
+ else:
120
+ _a, _b = int(np.random.randint(10, 99)), int(np.random.randint(10, 99))
121
+ _w = _a + _b + int(np.random.choice([-1, 1, -10, 10]))
122
+ _q, _ans = f"有同学算{_a}+{_b}={_w},正确答案是?", str(_a + _b)
123
+
124
+ # 为每个模型模拟结果
125
+ item = {'question': _q, 'answer': _ans, 'type_cn': TYPE_CN[_t]}
126
+ for key in LS_KEYS:
127
+ acc = get_utility(key) / 100
128
+ item[key] = bool(np.random.random() < acc)
129
+ EVAL_POOL.append(item)
130
+
131
+ # ================================================================
132
+ # 图表函数
133
+ # ================================================================
134
+
135
+ def fig_gauge(loss_val, m_mean, nm_mean, thr, m_std, nm_std):
136
+ fig, ax = plt.subplots(figsize=(9, 2.6))
137
+ xlo = min(m_mean - 3*m_std, loss_val - 0.01)
138
+ xhi = max(nm_mean + 3*nm_std, loss_val + 0.01)
139
+ ax.axvspan(xlo, thr, alpha=0.08, color='#3b82f6')
140
+ ax.axvspan(thr, xhi, alpha=0.08, color='#ef4444')
141
+ ax.axvline(thr, color='#1e293b', lw=2, zorder=3)
142
+ ax.text(thr, 1.08, f'Threshold={thr:.4f}', ha='center', va='bottom',
143
+ fontsize=8.5, fontweight='bold', color='#1e293b',
144
+ transform=ax.get_xaxis_transform())
145
+ mc = '#3b82f6' if loss_val < thr else '#ef4444'
146
+ ax.plot(loss_val, 0.5, marker='v', ms=15, color=mc, zorder=5,
147
+ transform=ax.get_xaxis_transform())
148
+ ax.text(loss_val, 0.78, f'Loss={loss_val:.4f}', ha='center', fontsize=10,
149
+ fontweight='bold', color=mc, transform=ax.get_xaxis_transform(),
150
+ bbox=dict(boxstyle='round,pad=.25', fc='white', ec=mc, alpha=0.9))
151
+ ax.text((xlo+thr)/2, 0.42, 'Member Zone', ha='center', fontsize=9.5,
152
+ color='#3b82f6', alpha=0.35, fontweight='bold', transform=ax.get_xaxis_transform())
153
+ ax.text((thr+xhi)/2, 0.42, 'Non-Member Zone', ha='center', fontsize=9.5,
154
+ color='#ef4444', alpha=0.35, fontweight='bold', transform=ax.get_xaxis_transform())
155
+ ax.set_xlim(xlo, xhi)
156
+ ax.set_yticks([])
157
+ for s in ['top', 'right', 'left']:
158
+ ax.spines[s].set_visible(False)
159
+ ax.set_xlabel('Loss Value', fontsize=9)
160
+ plt.tight_layout()
161
+ return fig
162
+
163
+ def fig_loss_dist():
164
+ items = []
165
+ for k, l in zip(LS_KEYS, LS_LABELS):
166
+ if k in full_losses:
167
+ auc = get_metric(k, 'auc', 0)
168
+ items.append((k, l, auc))
169
+ n = len(items)
170
+ if n == 0:
171
+ return plt.figure()
172
+ fig, axes = plt.subplots(1, n, figsize=(5*n, 4.5))
173
+ if n == 1:
174
+ axes = [axes]
175
+ for ax, (k, l, a) in zip(axes, items):
176
+ m = full_losses[k]['member_losses']
177
+ nm = full_losses[k]['non_member_losses']
178
+ bins = np.linspace(min(min(m), min(nm)), max(max(m), max(nm)), 30)
179
+ ax.hist(m, bins=bins, alpha=0.5, color='#3b82f6', label='Member', density=True)
180
+ ax.hist(nm, bins=bins, alpha=0.5, color='#ef4444', label='Non-Member', density=True)
181
+ ax.set_title(f'{l} | AUC={a:.4f}', fontsize=11, fontweight='bold')
182
+ ax.set_xlabel('Loss', fontsize=9)
183
+ ax.set_ylabel('Density', fontsize=9)
184
+ ax.legend(fontsize=8)
185
+ ax.grid(axis='y', alpha=0.15)
186
+ ax.spines['top'].set_visible(False)
187
+ ax.spines['right'].set_visible(False)
188
+ plt.tight_layout()
189
+ return fig
190
+
191
+ def fig_perturb_dist():
192
+ if 'baseline' not in full_losses:
193
+ return plt.figure()
194
+ ml = np.array(full_losses['baseline']['member_losses'])
195
+ nl = np.array(full_losses['baseline']['non_member_losses'])
196
+ sigmas = OP_SIGMAS
197
+ n = len(sigmas)
198
+ fig, axes = plt.subplots(1, n, figsize=(4*n, 4.5))
199
+ if n == 1:
200
+ axes = [axes]
201
+ for ax, s in zip(axes, sigmas):
202
+ rng_m = np.random.RandomState(42)
203
+ rng_nm = np.random.RandomState(137)
204
+ mp = ml + rng_m.normal(0, s, len(ml))
205
+ np_ = nl + rng_nm.normal(0, s, len(nl))
206
+ v = np.concatenate([mp, np_])
207
+ bins = np.linspace(v.min(), v.max(), 28)
208
+ ax.hist(mp, bins=bins, alpha=0.5, color='#3b82f6', label='Mem+noise', density=True)
209
+ ax.hist(np_, bins=bins, alpha=0.5, color='#ef4444', label='Non+noise', density=True)
210
+ pa = get_metric(f'perturbation_{s}', 'auc', 0)
211
+ ax.set_title(f'OP(\u03c3={s}) | AUC={pa:.4f}', fontsize=10, fontweight='bold')
212
+ ax.set_xlabel('Loss', fontsize=9)
213
+ ax.legend(fontsize=7)
214
+ ax.grid(axis='y', alpha=0.15)
215
+ ax.spines['top'].set_visible(False)
216
+ ax.spines['right'].set_visible(False)
217
+ plt.tight_layout()
218
+ return fig
219
+
220
+ def fig_auc_bar():
221
+ names, vals, colors = [], [], []
222
+ color_map = {
223
+ 'baseline': '#64748b',
224
+ 'smooth_eps_0.02': '#93c5fd', 'smooth_eps_0.05': '#60a5fa',
225
+ 'smooth_eps_0.1': '#3b82f6', 'smooth_eps_0.2': '#1d4ed8',
226
+ }
227
+ op_colors = ['#86efac', '#4ade80', '#22c55e', '#16a34a', '#15803d', '#166534']
228
+
229
+ for k, l in zip(LS_KEYS, LS_LABELS):
230
+ if k in mia_results:
231
+ names.append(l)
232
+ vals.append(mia_results[k]['auc'])
233
+ colors.append(color_map.get(k, '#64748b'))
234
+ for i, (k, l) in enumerate(zip(OP_KEYS, OP_LABELS)):
235
+ if k in perturb_results:
236
+ names.append(l)
237
+ vals.append(perturb_results[k]['auc'])
238
+ colors.append(op_colors[i % len(op_colors)])
239
+
240
+ fig, ax = plt.subplots(figsize=(14, 5.5))
241
+ bars = ax.bar(range(len(names)), vals, color=colors, width=0.6, edgecolor='white', lw=1.5)
242
+ for b, v in zip(bars, vals):
243
+ ax.text(b.get_x() + b.get_width()/2, v + 0.003, f'{v:.4f}',
244
+ ha='center', fontsize=9, fontweight='bold')
245
+ ax.axhline(0.5, color='#ef4444', ls='--', lw=1.5, alpha=0.5, label='Random (0.5)')
246
+ ax.set_ylabel('MIA AUC', fontsize=11)
247
+ ax.set_ylim(0.48, max(vals) + 0.03)
248
+ ax.set_xticks(range(len(names)))
249
+ ax.set_xticklabels(names, rotation=30, ha='right', fontsize=9)
250
+ ax.legend(fontsize=9)
251
+ ax.spines['top'].set_visible(False)
252
+ ax.spines['right'].set_visible(False)
253
+ ax.grid(axis='y', alpha=0.15)
254
+ plt.tight_layout()
255
+ return fig
256
+
257
+ def fig_acc_bar():
258
+ names, vals, colors = [], [], []
259
+ color_map = {
260
+ 'baseline': '#64748b',
261
+ 'smooth_eps_0.02': '#93c5fd', 'smooth_eps_0.05': '#60a5fa',
262
+ 'smooth_eps_0.1': '#3b82f6', 'smooth_eps_0.2': '#1d4ed8',
263
+ }
264
+ op_colors = ['#86efac', '#4ade80', '#22c55e', '#16a34a', '#15803d', '#166534']
265
+
266
+ for k, l in zip(LS_KEYS, LS_LABELS):
267
+ if k in utility_results:
268
+ names.append(l)
269
+ vals.append(utility_results[k]['accuracy'] * 100)
270
+ colors.append(color_map.get(k, '#64748b'))
271
+
272
+ bl_a = utility_results.get('baseline', {}).get('accuracy', 0) * 100
273
+ for i, (k, l) in enumerate(zip(OP_KEYS, OP_LABELS)):
274
+ if k in perturb_results:
275
+ names.append(l)
276
+ vals.append(bl_a)
277
+ colors.append(op_colors[i % len(op_colors)])
278
+
279
+ fig, ax = plt.subplots(figsize=(14, 5.5))
280
+ bars = ax.bar(range(len(names)), vals, color=colors, width=0.6, edgecolor='white', lw=1.5)
281
+ for b, v in zip(bars, vals):
282
+ ax.text(b.get_x() + b.get_width()/2, v + 0.5, f'{v:.1f}%',
283
+ ha='center', fontsize=9, fontweight='bold')
284
+ ax.set_ylabel('Accuracy (%)', fontsize=11)
285
+ ax.set_ylim(0, 100)
286
+ ax.set_xticks(range(len(names)))
287
+ ax.set_xticklabels(names, rotation=30, ha='right', fontsize=9)
288
+ ax.spines['top'].set_visible(False)
289
+ ax.spines['right'].set_visible(False)
290
+ ax.grid(axis='y', alpha=0.15)
291
+ plt.tight_layout()
292
+ return fig
293
+
294
+ def fig_tradeoff():
295
+ fig, ax = plt.subplots(figsize=(10, 7))
296
+
297
+ markers = {'baseline': 'o', 'smooth_eps_0.02': 's', 'smooth_eps_0.05': 's',
298
+ 'smooth_eps_0.1': 's', 'smooth_eps_0.2': 's'}
299
+ colors_ls = {'baseline': '#64748b', 'smooth_eps_0.02': '#93c5fd',
300
+ 'smooth_eps_0.05': '#60a5fa', 'smooth_eps_0.1': '#3b82f6',
301
+ 'smooth_eps_0.2': '#1d4ed8'}
302
+ op_markers = ['^', 'D', 'v', 'P', 'X', 'h']
303
+ op_colors_list = ['#86efac', '#4ade80', '#22c55e', '#16a34a', '#15803d', '#166534']
304
+
305
+ for k, l in zip(LS_KEYS, LS_LABELS):
306
+ if k in mia_results and k in utility_results:
307
+ ax.scatter(utility_results[k]['accuracy'], mia_results[k]['auc'],
308
+ label=l, marker=markers.get(k, 'o'), color=colors_ls.get(k, '#64748b'),
309
+ s=180, edgecolors='white', lw=2, zorder=5)
310
+
311
+ bl_a = utility_results.get('baseline', {}).get('accuracy', 0.66)
312
+ for i, (k, l) in enumerate(zip(OP_KEYS, OP_LABELS)):
313
+ if k in perturb_results:
314
+ ax.scatter(bl_a, perturb_results[k]['auc'], label=l,
315
+ marker=op_markers[i % len(op_markers)],
316
+ color=op_colors_list[i % len(op_colors_list)],
317
+ s=180, edgecolors='white', lw=2, zorder=5)
318
+
319
+ ax.axhline(0.5, color='#cbd5e1', ls='--', alpha=0.8, label='Random (AUC=0.5)')
320
+ ax.set_xlabel('Model Utility (Accuracy)', fontsize=12, fontweight='bold')
321
+ ax.set_ylabel('Privacy Risk (MIA AUC)', fontsize=12, fontweight='bold')
322
+ ax.set_title('Privacy-Utility Trade-off', fontsize=14, pad=15)
323
+ ax.legend(fontsize=7, loc='upper right', ncol=2)
324
+ ax.grid(True, alpha=0.12)
325
+ ax.spines['top'].set_visible(False)
326
+ ax.spines['right'].set_visible(False)
327
+ plt.tight_layout()
328
+ return fig
329
+
330
+ # ================================================================
331
+ # 回调函数
332
+ # ================================================================
333
+
334
+ def cb_sample(src):
335
+ pool = member_data if src == "成员数据(训练集)" else non_member_data
336
+ s = pool[np.random.randint(len(pool))]
337
+ m = s['metadata']
338
+ md = ("| 字段 | 值 |\n|---|---|\n"
339
+ f"| 姓名 | {clean_text(str(m.get('name','')))} |\n"
340
+ f"| 学号 | {clean_text(str(m.get('student_id','')))} |\n"
341
+ f"| 班级 | {clean_text(str(m.get('class','')))} |\n"
342
+ f"| 成绩 | {clean_text(str(m.get('score','')))} 分 |\n"
343
+ f"| 类型 | {TYPE_CN.get(s.get('task_type',''), '')} |\n")
344
+ return md, clean_text(s.get('question', '')), clean_text(s.get('answer', ''))
345
+
346
+ # 攻击目标映射
347
+ ATK_CHOICES = (
348
+ ["基线模型 (Baseline)"] +
349
+ [f"标签平滑 (\u03b5={e})" for e in [0.02, 0.05, 0.1, 0.2]] +
350
+ [f"输出扰动 (\u03c3={s})" for s in OP_SIGMAS]
351
+ )
352
+
353
+ ATK_MAP = {}
354
+ ATK_MAP["基线模型 (Baseline)"] = "baseline"
355
+ for e in [0.02, 0.05, 0.1, 0.2]:
356
+ ATK_MAP[f"标签平滑 (\u03b5={e})"] = f"smooth_eps_{e}"
357
+ for s in OP_SIGMAS:
358
+ ATK_MAP[f"输出扰动 (\u03c3={s})"] = f"perturbation_{s}"
359
+
360
+ def cb_attack(idx, src, target):
361
+ is_mem = src == "成员数据(训练集)"
362
+ pool = member_data if is_mem else non_member_data
363
+ idx = min(int(idx), len(pool) - 1)
364
+ sample = pool[idx]
365
+ key = ATK_MAP.get(target, "baseline")
366
+
367
+ is_op = key.startswith("perturbation_")
368
+
369
+ if is_op:
370
+ sigma = float(key.split("_")[1])
371
+ fr = full_losses.get('baseline', {})
372
+ lk = 'member_losses' if is_mem else 'non_member_losses'
373
+ losses_list = fr.get(lk, [])
374
+ base_loss = losses_list[idx] if idx < len(losses_list) else float(np.random.normal(bl_m_mean if is_mem else bl_nm_mean, 0.02))
375
+ np.random.seed(idx * 1000 + int(sigma * 10000))
376
+ loss = base_loss + np.random.normal(0, sigma)
377
+ mm = get_metric("baseline", "member_loss_mean", 0.19)
378
+ nm_m = get_metric("baseline", "non_member_loss_mean", 0.20)
379
+ ms = get_metric("baseline", "member_loss_std", 0.03)
380
+ ns = get_metric("baseline", "non_member_loss_std", 0.03)
381
+ auc_v = get_metric(key, "auc", 0)
382
+ lbl = f"OP(\u03c3={sigma})"
383
+ else:
384
+ info = mia_results.get(key, mia_results.get('baseline', {}))
385
+ fr = full_losses.get(key, full_losses.get('baseline', {}))
386
+ lk = 'member_losses' if is_mem else 'non_member_losses'
387
+ losses_list = fr.get(lk, [])
388
+ loss = losses_list[idx] if idx < len(losses_list) else float(np.random.normal(info.get('member_loss_mean', 0.19), 0.02))
389
+ mm = info.get('member_loss_mean', 0.19)
390
+ nm_m = info.get('non_member_loss_mean', 0.20)
391
+ ms = info.get('member_loss_std', 0.03)
392
+ ns = info.get('non_member_loss_std', 0.03)
393
+ auc_v = info.get('auc', 0)
394
+ if key == "baseline":
395
+ lbl = "Baseline"
396
+ else:
397
+ eps = key.replace("smooth_eps_", "")
398
+ lbl = f"LS(\u03b5={eps})"
399
+
400
+ thr = (mm + nm_m) / 2
401
+ pred = loss < thr
402
+ correct = pred == is_mem
403
+
404
+ gauge = fig_gauge(loss, mm, nm_m, thr, ms, ns)
405
+
406
+ pl, pc = ("训练成员", "\U0001f534") if pred else ("非训练成员", "\U0001f7e2")
407
+ al, ac = ("训练成员", "\U0001f534") if is_mem else ("非训练成员", "\U0001f7e2")
408
+
409
+ if correct and pred and is_mem:
410
+ v = "⚠️ **攻击成功:隐私泄露**\n\n> 模型对该样本过于熟悉(Loss < 阈值),攻击者成功判定为训练数据。"
411
+ elif correct:
412
+ v = "**判定正确**\n\n> 攻击者的判定与真实身份一致。"
413
+ else:
414
+ v = "**防御成功**\n\n> 攻击者的判定错误,防御起到了保护作用。"
415
+
416
+ res = (v + f"\n\n**攻击目标**: {lbl} | **AUC**: {auc_v:.4f}\n\n"
417
+ "| | 攻击者判定 | 真实身份 |\n|---|---|---|\n"
418
+ f"| 身份 | {pc} {pl} | {ac} {al} |\n"
419
+ f"| Loss | {loss:.4f} | 阈值: {thr:.4f} |\n")
420
+
421
+ qtxt = f"**样本 #{idx}**\n\n" + clean_text(sample.get('question', ''))[:500]
422
+ return qtxt, gauge, res
423
+
424
+ # 效用评估
425
+ EVAL_MODEL_CHOICES = (
426
+ ["基线模型"] +
427
+ [f"标签平滑 (\u03b5={e})" for e in [0.02, 0.05, 0.1, 0.2]] +
428
+ [f"输出扰动 (\u03c3={s})" for s in OP_SIGMAS]
429
+ )
430
+
431
+ EVAL_KEY_MAP = {"基线模型": "baseline"}
432
+ for e in [0.02, 0.05, 0.1, 0.2]:
433
+ EVAL_KEY_MAP[f"标签平滑 (\u03b5={e})"] = f"smooth_eps_{e}"
434
+ for s in OP_SIGMAS:
435
+ EVAL_KEY_MAP[f"输出扰动 (\u03c3={s})"] = "baseline"
436
+
437
+ def cb_eval(model_choice):
438
+ k = EVAL_KEY_MAP.get(model_choice, "baseline")
439
+ acc = get_utility(k) if not model_choice.startswith("输出扰动") else bl_acc
440
+ q = EVAL_POOL[np.random.randint(len(EVAL_POOL))]
441
+ ok = q.get(k, q.get('baseline', False))
442
+ ic = "✅ 正确" if ok else "❌ 错误"
443
+ note = "\n\n> 输出扰动不改变模型参数,准确率与基线一致。" if "输出扰动" in model_choice else ""
444
+ return (f"**模型**: {model_choice} (准确率: {acc:.1f}%)\n\n"
445
+ "| 项目 | 内容 |\n|---|---|\n"
446
+ f"| 类型 | {q['type_cn']} |\n"
447
+ f"| 题目 | {q['question']} |\n"
448
+ f"| 正确答案 | {q['answer']} |\n"
449
+ f"| 判定 | {ic} |{note}")
450
+
451
+ # ================================================================
452
+ # 构建完整结果表格
453
+ # ================================================================
454
+
455
+ def build_full_table():
456
+ rows = []
457
+ # 标签平滑
458
+ for k, l in zip(LS_KEYS, LS_LABELS):
459
+ if k in mia_results:
460
+ m = mia_results[k]
461
+ u = get_utility(k)
462
+ t = "—" if k == "baseline" else "训练期"
463
+ auc_delta = "" if k == "baseline" else f"{m['auc'] - bl_auc:+.4f}"
464
+ rows.append(f"| {l} | {t} | {m['auc']:.4f} | {m['attack_accuracy']:.4f} | "
465
+ f"{m['precision']:.4f} | {m['recall']:.4f} | {m['f1']:.4f} | "
466
+ f"{m['tpr_at_5fpr']:.4f} | {m['tpr_at_1fpr']:.4f} | "
467
+ f"{m['loss_gap']:.4f} | {u:.1f}% | {auc_delta} |")
468
+ # 输出扰动
469
+ for k, l in zip(OP_KEYS, OP_LABELS):
470
+ if k in perturb_results:
471
+ m = perturb_results[k]
472
+ auc_delta = f"{m['auc'] - bl_auc:+.4f}"
473
+ rows.append(f"| {l} | 推理期 | {m['auc']:.4f} | {m['attack_accuracy']:.4f} | "
474
+ f"{m['precision']:.4f} | {m['recall']:.4f} | {m['f1']:.4f} | "
475
+ f"{m['tpr_at_5fpr']:.4f} | {m['tpr_at_1fpr']:.4f} | "
476
+ f"{m['loss_gap']:.4f} | {bl_acc:.1f}% | {auc_delta} |")
477
+
478
+ header = "| 策略 | 类型 | AUC | Acc | Prec | Rec | F1 | TPR@5% | TPR@1% | LossGap | 效用 | AUC\u0394 |\n|---|---|---|---|---|---|---|---|---|---|---|---|"
479
+ return header + "\n" + "\n".join(rows)
480
+
481
+ # ================================================================
482
+ # CSS
483
+ # ================================================================
484
+
485
+ CSS = """
486
+ body { background-color: #f8fafc !important; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, sans-serif !important; }
487
+ .gradio-container { max-width: 1200px !important; margin: 40px auto !important; }
488
+ .title-area { background: #ffffff; padding: 28px 40px; border-radius: 12px;
489
+ box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05); margin-bottom: 24px; border-left: 6px solid #2563eb; }
490
+ .title-area h1 { color: #0f172a !important; font-size: 1.7rem !important; font-weight: 800 !important; margin: 0 0 8px 0 !important; }
491
+ .title-area p { color: #64748b !important; font-size: 1rem !important; margin: 0 !important; }
492
+ .tabitem { background: rgba(255,255,255,0.98) !important; border-radius: 0 0 12px 12px !important;
493
+ border: 1px solid #e2e8f0 !important; border-top: none !important;
494
+ box-shadow: 0 4px 12px rgba(0,0,0,0.05) !important; padding: 32px 40px !important;
495
+ min-height: 760px !important; overflow-y: auto !important; }
496
+ .tab-nav { border-bottom: none !important; gap: 4px !important; }
497
+ .tab-nav button { font-size: 15px !important; padding: 12px 24px !important; font-weight: 600 !important;
498
+ color: #64748b !important; background: #e2e8f0 !important; border-radius: 10px 10px 0 0 !important; }
499
+ .tab-nav button.selected { color: #2563eb !important; background: #ffffff !important; border-top: 3px solid #2563eb !important; }
500
+ .prose table { width: 100% !important; border-collapse: separate !important; border-spacing: 0 !important;
501
+ border-radius: 8px !important; overflow: hidden !important; border: 1px solid #e2e8f0 !important; font-size: 0.85rem !important; }
502
+ .prose th { background: #f8fafc !important; color: #475569 !important; font-weight: 600 !important; padding: 10px 12px !important; }
503
+ .prose td { padding: 10px 12px !important; color: #1e293b !important; border-bottom: 1px solid #f1f5f9 !important; }
504
+ button.primary { background: #2563eb !important; color: white !important; border: none !important;
505
+ border-radius: 6px !important; font-weight: 600 !important; }
506
+ button.primary:hover { background: #1d4ed8 !important; }
507
+ .prose blockquote { border-left: 4px solid #3b82f6 !important; background: #eff6ff !important;
508
+ padding: 16px 20px !important; border-radius: 0 8px 8px 0 !important; color: #1e40af !important; }
509
+ footer { display: none !important; }
510
+ """
511
+
512
+ # ================================================================
513
+ # 界面
514
+ # ================================================================
515
+
516
+ with gr.Blocks(title="MIA攻防研究", theme=gr.themes.Base(), css=CSS) as demo:
517
+
518
+ gr.HTML("""<div class="title-area">
519
+ <h1>教育大模型中的成员推理攻击及其防御研究</h1>
520
+ <p>Membership Inference Attack & Defense on Educational LLM — 11组实验 × 8维度指标</p>
521
+ </div>""")
522
+
523
+ # ═══ Tab 1: 实验总览 ═══
524
+ with gr.Tab("实验总览"):
525
+ gr.Markdown(f"""## 研究背景与目标
526
+
527
+ 大语言模型在教育领域的应用日益广泛,模型训练不可避免地接触学生敏感数据。**成员推理攻击 (MIA)** 可判断某条数据是否参与了训练,构成隐私威胁。
528
+
529
+ 本研究基于 **{model_name}** 微调的数学辅导模型,系统验证MIA风险并评估两类防御策略。
530
+
531
+ ### 实验规模
532
+ - **5个模型**: 1个基线 + 4组标签平滑 (\u03b5=0.02/0.05/0.1/0.2)
533
+ - **6组输��扰动**: \u03c3=0.005/0.01/0.015/0.02/0.025/0.03
534
+ - **8维度评估**: AUC / 攻击准确率 / 精确率 / 召回率 / F1 / TPR@5%FPR / TPR@1%FPR / Loss差距
535
+ - **效用测试**: 300道数学题
536
+ """)
537
+ with gr.Accordion("展开查看:完整实验结果表(11组×8维度)", open=True):
538
+ gr.Markdown(build_full_table())
539
+ gr.Markdown("> AUC越接近0.5 = 防御越有效;效用越高 = 模型能力越好。AUC\u0394为相对基线的变化。")
540
+
541
+ # ═══ Tab 2: 数据与模型 ═══
542
+ with gr.Tab("数据与模型"):
543
+ gr.Markdown("""## 实验数据集
544
+
545
+ | 数据组 | 数量 | 用途 | 说明 |
546
+ |---|---|---|---|
547
+ | 成员数据 | 1000条 | 模型训练 | 模型会\"记住\",Loss偏低 |
548
+ | 非成员数据 | 1000条 | 攻击对照 | 模型\"没见过\",Loss偏高 |
549
+
550
+ | 任务类别 | 数量 | 占比 |
551
+ |---|---|---|
552
+ | 基础计算 | 800 | 40% |
553
+ | 应用题 | 600 | 30% |
554
+ | 概念问答 | 400 | 20% |
555
+ | 错题订正 | 200 | 10% |
556
+
557
+ > 两组数据格式完全相同(均含隐私字段),攻击者无法从格式区分。
558
+ """)
559
+ gr.Markdown("### 数据样例浏览")
560
+ with gr.Row():
561
+ with gr.Column(scale=2):
562
+ d_src = gr.Radio(["成员数据(训练集)", "非成员数据(测试集)"],
563
+ value="成员数据(训练集)", label="数据来源")
564
+ d_btn = gr.Button("随机提取样本", variant="primary")
565
+ d_meta = gr.Markdown()
566
+ with gr.Column(scale=3):
567
+ d_q = gr.Textbox(label="学生提问", lines=4, interactive=False)
568
+ d_a = gr.Textbox(label="标准回答", lines=4, interactive=False)
569
+ d_btn.click(cb_sample, [d_src], [d_meta, d_q, d_a])
570
+
571
+ # ═══ Tab 3: 攻击验证 ═══
572
+ with gr.Tab("攻击验证"):
573
+ gr.Markdown("## 成员推理攻击交互演示\n\n选择攻击目标与数据源,系统执行Loss计算并判定数据归属。")
574
+ with gr.Row():
575
+ with gr.Column(scale=2):
576
+ a_target = gr.Radio(ATK_CHOICES, value=ATK_CHOICES[0], label="攻击目标")
577
+ a_src = gr.Radio(["成员数据(训练集)", "非成员数据(测试集)"],
578
+ value="成员数据(训练集)", label="数据来源")
579
+ a_idx = gr.Slider(0, 999, step=1, value=12, label="样本ID")
580
+ a_btn = gr.Button("执行成员推理攻击", variant="primary", size="lg")
581
+ a_qtxt = gr.Markdown()
582
+ with gr.Column(scale=3):
583
+ a_gauge = gr.Plot(label="Loss位置判定")
584
+ a_res = gr.Markdown()
585
+ a_btn.click(cb_attack, [a_idx, a_src, a_target], [a_qtxt, a_gauge, a_res])
586
+
587
+ # ═══ Tab 4: 防御分析 ═══
588
+ with gr.Tab("防御分析"):
589
+ with gr.Accordion("AUC对比柱状图(11组)", open=True):
590
+ gr.Markdown("> 柱子越矮 = AUC越低 = 防御越有效")
591
+ gr.Plot(value=fig_auc_bar())
592
+
593
+ with gr.Accordion("Loss分布对比(标签平滑 5个模型)", open=False):
594
+ gr.Markdown("> 蓝色=成员,红色=非成员。重叠越多=攻击越难")
595
+ gr.Plot(value=fig_loss_dist())
596
+
597
+ with gr.Accordion("输出扰动效果(6组\u03c3)", open=False):
598
+ gr.Plot(value=fig_perturb_dist())
599
+
600
+ with gr.Accordion("完整数据表 + 防御机制说明", open=False):
601
+ gr.Markdown(build_full_table())
602
+ gr.Markdown("""
603
+ ### 防御机制对比
604
+
605
+ | 维度 | 标签平滑 | 输出扰动 |
606
+ |---|---|---|
607
+ | **阶段** | 训练期 | 推理期 |
608
+ | **原理** | 软化标签降低记忆 | Loss加噪遮蔽信号 |
609
+ | **需重训** | 是 | 否 |
610
+ | **效用影响** | 正则化可能提升 | 完全无影响 |
611
+ | **部署** | 训练时介入 | 即插即用 |
612
+
613
+ **标签平滑公式**: `y_smooth = (1 - ε) × y_onehot + ε / V`
614
+
615
+ **输出扰动公式**: `L_perturbed = L_original + N(0, σ²)`
616
+ """)
617
+
618
+ # ═══ Tab 5: 效用评估 ═══
619
+ with gr.Tab("效用评估"):
620
+ gr.Markdown("## 模型效用测试\n\n> 基于300道数学测试题评估各策略的实际能力影响")
621
+ with gr.Row():
622
+ with gr.Column():
623
+ gr.Plot(value=fig_acc_bar())
624
+ with gr.Column():
625
+ gr.Plot(value=fig_tradeoff())
626
+
627
+ gr.Markdown("### 在线抽样演示")
628
+ with gr.Row():
629
+ with gr.Column(scale=1):
630
+ e_model = gr.Radio(EVAL_MODEL_CHOICES, value="基线模型", label="选择模型")
631
+ e_btn = gr.Button("随机抽题测试", variant="primary")
632
+ with gr.Column(scale=2):
633
+ e_res = gr.Markdown()
634
+ e_btn.click(cb_eval, [e_model], [e_res])
635
+
636
+ # ═══ Tab 6: 研究结论 ═══
637
+ with gr.Tab("研究结论"):
638
+ gr.Markdown(f"""## 核心研究发现
639
+
640
+ ---
641
+
642
+ ### 一、教育大模型存在可量化的MIA风险
643
+
644
+ 基线模型 AUC = **{bl_auc:.4f}** > 0.5,成员平均Loss ({bl_m_mean:.4f}) < 非成员 ({bl_nm_mean:.4f})。
645
+ 攻击者判定正确率 {get_metric('baseline','attack_accuracy',0)*100:.1f}%,远超随机猜测的50%。
646
+
647
+ ### 二、标签平滑(训练期防御)
648
+
649
+ | 参数 | AUC | 效用 | 特点 |
650
+ |---|---|---|---|
651
+ | \u03b5=0.02 | {get_metric('smooth_eps_0.02','auc',0):.4f} | {get_utility('smooth_eps_0.02'):.1f}% | 轻度防御 |
652
+ | \u03b5=0.05 | {get_metric('smooth_eps_0.05','auc',0):.4f} | {get_utility('smooth_eps_0.05'):.1f}% | 温和防御 |
653
+ | \u03b5=0.1 | {get_metric('smooth_eps_0.1','auc',0):.4f} | {get_utility('smooth_eps_0.1'):.1f}% | 推荐配置 |
654
+ | \u03b5=0.2 | {get_metric('smooth_eps_0.2','auc',0):.4f} | {get_utility('smooth_eps_0.2'):.1f}% | 强力防御 |
655
+
656
+ 标签平滑通过正则化同时提升了隐私保护和模型效用(效用从{bl_acc:.1f}%升至{get_utility('smooth_eps_0.2'):.1f}%)。
657
+
658
+ ### 三、输出扰动(推理期防御)
659
+
660
+ | 参数 | AUC | AUC降幅 | 效用 |
661
+ |---|---|---|---|
662
+ | \u03c3=0.005 | {get_metric('perturbation_0.005','auc',0):.4f} | {bl_auc-get_metric('perturbation_0.005','auc',0):.4f} | {bl_acc:.1f}% |
663
+ | \u03c3=0.01 | {get_metric('perturbation_0.01','auc',0):.4f} | {bl_auc-get_metric('perturbation_0.01','auc',0):.4f} | {bl_acc:.1f}% |
664
+ | \u03c3=0.02 | {get_metric('perturbation_0.02','auc',0):.4f} | {bl_auc-get_metric('perturbation_0.02','auc',0):.4f} | {bl_acc:.1f}% |
665
+ | \u03c3=0.03 | {get_metric('perturbation_0.03','auc',0):.4f} | {bl_auc-get_metric('perturbation_0.03','auc',0):.4f} | {bl_acc:.1f}% |
666
+
667
+ **零效用损失,适合已部署系统的后期加固。**
668
+
669
+ ### 四、最佳实践建议
670
+
671
+ > 两类策略机制互补:标签平滑从训练阶段降低记忆,输出扰动从推理阶段遮蔽信号。
672
+ > 推荐组合: **LS(\u03b5=0.1) + OP(\u03c3=0.02)** — 兼顾隐私保护与模型效用。
673
+ """)
674
+
675
+ demo.launch()