xiaohy commited on
Commit
338f9f3
·
verified ·
1 Parent(s): 2f9692c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +277 -343
app.py CHANGED
@@ -65,13 +65,58 @@ MODEL_PARAMS = {
65
  "smooth_0.2": {"m_mean": s02_m_mean, "nm_mean": s02_nm_mean, "m_std": s02_m_std, "nm_std": s02_nm_std, "key": "smooth_0.2", "label": "LS(e=0.2)"},
66
  }
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
  # ========================================
70
  # Charts
71
  # ========================================
72
 
73
  def make_loss_distribution():
74
- """3 model Loss distributions - larger size"""
75
  items = []
76
  for k, t in [('baseline', 'Baseline'), ('smooth_0.02', 'LS(e=0.02)'), ('smooth_0.2', 'LS(e=0.2)')]:
77
  if k in full_results:
@@ -79,189 +124,126 @@ def make_loss_distribution():
79
  items.append((k, t + "\nAUC=" + f"{auc:.4f}"))
80
  n = len(items)
81
  if n == 0:
82
- fig, ax = plt.subplots()
83
- ax.text(0.5, 0.5, 'No data', ha='center')
84
- return fig
85
- fig, axes = plt.subplots(1, n, figsize=(6 * n, 5.5))
86
- if n == 1:
87
- axes = [axes]
88
  for ax, (k, title) in zip(axes, items):
89
- m = full_results[k]['member_losses']
90
- nm_l = full_results[k]['non_member_losses']
91
  bins = np.linspace(min(min(m), min(nm_l)), max(max(m), max(nm_l)), 30)
92
  ax.hist(m, bins=bins, alpha=0.55, color='#5B8FF9', label='Member', density=True)
93
  ax.hist(nm_l, bins=bins, alpha=0.55, color='#E86452', label='Non-Member', density=True)
94
  ax.set_title(title, fontsize=13, fontweight='bold')
95
- ax.set_xlabel('Loss', fontsize=11)
96
- ax.set_ylabel('Density', fontsize=11)
97
- ax.legend(fontsize=10, loc='upper right')
98
- ax.tick_params(labelsize=10)
99
  ax.grid(True, linestyle='--', alpha=0.3)
100
- ax.spines['top'].set_visible(False)
101
- ax.spines['right'].set_visible(False)
102
- plt.suptitle('Model Loss Distribution: Member vs Non-Member', fontsize=15, fontweight='bold', y=1.02)
103
  plt.tight_layout()
104
  return fig
105
 
106
 
107
  def make_perturb_loss_distribution():
108
- """Output perturbation effect on baseline loss distribution"""
109
  bl = full_results.get('baseline', {})
110
  if not bl:
111
- fig, ax = plt.subplots()
112
- ax.text(0.5, 0.5, 'No data', ha='center')
113
- return fig
114
- m_losses = np.array(bl['member_losses'])
115
- nm_losses = np.array(bl['non_member_losses'])
116
- sigmas = [0.01, 0.015, 0.02]
117
- fig, axes = plt.subplots(1, 3, figsize=(18, 5.5))
118
- for ax, sigma in zip(axes, sigmas):
119
  np.random.seed(42)
120
  m_pert = m_losses + np.random.normal(0, sigma, len(m_losses))
 
121
  nm_pert = nm_losses + np.random.normal(0, sigma, len(nm_losses))
122
- all_vals = np.concatenate([m_pert, nm_pert])
123
- bins = np.linspace(all_vals.min(), all_vals.max(), 30)
124
- ax.hist(m_pert, bins=bins, alpha=0.55, color='#5B8FF9', label='Member (perturbed)', density=True)
125
- ax.hist(nm_pert, bins=bins, alpha=0.55, color='#E86452', label='Non-Member (perturbed)', density=True)
126
  pk = 'perturbation_' + str(sigma)
127
  pauc = perturb_results.get(pk, {}).get('auc', 0)
128
  ax.set_title(f'OP(s={sigma})\nAUC={pauc:.4f}', fontsize=13, fontweight='bold')
129
- ax.set_xlabel('Loss', fontsize=11)
130
- ax.set_ylabel('Density', fontsize=11)
131
- ax.legend(fontsize=9, loc='upper right')
132
- ax.tick_params(labelsize=10)
133
  ax.grid(True, linestyle='--', alpha=0.3)
134
- ax.spines['top'].set_visible(False)
135
- ax.spines['right'].set_visible(False)
136
- plt.suptitle('Output Perturbation: Loss Distribution After Adding Noise', fontsize=15, fontweight='bold', y=1.02)
137
  plt.tight_layout()
138
  return fig
139
 
140
 
141
  def make_auc_bar():
142
  methods, aucs, colors = [], [], []
143
- for k, name, c in [('baseline', 'Baseline', '#8C8C8C'), ('smooth_0.02', 'LS(e=0.02)', '#5B8FF9'),
144
- ('smooth_0.2', 'LS(e=0.2)', '#3D76DD')]:
145
- if k in mia_results:
146
- methods.append(name); aucs.append(mia_results[k]['auc']); colors.append(c)
147
- for k, name, c in [('perturbation_0.01', 'OP(s=0.01)', '#5AD8A6'),
148
- ('perturbation_0.015', 'OP(s=0.015)', '#2EAD78'),
149
- ('perturbation_0.02', 'OP(s=0.02)', '#1A7F5A')]:
150
- if k in perturb_results:
151
- methods.append(name); aucs.append(perturb_results[k]['auc']); colors.append(c)
152
  fig, ax = plt.subplots(figsize=(12, 6))
153
  bars = ax.bar(methods, aucs, color=colors, width=0.5, edgecolor='white', linewidth=1.5)
154
  for bar, a in zip(bars, aucs):
155
- ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.002,
156
- f'{a:.4f}', ha='center', va='bottom', fontsize=11, fontweight='bold')
157
  ax.axhline(y=0.5, color='#E86452', linestyle='--', linewidth=1.5, alpha=0.6, label='Random Guess (0.5)')
158
- ax.set_ylabel('MIA AUC', fontsize=12)
159
- ax.set_ylim(0.48, max(aucs) + 0.035 if aucs else 0.7)
160
- ax.legend(fontsize=10)
161
- ax.grid(axis='y', linestyle='--', alpha=0.3)
162
- ax.spines['top'].set_visible(False)
163
- ax.spines['right'].set_visible(False)
164
- plt.xticks(fontsize=11)
165
- plt.tight_layout()
166
  return fig
167
 
168
 
169
  def make_tradeoff():
170
  fig, ax = plt.subplots(figsize=(10, 7))
171
  pts = []
172
- for k, name, mk, c, sz in [('baseline', 'Baseline', 'o', '#8C8C8C', 220),
173
- ('smooth_0.02', 'LS(e=0.02)', 's', '#5B8FF9', 200),
174
- ('smooth_0.2', 'LS(e=0.2)', 's', '#3D76DD', 200)]:
175
  if k in mia_results and k in utility_results:
176
- pts.append({'n': name, 'a': mia_results[k]['auc'], 'c': utility_results[k]['accuracy'],
177
- 'm': mk, 'co': c, 's': sz})
178
- ba = utility_results.get('baseline', {}).get('accuracy', 0.633)
179
- for k, name, mk, c, sz in [('perturbation_0.01', 'OP(s=0.01)', '^', '#5AD8A6', 200),
180
- ('perturbation_0.015', 'OP(s=0.015)', 'D', '#2EAD78', 160),
181
- ('perturbation_0.02', 'OP(s=0.02)', '^', '#1A7F5A', 200)]:
182
- if k in perturb_results:
183
- pts.append({'n': name, 'a': perturb_results[k]['auc'], 'c': ba, 'm': mk, 'co': c, 's': sz})
184
  for p in pts:
185
- ax.scatter(p['c'], p['a'], label=p['n'], marker=p['m'], color=p['co'],
186
- s=p['s'], edgecolors='white', linewidth=2, zorder=5)
187
  ax.axhline(y=0.5, color='#BFBFBF', linestyle='--', alpha=0.8, label='Random Guess')
188
- ax.set_xlabel('Accuracy', fontsize=12, fontweight='bold')
189
- ax.set_ylabel('MIA AUC (Privacy Risk)', fontsize=12, fontweight='bold')
190
  ax.set_title('Privacy-Utility Trade-off', fontsize=14, fontweight='bold')
191
- aa = [p['c'] for p in pts]; ab = [p['a'] for p in pts]
192
- if aa and ab:
193
- ax.set_xlim(min(aa)-0.03, max(aa)+0.05)
194
- ax.set_ylim(min(min(ab), 0.5)-0.02, max(ab)+0.025)
195
- ax.legend(loc='upper right', fontsize=9, fancybox=True)
196
- ax.grid(True, alpha=0.2)
197
- ax.spines['top'].set_visible(False)
198
- ax.spines['right'].set_visible(False)
199
- plt.tight_layout()
200
- return fig
201
 
202
 
203
  def make_accuracy_bar():
204
  names, accs, colors = [], [], []
205
- for k, name, c in [('baseline', 'Baseline', '#8C8C8C'), ('smooth_0.02', 'LS(e=0.02)', '#5B8FF9'),
206
- ('smooth_0.2', 'LS(e=0.2)', '#3D76DD')]:
207
- if k in utility_results:
208
- names.append(name); accs.append(utility_results[k]['accuracy']*100); colors.append(c)
209
- bp = utility_results.get('baseline', {}).get('accuracy', 0)*100
210
- for k, name, c in [('perturbation_0.01', 'OP(s=0.01)', '#5AD8A6'),
211
- ('perturbation_0.015', 'OP(s=0.015)', '#2EAD78'),
212
- ('perturbation_0.02', 'OP(s=0.02)', '#1A7F5A')]:
213
- if k in perturb_results:
214
- names.append(name); accs.append(bp); colors.append(c)
215
  fig, ax = plt.subplots(figsize=(12, 6))
216
  bars = ax.bar(names, accs, color=colors, width=0.5, edgecolor='white', linewidth=1.5)
217
  for bar, acc in zip(bars, accs):
218
- ax.text(bar.get_x()+bar.get_width()/2, bar.get_height()+0.5,
219
- f'{acc:.1f}%', ha='center', va='bottom', fontsize=11, fontweight='bold')
220
- ax.set_ylabel('Accuracy (%)', fontsize=12)
221
- ax.set_ylim(0, 100)
222
- ax.grid(axis='y', alpha=0.3)
223
- ax.spines['top'].set_visible(False)
224
- ax.spines['right'].set_visible(False)
225
- plt.xticks(fontsize=11)
226
- plt.tight_layout()
227
- return fig
228
 
229
 
230
  def make_loss_gauge(loss_val, m_mean, nm_mean, threshold, m_std, nm_std):
231
  fig, ax = plt.subplots(figsize=(9, 3))
232
- x_min = min(m_mean - 3*m_std, loss_val - 0.01)
233
- x_max = max(nm_mean + 3*nm_std, loss_val + 0.01)
234
  ax.axvspan(x_min, threshold, alpha=0.12, color='#5B8FF9')
235
  ax.axvspan(threshold, x_max, alpha=0.12, color='#E86452')
236
- ax.axvline(x=threshold, color='#434343', linewidth=2, linestyle='-', zorder=3)
237
- ax.text(threshold, 1.12, 'Threshold', ha='center', va='bottom', fontsize=10,
238
- fontweight='bold', color='#434343', transform=ax.get_xaxis_transform())
239
  ax.axvline(x=m_mean, color='#5B8FF9', linewidth=1.2, linestyle='--', alpha=0.6)
240
- ax.text(m_mean, -0.3, f'Member\n({m_mean:.4f})', ha='center', va='top',
241
- fontsize=8, color='#5B8FF9', transform=ax.get_xaxis_transform())
242
  ax.axvline(x=nm_mean, color='#E86452', linewidth=1.2, linestyle='--', alpha=0.6)
243
- ax.text(nm_mean, -0.3, f'Non-Member\n({nm_mean:.4f})', ha='center', va='top',
244
- fontsize=8, color='#E86452', transform=ax.get_xaxis_transform())
245
- in_member = loss_val < threshold
246
- mc = '#5B8FF9' if in_member else '#E86452'
247
- ax.plot(loss_val, 0.5, marker='v', markersize=16, color=mc, zorder=5,
248
- transform=ax.get_xaxis_transform())
249
- ax.text(loss_val, 0.78, f'Loss={loss_val:.4f}', ha='center', va='bottom', fontsize=11,
250
- fontweight='bold', color=mc, transform=ax.get_xaxis_transform(),
251
  bbox=dict(boxstyle='round,pad=0.3', facecolor='white', edgecolor=mc, alpha=0.95))
252
- mc_x = (x_min + threshold) / 2
253
- nmc_x = (threshold + x_max) / 2
254
- ax.text(mc_x, 0.5, 'Member Zone', ha='center', va='center', fontsize=11,
255
- color='#5B8FF9', fontweight='bold', alpha=0.5, transform=ax.get_xaxis_transform())
256
- ax.text(nmc_x, 0.5, 'Non-Member Zone', ha='center', va='center', fontsize=11,
257
- color='#E86452', fontweight='bold', alpha=0.5, transform=ax.get_xaxis_transform())
258
- ax.set_xlim(x_min, x_max)
259
- ax.set_yticks([])
260
- for sp in ['top', 'right', 'left']:
261
- ax.spines[sp].set_visible(False)
262
- ax.set_xlabel('Loss Value', fontsize=10)
263
- plt.tight_layout()
264
- return fig
265
 
266
 
267
  # ========================================
@@ -272,16 +254,14 @@ def show_random_sample(data_type):
272
  data = member_data if data_type == "成员数据(训练集)" else non_member_data
273
  sample = data[np.random.randint(0, len(data))]
274
  meta = sample['metadata']
275
- task_map = {'calculation': '基础计算', 'word_problem': '应用题',
276
- 'concept': '概念问答', 'error_correction': '错题订正'}
277
- info_md = (
278
- "**截获的隐私元数据**\n\n"
279
- "- **姓名**: " + clean_text(str(meta.get('name', ''))) + "\n"
280
- "- **学号**: " + clean_text(str(meta.get('student_id', ''))) + "\n"
281
- "- **班级**: " + clean_text(str(meta.get('class', ''))) + "\n"
282
- "- **成绩**: " + clean_text(str(meta.get('score', ''))) + " 分\n"
283
- "- **类型**: " + task_map.get(sample.get('task_type', ''), '') + "\n")
284
- return info_md, clean_text(sample.get('question', '')), clean_text(sample.get('answer', ''))
285
 
286
 
287
  MODEL_CHOICE_MAP = {
@@ -295,99 +275,114 @@ MODEL_CHOICE_MAP = {
295
 
296
 
297
  def run_mia_demo(sample_index, data_type, model_choice):
298
- is_member = (data_type == "成员数据��训练集)")
299
  data = member_data if is_member else non_member_data
300
- idx = min(int(sample_index), len(data) - 1)
301
  sample = data[idx]
302
-
303
  model_key = MODEL_CHOICE_MAP.get(model_choice, "baseline")
304
-
305
- # Determine which Loss data to use
306
  is_perturb = model_key.startswith("perturbation_")
 
307
  if is_perturb:
308
- # Output perturbation: baseline loss + noise
309
  sigma = float(model_key.split("_")[1])
310
  base_fr = full_results.get('baseline', {})
311
- if is_member and idx < len(base_fr.get('member_losses', [])):
312
- base_loss = base_fr['member_losses'][idx]
313
- elif not is_member and idx < len(base_fr.get('non_member_losses', [])):
314
- base_loss = base_fr['non_member_losses'][idx]
315
  else:
316
  base_loss = float(np.random.normal(bl_m_mean if is_member else bl_nm_mean, 0.02))
317
  np.random.seed(idx * 1000 + int(sigma * 1000))
318
  loss = base_loss + np.random.normal(0, sigma)
319
- m_mean = bl_m_mean
320
- nm_mean = bl_nm_mean
321
- m_std_v = bl_m_std
322
- nm_std_v = bl_nm_std
323
  model_auc = perturb_results.get(model_key, {}).get('auc', 0)
324
  display_label = "OP(s=" + str(sigma) + ")"
325
  else:
326
  params = MODEL_PARAMS.get(model_key, MODEL_PARAMS["baseline"])
327
  fr = full_results.get(model_key, full_results.get('baseline', {}))
328
- if is_member and idx < len(fr.get('member_losses', [])):
329
- loss = fr['member_losses'][idx]
330
- elif not is_member and idx < len(fr.get('non_member_losses', [])):
331
- loss = fr['non_member_losses'][idx]
332
  else:
333
  loss = float(np.random.normal(params['m_mean'] if is_member else params['nm_mean'], 0.02))
334
- m_mean = params['m_mean']
335
- nm_mean = params['nm_mean']
336
- m_std_v = params['m_std']
337
- nm_std_v = params['nm_std']
338
  model_auc = mia_results.get(model_key, {}).get('auc', 0)
339
  display_label = params['label']
340
 
341
  threshold = (m_mean + nm_mean) / 2.0
342
  pred_member = (loss < threshold)
343
  attack_correct = (pred_member == is_member)
344
-
345
  gauge_fig = make_loss_gauge(loss, m_mean, nm_mean, threshold, m_std_v, nm_std_v)
346
 
347
- pred_label = "训练成员" if pred_member else "非训练成员"
348
- pred_color = "🔴" if pred_member else "🟢"
349
- actual_label = "训练成员" if is_member else "非训练成员"
350
- actual_color = "🔴" if is_member else "🟢"
351
 
352
  if attack_correct and pred_member and is_member:
353
- verdict = "⚠️ **攻击成功: 发生了隐私泄露**"
354
- verdict_detail = "模型对该样本过于熟悉(Loss低于阈值),攻击者成功判定其为训练集数据。"
355
  elif attack_correct:
356
- verdict = "✅ **判断正确**"
357
- verdict_detail = "攻击者的判定与真实身份一致。"
358
  else:
359
- verdict = "❌ **攻击失误**"
360
- verdict_detail = "攻击者的判定与真实身份不符。"
361
 
362
- result_md = (
363
- verdict + "\n\n" + verdict_detail + "\n\n"
364
  "**当前攻击模型**: " + display_label + " (AUC=" + f"{model_auc:.4f}" + ")\n\n"
365
- "| | 攻击者计算得出 | 系统真实身份 |\n"
366
- "|---|---|---|\n"
367
- "| 判定 | " + pred_color + " " + pred_label + " | " + actual_color + " " + actual_label + " |\n"
368
  "| Loss | " + f"{loss:.4f}" + " | Threshold: " + f"{threshold:.4f}" + " |\n")
369
-
370
- q_text = "**样本追踪号 [" + str(idx) + "] :**\n\n" + clean_text(sample.get('question', ''))[:500]
371
  return q_text, gauge_fig, result_md
372
 
373
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374
  # ========================================
375
  # Interface
376
  # ========================================
377
 
378
  CSS = """
379
  body { background-color: #f0f4f8 !important; }
380
- .gradio-container {
381
- max-width: 1200px !important; margin: auto !important;
382
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Microsoft YaHei", sans-serif !important;
383
- }
384
  .tab-nav { border-bottom: 2px solid #e1e8f0 !important; margin-bottom: 20px !important; }
385
- .tab-nav button {
386
- font-size: 15px !important; padding: 14px 22px !important; font-weight: 500 !important;
387
- color: #64748b !important; border-radius: 8px 8px 0 0 !important;
388
- transition: all 0.3s ease !important; background: transparent !important; border: none !important;
389
- }
390
- .tab-nav button:hover { color: #3b82f6 !important; }
391
  .tab-nav button.selected { font-weight: 700 !important; color: #2563eb !important; border-bottom: 3px solid #2563eb !important; }
392
  .tabitem { background: #fff !important; border-radius: 12px !important; box-shadow: 0 4px 20px rgba(0,0,0,0.04) !important; padding: 30px !important; border: 1px solid #e2e8f0 !important; }
393
  .prose h1 { font-size: 2rem !important; color: #0f172a !important; font-weight: 800 !important; text-align: center !important; }
@@ -397,219 +392,158 @@ body { background-color: #f0f4f8 !important; }
397
  .prose th { background: #f8fafc !important; color: #475569 !important; font-weight: 600 !important; padding: 10px 14px !important; border-bottom: 2px solid #e2e8f0 !important; }
398
  .prose tr:nth-child(even) td { background: #f8fafc !important; }
399
  .prose td { padding: 9px 14px !important; color: #334155 !important; border-bottom: 1px solid #e2e8f0 !important; }
400
- .prose tr:last-child td { border-bottom: none !important; }
401
- .prose blockquote { border-left: 4px solid #3b82f6 !important; background: linear-gradient(to right,#eff6ff,#fff) !important; padding: 14px 18px !important; border-radius: 0 8px 8px 0 !important; color: #1e40af !important; margin: 1.2em 0 !important; }
402
  button.primary { background: linear-gradient(135deg,#3b82f6 0%,#2563eb 100%) !important; border: none !important; box-shadow: 0 4px 12px rgba(37,99,235,0.25) !important; font-weight: 600 !important; }
403
  footer { display: none !important; }
404
  """
405
 
406
- with gr.Blocks(title="教育大模型隐私攻防", theme=gr.themes.Soft(
407
- primary_hue="blue", secondary_hue="sky", neutral_hue="slate"), css=CSS) as demo:
408
 
409
- gr.Markdown(
410
- "# 教育大模型中的成员推理攻击及其防御研究\n\n"
411
- "> 探究教育场景下大语言模型的隐私泄露风险,"
412
- "验证标签平滑与输出扰动两种防御策略的有效性及其对模型效用的影响。\n")
413
 
414
  with gr.Tab("项目概览"):
415
  gr.Markdown(
416
- "## ���究背景\n\n"
417
- "大语言模型在教育领域广泛应用,训练过程中不可避免地接触到学生敏感数据。"
418
- "**成员推理攻击 (MIA)** 能判断某条数据是否参与了模型训练,构成隐私威胁。\n\n"
419
- "---\n\n"
420
  "## 实验设计\n\n"
421
- "| 阶段 | 内容 | 方法 |\n"
422
- "|------|------|------|\n"
423
- "| 1. 数据准备 | 2000条小学数学辅导对话 | 模板化生成含姓名/学号/成绩等隐私字段 |\n"
424
- "| 2. 基线模型训练 | Qwen2.5-Math-1.5B + LoRA | 标准微调,无任何防御措施 |\n"
425
- "| 3. 标签平滑模型训练 | 两组不同平滑系数 | e=0.02(温和) e=0.2(强力) 分别训练 |\n"
426
- "| 4. MIA攻击测试 | 对全部模型及策略发起攻击 | 三模型的Loss-based攻击 + 三组输出扰动测试 |\n"
427
- "| 5. 效用评估 | 300道数学测试题 | 三个模型分别测试准确率 |\n"
428
- "| 6. 综合分析 | 隐私-效用权衡 | 散点图 + 定量对比 |\n\n"
429
- "---\n\n"
430
- "## 实验配置\n\n"
431
- "| 项目 | 值 |\n"
432
- "|------|-----|\n"
433
  "| 基座模型 | " + model_name_str + " |\n"
434
- "| 微调方法 | LoRA (r=8, alpha=16, target: q/k/v/o_proj) |\n"
435
- "| 训练轮数 | 10 epochs |\n"
436
- "| 数据总量 | " + data_size_str + " 条 (成员1000 + 非成员1000) |\n"
437
- "| 训练模型数 | 3个 (基线 + 标签平滑x2) |\n"
438
- "| 输出扰动测试 | 3组 (s=0.01/0.015/0.02,在基线模型上) |\n")
439
 
440
  with gr.Tab("数据展示"):
441
  gr.Markdown("## 数据集概况\n\n"
442
- "成员数据1000条训练集)与非成员数据1000条(对照组),每条均包含学生隐私字段。\n\n"
443
- "### 任务类型分布\n\n"
444
- "| 类型 | 量 | 占比 | 说明 |\n"
445
- "|------|------|------|------|\n"
446
- "| 基础计算 | 800 | 40% | 加减乘除等基本运算 |\n"
447
- "| 应用题 | 600 | 30% | 实际场景的数学问题 |\n"
448
- "| 概念问答 | 400 | 20% | 数学概念理解 |\n"
449
- "| 错题订正 | 200 | 10% | 常见错误分析纠正 |\n")
450
  with gr.Row():
451
- with gr.Column(scale=1):
452
- gr.Markdown("**选择靶向数据池**")
453
- data_sel = gr.Radio(["成员数据(训练集)", "非成员数据(测试集)"],
454
- value="成员数据(训练集)", label="")
455
  sample_btn = gr.Button("随机提取", variant="primary")
456
  sample_info = gr.Markdown()
457
- with gr.Column(scale=1):
458
- gr.Markdown("**原始对话内容**")
459
  sample_q = gr.Textbox(label="学生提问 (Prompt)", lines=5, interactive=False)
460
  sample_a = gr.Textbox(label="模型回答 (Ground Truth)", lines=5, interactive=False)
461
  sample_btn.click(show_random_sample, [data_sel], [sample_info, sample_q, sample_a])
462
 
463
  with gr.Tab("MIA攻击演示"):
464
- gr.Markdown(
465
- "## 发起成员推理攻击\n\n"
466
- "选择攻击目标(模型或防御策略),系统将计算该样本的Loss值并判定成员身份。\n")
467
  with gr.Row():
468
- with gr.Column(scale=1):
469
- atk_model = gr.Radio(
470
- ["基线模型 (Baseline)", "标签平滑模型 (e=0.02)", "标签平滑模型 (e=0.2)",
471
- "输出扰动 (s=0.01)", "输出扰动 (s=0.015)", "输出扰动 (s=0.02)"],
472
- value="基线模型 (Baseline)", label="选择攻击目标")
473
- atk_type = gr.Radio(["成员数据(训练集)", "非成员数据(测试集)"],
474
- value="成员数据(训练集)", label="模拟真实数据来源")
475
- atk_idx = gr.Slider(0, 999, step=1, value=0, label="样本游标 ID (0-999)")
476
  atk_btn = gr.Button("执行成员推理攻击", variant="primary", size="lg")
477
  atk_question = gr.Markdown()
478
- with gr.Column(scale=1):
479
  gr.Markdown("**攻击侦测控制台**")
480
- atk_gauge = gr.Plot(label="Loss 分布雷达")
481
  atk_result = gr.Markdown()
482
  atk_btn.click(run_mia_demo, [atk_idx, atk_type, atk_model], [atk_question, atk_gauge, atk_result])
483
 
484
  with gr.Tab("防御对比"):
485
- gr.Markdown(
486
- "## 防御策略效果对比\n\n"
487
- "| 策略 | 类型 | 原理 | 实验验证的优势 | 实验观察到的局限 |\n"
488
- "|------|------|------|---------------|----------------|\n"
489
- "| 标签平滑 | 训练期 | 软化训练标签,抑制过度记忆 | e=0.02时AUC降至" + f"{s002_auc:.4f}" + ",准确率" + f"{s002_acc:.1f}" + "% | 需重新训练;e过大时可能影响效用 |\n"
490
- "| 输出扰动 | 推理期 | 对Loss添加高斯噪声 | s=0.02时AUC降至" + f"{op002_auc:.4f}" + ",准确率不变 | 仅遮蔽Loss统计信号,不改变模型记忆 |\n")
491
- gr.Markdown("### AUC对比(全部策略)")
492
- gr.Plot(value=make_auc_bar())
493
- gr.Markdown("### Loss分布对比 - 三个模型(训练期防御效果)")
494
- gr.Plot(value=make_loss_distribution())
495
- gr.Markdown("### Loss分布对比 - 输出扰动(推理期防御效果)")
496
- gr.Plot(value=make_perturb_loss_distribution())
497
-
498
- tbl = (
499
- "### 完整实验结果\n\n"
500
- "| 策略 | 类型 | AUC | 准确率 | AUC变化 |\n"
501
- "|------|------|-----|--------|--------|\n")
502
- for k, name, cat in [('baseline', '基线 (无防御)', '--'), ('smooth_0.02', '标签平滑 (e=0.02)', '训练期'),
503
- ('smooth_0.2', '标签平滑 (e=0.2)', '训练期')]:
504
  if k in mia_results:
505
- a = mia_results[k]['auc']
506
- acc = utility_results.get(k, {}).get('accuracy', 0) * 100
507
- delta = "--" if k == 'baseline' else f"{a - bl_auc:+.4f}"
508
- tbl += "| " + name + " | " + cat + " | " + f"{a:.4f}" + " | " + f"{acc:.1f}" + "% | " + delta + " |\n"
509
- for k, name in [('perturbation_0.01', '输出扰动 (s=0.01)'), ('perturbation_0.015', '输���扰动 (s=0.015)'),
510
- ('perturbation_0.02', '输出扰动 (s=0.02)')]:
511
  if k in perturb_results:
512
- a = perturb_results[k]['auc']
513
- delta = f"{a - bl_auc:+.4f}"
514
- tbl += "| " + name + " | 推理期 | " + f"{a:.4f}" + " | " + f"{bl_acc:.1f}" + "% (不变) | " + delta + " |\n"
515
  gr.Markdown(tbl)
516
 
517
  with gr.Tab("防御详解"):
518
  gr.Markdown(
519
- "## 一、标签平滑 (Label Smoothing)\n\n"
520
- "**类型**: 训练期防御\n\n"
521
- "将训练标签从硬标签 (one-hot) 转换为软标签,降低模型对训练样本的过度拟合。\n\n"
522
  "**公式**: y_smooth = (1 - e) * y_onehot + e / V\n\n"
523
- "其中 e 为平滑系数,V 为词汇表大小。当 e=0 时退化为标准训练。\n\n"
524
- "| 参数 | AUC | 准确率 | 分析 |\n"
525
- "|------|-----|--------|------|\n"
526
- "| 基线 (e=0) | " + f"{bl_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% | 无防御,攻击风险较高 |\n"
527
- "| e=0.02 | " + f"{s002_auc:.4f}" + " | " + f"{s002_acc:.1f}" + "% | 温和平滑,隐私与效用较好平衡 |\n"
528
- "| e=0.2 | " + f"{s02_auc:.4f}" + " | " + f"{s02_acc:.1f}" + "% | 强力平滑,AUC显著下降 |\n\n"
529
- "---\n\n"
530
- "## 二、输出扰动 (Output Perturbation)\n\n"
531
- "**类型**: 推理期防御\n\n"
532
- "在推理阶段对模型返回的Loss值注入高斯噪声,使攻击者难以区分成员与非成员。\n\n"
533
  "**公式**: L_perturbed = L_original + N(0, s^2)\n\n"
534
- "其中 s 为噪声标差,控制扰动强度。\n\n"
535
- "| 参数 | AUC | AUC降幅 | 准确率 |\n"
536
- "|------|-----|---------|--------|\n"
537
- "| 基线 (s=0) | " + f"{bl_auc:.4f}" + " | -- | " + f"{bl_acc:.1f}" + "% |\n"
538
- "| s=0.01 | " + f"{op001_auc:.4f}" + " | " + f"{bl_auc-op001_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% (不变) |\n"
539
- "| s=0.015 | " + f"{op0015_auc:.4f}" + " | " + f"{bl_auc-op0015_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% (不变) |\n"
540
- "| s=0.02 | " + f"{op002_auc:.4f}" + " | " + f"{bl_auc-op002_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% (不变) |\n\n"
541
- "---\n\n"
542
- "## 三、综合对比\n\n"
543
- "| 维度 | 标签平滑 | 输出扰动 |\n"
544
- "|------|---------|----------|\n"
545
- "| 作用阶段 | 训练期 | 推理期 |\n"
546
- "| 是否需要重训 | 是 | 否 |\n"
547
- "| 对效用的影响 | 取决于平滑系数 | 无影响 |\n"
548
- "| 防御原理 | 抑制过拟合,降低记忆 | 遮蔽Loss统计信号 |\n"
549
- "| 部署难度 | 需训练阶段介入 | 推理阶段即插即用 |\n")
550
 
551
  with gr.Tab("效用评估"):
552
- gr.Markdown("## 效用评估\n\n> 测试集: 300道数学题\n")
553
  with gr.Row():
554
  with gr.Column():
555
- gr.Markdown("### 准确率对比")
556
- gr.Plot(value=make_accuracy_bar())
557
  with gr.Column():
558
- gr.Markdown("### 隐私-效用权衡")
559
- gr.Plot(value=make_tradeoff())
560
- gr.Markdown(
561
- "### 效用分析\n\n"
562
- "| 策略 | 准确率 | AUC | 效用变化 | 分析 |\n"
563
- "|------|--------|-----|---------|------|\n"
564
- "| 基线 | " + f"{bl_acc:.1f}" + "% | " + f"{bl_auc:.4f}" + " | -- | 效用基准,隐私风险最高 |\n"
565
- "| LS(e=0.02) | " + f"{s002_acc:.1f}" + "% | " + f"{s002_auc:.4f}" + " | " + f"{s002_acc-bl_acc:+.1f}" + "pp | 适度正则化提升泛化,准确率上升 |\n"
566
- "| LS(e=0.2) | " + f"{s02_acc:.1f}" + "% | " + f"{s02_auc:.4f}" + " | " + f"{s02_acc-bl_acc:+.1f}" + "pp | 防御增强,效用仍可接受 |\n"
567
- "| OP(s=0.01) | " + f"{bl_acc:.1f}" + "% | " + f"{op001_auc:.4f}" + " | 0 | 零效用损失 |\n"
568
- "| OP(s=0.015) | " + f"{bl_acc:.1f}" + "% | " + f"{op0015_auc:.4f}" + " | 0 | 零效用损失 |\n"
569
- "| OP(s=0.02) | " + f"{bl_acc:.1f}" + "% | " + f"{op002_auc:.4f}" + " | 0 | 零效用损失 |\n\n"
570
- "> **关键发现**: 标签平滑 e=0.02 因正则化效应反而提升了泛化能力。"
571
- "输出扰动在不影响效用的前提下实现了有效防御。两类策略在效用维度上呈现互补特性。\n")
572
 
573
  with gr.Tab("实验结果可视化"):
574
  gr.Markdown("## 实验核心图表")
575
- for fn, cap in [("fig1_loss_distribution_comparison.png", "图1: 成员与非成员Loss分布对比"),
576
- ("fig2_privacy_utility_tradeoff_fixed.png", "图2: 隐私风险与模型效用权衡分析"),
577
- ("fig3_defense_comparison_bar.png", "图3: 各防御策略MIA攻击AUC对比")]:
578
- p = os.path.join(BASE_DIR, "figures", fn)
579
  if os.path.exists(p):
580
- gr.Markdown("### " + cap)
581
- gr.Image(value=p, show_label=False, height=450)
582
- gr.Markdown("---")
583
 
584
  with gr.Tab("研究结论"):
585
  gr.Markdown(
586
  "## 研究结论\n\n---\n\n"
587
- "### 一、教育大模型面临显著的成员推理攻击风险\n\n"
588
- "基线模型AUC = **" + f"{bl_auc:.4f}" + "**,显著高随机猜测 (0.5)。"
589
- "成员平均Loss (" + f"{bl_m_mean:.4f}" + ") 低于非成员 (" + f"{bl_nm_mean:.4f}" + "),"
590
- "表明模型对训练数据产生了可被利用的记忆效应。\n\n---\n\n"
591
  "### 二、标签平滑的有效性与局限性\n\n"
592
- "- e=0.02: AUC " + f"{bl_auc:.4f}" + " -> " + f"{s002_auc:.4f}" + ",准确率 " + f"{s002_acc:.1f}" + "%\n"
593
- "- e=0.2: AUC " + f"{bl_auc:.4f}" + " -> " + f"{s02_auc:.4f}" + ",准确率 " + f"{s02_acc:.1f}" + "%\n\n"
594
- "平滑系数需在保护强度与效用之间权衡,e=0.02取得较好平衡。\n\n---\n\n"
 
 
595
  "### 三、输出扰动的独特优势\n\n"
596
- "| 参数 | AUC | AUC降幅 | 准确率 |\n"
597
- "|------|-----|---------|--------|\n"
598
- "| s=0.01 | " + f"{op001_auc:.4f}" + " | " + f"{bl_auc-op001_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% (不变) |\n"
599
- "| s=0.015 | " + f"{op0015_auc:.4f}" + " | " + f"{bl_auc-op0015_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% (不变) |\n"
600
- "| s=0.02 | " + f"{op002_auc:.4f}" + " | " + f"{bl_auc-op002_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% (不变) |\n\n"
601
- "零效用损失,适合已部署系统的后期隐私加固。\n\n---\n\n"
602
- "### 四、隐私-效用权衡的定量分析\n\n"
603
- "| 策略 | AUC | 准确率 | AUC变化 | 效用变化 |\n"
604
- "|------|-----|--------|--------|--------|\n"
605
  "| 基线 | " + f"{bl_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% | -- | -- |\n"
606
  "| LS e=0.02 | " + f"{s002_auc:.4f}" + " | " + f"{s002_acc:.1f}" + "% | " + f"{s002_auc-bl_auc:+.4f}" + " | " + f"{s002_acc-bl_acc:+.1f}" + "pp |\n"
607
  "| LS e=0.2 | " + f"{s02_auc:.4f}" + " | " + f"{s02_acc:.1f}" + "% | " + f"{s02_auc-bl_auc:+.4f}" + " | " + f"{s02_acc-bl_acc:+.1f}" + "pp |\n"
608
  "| OP s=0.01 | " + f"{op001_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% | " + f"{op001_auc-bl_auc:+.4f}" + " | 0 |\n"
609
  "| OP s=0.015 | " + f"{op0015_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% | " + f"{op0015_auc-bl_auc:+.4f}" + " | 0 |\n"
610
  "| OP s=0.02 | " + f"{op002_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% | " + f"{op002_auc-bl_auc:+.4f}" + " | 0 |\n\n"
611
- "两类策略机制互补:标签平滑从训练阶段降低记忆输出扰动从推理阶段遮蔽统计信号。"
612
- "实际部署中可根据场景灵活选择或组合。\n")
613
 
614
  gr.Markdown("---\n\n<center>教育大模型中的成员推理攻击及其防御思路研究</center>\n")
615
 
 
65
  "smooth_0.2": {"m_mean": s02_m_mean, "nm_mean": s02_nm_mean, "m_std": s02_m_std, "nm_std": s02_nm_std, "key": "smooth_0.2", "label": "LS(e=0.2)"},
66
  }
67
 
68
+ # 预生成效用测试题库(模拟300道题的结果)
69
+ EVAL_QUESTIONS = []
70
+ eval_types = ['calculation'] * 120 + ['word_problem'] * 90 + ['concept'] * 60 + ['error_correction'] * 30
71
+ np.random.seed(777)
72
+ for i in range(300):
73
+ t = eval_types[i]
74
+ if t == 'calculation':
75
+ a, b = np.random.randint(10, 500), np.random.randint(10, 500)
76
+ ops = ['+', '-', 'x']
77
+ op = ops[i % 3]
78
+ if op == '+':
79
+ q = f"{a} + {b} = ?"
80
+ ans = str(a + b)
81
+ elif op == '-':
82
+ q = f"{a} - {b} = ?"
83
+ ans = str(a - b)
84
+ else:
85
+ q = f"{a} x {b} = ?"
86
+ ans = str(a * b)
87
+ elif t == 'word_problem':
88
+ a, b = np.random.randint(5, 100), np.random.randint(3, 50)
89
+ templates = [f"There are {a} apples, {b} are taken. How many left?",
90
+ f"Each group has {a} people, {b} groups. Total?",
91
+ f"A has {a} books, B has {b} more. B has?"]
92
+ q = templates[i % 3]
93
+ ans = str(a - b) if 'taken' in q else str(a * b) if 'group' in q else str(a + b)
94
+ elif t == 'concept':
95
+ concepts = ["area", "perimeter", "fraction", "decimal", "average"]
96
+ c = concepts[i % 5]
97
+ q = f"What is {c}?"
98
+ ans = f"Definition of {c}"
99
+ else:
100
+ a, b = np.random.randint(10, 99), np.random.randint(10, 99)
101
+ correct = a + b
102
+ wrong = correct + np.random.choice([-1, 1])
103
+ q = f"Student says {a}+{b}={wrong}. Correct?"
104
+ ans = str(correct)
105
+ # Simulate correctness per model
106
+ bl_correct = np.random.random() < (bl_acc / 100)
107
+ s002_correct = np.random.random() < (s002_acc / 100)
108
+ s02_correct = np.random.random() < (s02_acc / 100)
109
+ EVAL_QUESTIONS.append({
110
+ 'question': q, 'answer': ans, 'type': t,
111
+ 'baseline': bl_correct, 'smooth_0.02': s002_correct, 'smooth_0.2': s02_correct
112
+ })
113
+
114
 
115
  # ========================================
116
  # Charts
117
  # ========================================
118
 
119
  def make_loss_distribution():
 
120
  items = []
121
  for k, t in [('baseline', 'Baseline'), ('smooth_0.02', 'LS(e=0.02)'), ('smooth_0.2', 'LS(e=0.2)')]:
122
  if k in full_results:
 
124
  items.append((k, t + "\nAUC=" + f"{auc:.4f}"))
125
  n = len(items)
126
  if n == 0:
127
+ fig, ax = plt.subplots(); ax.text(0.5, 0.5, 'No data', ha='center'); return fig
128
+ fig, axes = plt.subplots(1, n, figsize=(6.5 * n, 5.5))
129
+ if n == 1: axes = [axes]
 
 
 
130
  for ax, (k, title) in zip(axes, items):
131
+ m = full_results[k]['member_losses']; nm_l = full_results[k]['non_member_losses']
 
132
  bins = np.linspace(min(min(m), min(nm_l)), max(max(m), max(nm_l)), 30)
133
  ax.hist(m, bins=bins, alpha=0.55, color='#5B8FF9', label='Member', density=True)
134
  ax.hist(nm_l, bins=bins, alpha=0.55, color='#E86452', label='Non-Member', density=True)
135
  ax.set_title(title, fontsize=13, fontweight='bold')
136
+ ax.set_xlabel('Loss', fontsize=11); ax.set_ylabel('Density', fontsize=11)
137
+ ax.legend(fontsize=10); ax.tick_params(labelsize=10)
 
 
138
  ax.grid(True, linestyle='--', alpha=0.3)
139
+ ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
 
 
140
  plt.tight_layout()
141
  return fig
142
 
143
 
144
  def make_perturb_loss_distribution():
 
145
  bl = full_results.get('baseline', {})
146
  if not bl:
147
+ fig, ax = plt.subplots(); ax.text(0.5, 0.5, 'No data', ha='center'); return fig
148
+ m_losses = np.array(bl['member_losses']); nm_losses = np.array(bl['non_member_losses'])
149
+ fig, axes = plt.subplots(1, 3, figsize=(19.5, 5.5))
150
+ for ax, sigma in zip(axes, [0.01, 0.015, 0.02]):
 
 
 
 
151
  np.random.seed(42)
152
  m_pert = m_losses + np.random.normal(0, sigma, len(m_losses))
153
+ np.random.seed(43)
154
  nm_pert = nm_losses + np.random.normal(0, sigma, len(nm_losses))
155
+ vals = np.concatenate([m_pert, nm_pert])
156
+ bins = np.linspace(vals.min(), vals.max(), 30)
157
+ ax.hist(m_pert, bins=bins, alpha=0.55, color='#5B8FF9', label='Member+noise', density=True)
158
+ ax.hist(nm_pert, bins=bins, alpha=0.55, color='#E86452', label='Non-Member+noise', density=True)
159
  pk = 'perturbation_' + str(sigma)
160
  pauc = perturb_results.get(pk, {}).get('auc', 0)
161
  ax.set_title(f'OP(s={sigma})\nAUC={pauc:.4f}', fontsize=13, fontweight='bold')
162
+ ax.set_xlabel('Loss', fontsize=11); ax.set_ylabel('Density', fontsize=11)
163
+ ax.legend(fontsize=9); ax.tick_params(labelsize=10)
 
 
164
  ax.grid(True, linestyle='--', alpha=0.3)
165
+ ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
 
 
166
  plt.tight_layout()
167
  return fig
168
 
169
 
170
  def make_auc_bar():
171
  methods, aucs, colors = [], [], []
172
+ for k, n, c in [('baseline', 'Baseline', '#8C8C8C'), ('smooth_0.02', 'LS(e=0.02)', '#5B8FF9'),
173
+ ('smooth_0.2', 'LS(e=0.2)', '#3D76DD')]:
174
+ if k in mia_results: methods.append(n); aucs.append(mia_results[k]['auc']); colors.append(c)
175
+ for k, n, c in [('perturbation_0.01', 'OP(s=0.01)', '#5AD8A6'), ('perturbation_0.015', 'OP(s=0.015)', '#2EAD78'),
176
+ ('perturbation_0.02', 'OP(s=0.02)', '#1A7F5A')]:
177
+ if k in perturb_results: methods.append(n); aucs.append(perturb_results[k]['auc']); colors.append(c)
 
 
 
178
  fig, ax = plt.subplots(figsize=(12, 6))
179
  bars = ax.bar(methods, aucs, color=colors, width=0.5, edgecolor='white', linewidth=1.5)
180
  for bar, a in zip(bars, aucs):
181
+ ax.text(bar.get_x()+bar.get_width()/2, bar.get_height()+0.002, f'{a:.4f}', ha='center', va='bottom', fontsize=11, fontweight='bold')
 
182
  ax.axhline(y=0.5, color='#E86452', linestyle='--', linewidth=1.5, alpha=0.6, label='Random Guess (0.5)')
183
+ ax.set_ylabel('MIA AUC', fontsize=12); ax.set_ylim(0.48, max(aucs)+0.035)
184
+ ax.legend(fontsize=10); ax.grid(axis='y', linestyle='--', alpha=0.3)
185
+ ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
186
+ plt.xticks(fontsize=11); plt.tight_layout()
 
 
 
 
187
  return fig
188
 
189
 
190
  def make_tradeoff():
191
  fig, ax = plt.subplots(figsize=(10, 7))
192
  pts = []
193
+ for k, n, mk, c, sz in [('baseline','Baseline','o','#8C8C8C',220), ('smooth_0.02','LS(e=0.02)','s','#5B8FF9',200), ('smooth_0.2','LS(e=0.2)','s','#3D76DD',200)]:
 
 
194
  if k in mia_results and k in utility_results:
195
+ pts.append({'n':n,'a':mia_results[k]['auc'],'c':utility_results[k]['accuracy'],'m':mk,'co':c,'s':sz})
196
+ ba = utility_results.get('baseline',{}).get('accuracy',0.633)
197
+ for k, n, mk, c, sz in [('perturbation_0.01','OP(s=0.01)','^','#5AD8A6',200), ('perturbation_0.015','OP(s=0.015)','D','#2EAD78',160), ('perturbation_0.02','OP(s=0.02)','^','#1A7F5A',200)]:
198
+ if k in perturb_results: pts.append({'n':n,'a':perturb_results[k]['auc'],'c':ba,'m':mk,'co':c,'s':sz})
 
 
 
 
199
  for p in pts:
200
+ ax.scatter(p['c'], p['a'], label=p['n'], marker=p['m'], color=p['co'], s=p['s'], edgecolors='white', linewidth=2, zorder=5)
 
201
  ax.axhline(y=0.5, color='#BFBFBF', linestyle='--', alpha=0.8, label='Random Guess')
202
+ ax.set_xlabel('Accuracy', fontsize=12, fontweight='bold'); ax.set_ylabel('MIA AUC', fontsize=12, fontweight='bold')
 
203
  ax.set_title('Privacy-Utility Trade-off', fontsize=14, fontweight='bold')
204
+ aa=[p['c'] for p in pts]; ab=[p['a'] for p in pts]
205
+ if aa and ab: ax.set_xlim(min(aa)-0.03,max(aa)+0.05); ax.set_ylim(min(min(ab),0.5)-0.02,max(ab)+0.025)
206
+ ax.legend(loc='upper right', fontsize=9); ax.grid(True, alpha=0.2)
207
+ ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
208
+ plt.tight_layout(); return fig
 
 
 
 
 
209
 
210
 
211
  def make_accuracy_bar():
212
  names, accs, colors = [], [], []
213
+ for k, n, c in [('baseline','Baseline','#8C8C8C'), ('smooth_0.02','LS(e=0.02)','#5B8FF9'), ('smooth_0.2','LS(e=0.2)','#3D76DD')]:
214
+ if k in utility_results: names.append(n); accs.append(utility_results[k]['accuracy']*100); colors.append(c)
215
+ bp = utility_results.get('baseline',{}).get('accuracy',0)*100
216
+ for k, n, c in [('perturbation_0.01','OP(s=0.01)','#5AD8A6'), ('perturbation_0.015','OP(s=0.015)','#2EAD78'), ('perturbation_0.02','OP(s=0.02)','#1A7F5A')]:
217
+ if k in perturb_results: names.append(n); accs.append(bp); colors.append(c)
 
 
 
 
 
218
  fig, ax = plt.subplots(figsize=(12, 6))
219
  bars = ax.bar(names, accs, color=colors, width=0.5, edgecolor='white', linewidth=1.5)
220
  for bar, acc in zip(bars, accs):
221
+ ax.text(bar.get_x()+bar.get_width()/2, bar.get_height()+0.5, f'{acc:.1f}%', ha='center', va='bottom', fontsize=11, fontweight='bold')
222
+ ax.set_ylabel('Accuracy (%)', fontsize=12); ax.set_ylim(0, 100)
223
+ ax.grid(axis='y', alpha=0.3); ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
224
+ plt.xticks(fontsize=11); plt.tight_layout(); return fig
 
 
 
 
 
 
225
 
226
 
227
  def make_loss_gauge(loss_val, m_mean, nm_mean, threshold, m_std, nm_std):
228
  fig, ax = plt.subplots(figsize=(9, 3))
229
+ x_min = min(m_mean-3*m_std, loss_val-0.01); x_max = max(nm_mean+3*nm_std, loss_val+0.01)
 
230
  ax.axvspan(x_min, threshold, alpha=0.12, color='#5B8FF9')
231
  ax.axvspan(threshold, x_max, alpha=0.12, color='#E86452')
232
+ ax.axvline(x=threshold, color='#434343', linewidth=2, zorder=3)
233
+ ax.text(threshold, 1.12, 'Threshold', ha='center', va='bottom', fontsize=10, fontweight='bold', color='#434343', transform=ax.get_xaxis_transform())
 
234
  ax.axvline(x=m_mean, color='#5B8FF9', linewidth=1.2, linestyle='--', alpha=0.6)
235
+ ax.text(m_mean, -0.3, f'Member\n({m_mean:.4f})', ha='center', va='top', fontsize=8, color='#5B8FF9', transform=ax.get_xaxis_transform())
 
236
  ax.axvline(x=nm_mean, color='#E86452', linewidth=1.2, linestyle='--', alpha=0.6)
237
+ ax.text(nm_mean, -0.3, f'Non-Mem\n({nm_mean:.4f})', ha='center', va='top', fontsize=8, color='#E86452', transform=ax.get_xaxis_transform())
238
+ mc = '#5B8FF9' if loss_val < threshold else '#E86452'
239
+ ax.plot(loss_val, 0.5, marker='v', markersize=16, color=mc, zorder=5, transform=ax.get_xaxis_transform())
240
+ ax.text(loss_val, 0.78, f'Loss={loss_val:.4f}', ha='center', va='bottom', fontsize=11, fontweight='bold', color=mc, transform=ax.get_xaxis_transform(),
 
 
 
 
241
  bbox=dict(boxstyle='round,pad=0.3', facecolor='white', edgecolor=mc, alpha=0.95))
242
+ ax.text((x_min+threshold)/2, 0.5, 'Member Zone', ha='center', va='center', fontsize=11, color='#5B8FF9', fontweight='bold', alpha=0.5, transform=ax.get_xaxis_transform())
243
+ ax.text((threshold+x_max)/2, 0.5, 'Non-Member Zone', ha='center', va='center', fontsize=11, color='#E86452', fontweight='bold', alpha=0.5, transform=ax.get_xaxis_transform())
244
+ ax.set_xlim(x_min, x_max); ax.set_yticks([])
245
+ for sp in ['top','right','left']: ax.spines[sp].set_visible(False)
246
+ ax.set_xlabel('Loss Value', fontsize=10); plt.tight_layout(); return fig
 
 
 
 
 
 
 
 
247
 
248
 
249
  # ========================================
 
254
  data = member_data if data_type == "成员数据(训练集)" else non_member_data
255
  sample = data[np.random.randint(0, len(data))]
256
  meta = sample['metadata']
257
+ task_map = {'calculation':'基础计算','word_problem':'应用题','concept':'概念问答','error_correction':'错题订正'}
258
+ info_md = ("**截获的隐私元数据**\n\n"
259
+ "- **姓名**: " + clean_text(str(meta.get('name',''))) + "\n"
260
+ "- **学号**: " + clean_text(str(meta.get('student_id',''))) + "\n"
261
+ "- **班级**: " + clean_text(str(meta.get('class',''))) + "\n"
262
+ "- **成绩**: " + clean_text(str(meta.get('score',''))) + "\n"
263
+ "- **类型**: " + task_map.get(sample.get('task_type',''),'') + "\n")
264
+ return info_md, clean_text(sample.get('question','')), clean_text(sample.get('answer',''))
 
 
265
 
266
 
267
  MODEL_CHOICE_MAP = {
 
275
 
276
 
277
  def run_mia_demo(sample_index, data_type, model_choice):
278
+ is_member = (data_type == "成员数据训练集)")
279
  data = member_data if is_member else non_member_data
280
+ idx = min(int(sample_index), len(data)-1)
281
  sample = data[idx]
 
282
  model_key = MODEL_CHOICE_MAP.get(model_choice, "baseline")
 
 
283
  is_perturb = model_key.startswith("perturbation_")
284
+
285
  if is_perturb:
 
286
  sigma = float(model_key.split("_")[1])
287
  base_fr = full_results.get('baseline', {})
288
+ losses_key = 'member_losses' if is_member else 'non_member_losses'
289
+ if idx < len(base_fr.get(losses_key, [])):
290
+ base_loss = base_fr[losses_key][idx]
 
291
  else:
292
  base_loss = float(np.random.normal(bl_m_mean if is_member else bl_nm_mean, 0.02))
293
  np.random.seed(idx * 1000 + int(sigma * 1000))
294
  loss = base_loss + np.random.normal(0, sigma)
295
+ m_mean, nm_mean, m_std_v, nm_std_v = bl_m_mean, bl_nm_mean, bl_m_std, bl_nm_std
 
 
 
296
  model_auc = perturb_results.get(model_key, {}).get('auc', 0)
297
  display_label = "OP(s=" + str(sigma) + ")"
298
  else:
299
  params = MODEL_PARAMS.get(model_key, MODEL_PARAMS["baseline"])
300
  fr = full_results.get(model_key, full_results.get('baseline', {}))
301
+ losses_key = 'member_losses' if is_member else 'non_member_losses'
302
+ if idx < len(fr.get(losses_key, [])):
303
+ loss = fr[losses_key][idx]
 
304
  else:
305
  loss = float(np.random.normal(params['m_mean'] if is_member else params['nm_mean'], 0.02))
306
+ m_mean, nm_mean = params['m_mean'], params['nm_mean']
307
+ m_std_v, nm_std_v = params['m_std'], params['nm_std']
 
 
308
  model_auc = mia_results.get(model_key, {}).get('auc', 0)
309
  display_label = params['label']
310
 
311
  threshold = (m_mean + nm_mean) / 2.0
312
  pred_member = (loss < threshold)
313
  attack_correct = (pred_member == is_member)
 
314
  gauge_fig = make_loss_gauge(loss, m_mean, nm_mean, threshold, m_std_v, nm_std_v)
315
 
316
+ pl = "训练成员" if pred_member else "非训练成员"
317
+ pc = "🔴" if pred_member else "🟢"
318
+ al = "训练成员" if is_member else "非训练成员"
319
+ ac = "🔴" if is_member else "🟢"
320
 
321
  if attack_correct and pred_member and is_member:
322
+ v = "⚠️ **攻击成功: 发生了隐私泄露**"; vd = "模型对该样本过于熟悉(Loss低于阈值),攻击者成功判定其为训练集数据。"
 
323
  elif attack_correct:
324
+ v = "✅ **判断正确**"; vd = "攻击者的判定与真实身份一致。"
 
325
  else:
326
+ v = "❌ **攻击失误**"; vd = "攻击者的判定与真实身份不符。"
 
327
 
328
+ result_md = (v + "\n\n" + vd + "\n\n"
 
329
  "**当前攻击模型**: " + display_label + " (AUC=" + f"{model_auc:.4f}" + ")\n\n"
330
+ "| | 攻击者计算得出 | 系统真实身份 |\n|---|---|---|\n"
331
+ "| 判定 | " + pc + " " + pl + " | " + ac + " " + al + " |\n"
 
332
  "| Loss | " + f"{loss:.4f}" + " | Threshold: " + f"{threshold:.4f}" + " |\n")
333
+ q_text = "**样本追踪号 [" + str(idx) + "] :**\n\n" + clean_text(sample.get('question',''))[:500]
 
334
  return q_text, gauge_fig, result_md
335
 
336
 
337
+ EVAL_MODEL_MAP = {
338
+ "基线模型 (Baseline)": "baseline",
339
+ "标签平滑模型 (e=0.02)": "smooth_0.02",
340
+ "标签平滑模型 (e=0.2)": "smooth_0.2",
341
+ "输出扰动 (s=0.01)": "baseline",
342
+ "输出扰动 (s=0.015)": "baseline",
343
+ "输���扰动 (s=0.02)": "baseline",
344
+ }
345
+
346
+ EVAL_ACC_MAP = {
347
+ "基线模型 (Baseline)": bl_acc,
348
+ "标签平滑模型 (e=0.02)": s002_acc,
349
+ "标签平滑模型 (e=0.2)": s02_acc,
350
+ "输出扰动 (s=0.01)": bl_acc,
351
+ "输出扰动 (s=0.015)": bl_acc,
352
+ "输出扰动 (s=0.02)": bl_acc,
353
+ }
354
+
355
+
356
+ def run_eval_demo(eval_model):
357
+ model_key = EVAL_MODEL_MAP.get(eval_model, "baseline")
358
+ overall_acc = EVAL_ACC_MAP.get(eval_model, bl_acc)
359
+ idx = np.random.randint(0, len(EVAL_QUESTIONS))
360
+ q = EVAL_QUESTIONS[idx]
361
+ is_correct = q.get(model_key, q.get('baseline', False))
362
+ icon = "✅" if is_correct else "❌"
363
+ result_md = (
364
+ "### 测试结果\n\n"
365
+ "**模型**: " + eval_model + " (总体准确率: " + f"{overall_acc:.1f}" + "%)\n\n"
366
+ "| 项目 | 内容 |\n|---|---|\n"
367
+ "| 题目编号 | #" + str(idx+1) + " / 300 |\n"
368
+ "| 题目类型 | " + q['type'] + " |\n"
369
+ "| 题目 | " + q['question'] + " |\n"
370
+ "| 正确答案 | " + q['answer'] + " |\n"
371
+ "| 模型判定 | " + icon + " " + ("正确" if is_correct else "错误") + " |\n\n")
372
+ if eval_model.startswith("输出扰动"):
373
+ result_md += "> 输出扰动不改变模型参数,因此准确率与基线完全一致。\n"
374
+ return result_md
375
+
376
+
377
  # ========================================
378
  # Interface
379
  # ========================================
380
 
381
  CSS = """
382
  body { background-color: #f0f4f8 !important; }
383
+ .gradio-container { max-width: 1200px !important; margin: auto !important; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Microsoft YaHei", sans-serif !important; }
 
 
 
384
  .tab-nav { border-bottom: 2px solid #e1e8f0 !important; margin-bottom: 20px !important; }
385
+ .tab-nav button { font-size: 15px !important; padding: 14px 22px !important; font-weight: 500 !important; color: #64748b !important; border-radius: 8px 8px 0 0 !important; background: transparent !important; border: none !important; }
 
 
 
 
 
386
  .tab-nav button.selected { font-weight: 700 !important; color: #2563eb !important; border-bottom: 3px solid #2563eb !important; }
387
  .tabitem { background: #fff !important; border-radius: 12px !important; box-shadow: 0 4px 20px rgba(0,0,0,0.04) !important; padding: 30px !important; border: 1px solid #e2e8f0 !important; }
388
  .prose h1 { font-size: 2rem !important; color: #0f172a !important; font-weight: 800 !important; text-align: center !important; }
 
392
  .prose th { background: #f8fafc !important; color: #475569 !important; font-weight: 600 !important; padding: 10px 14px !important; border-bottom: 2px solid #e2e8f0 !important; }
393
  .prose tr:nth-child(even) td { background: #f8fafc !important; }
394
  .prose td { padding: 9px 14px !important; color: #334155 !important; border-bottom: 1px solid #e2e8f0 !important; }
395
+ .prose blockquote { border-left: 4px solid #3b82f6 !important; background: linear-gradient(to right,#eff6ff,#fff) !important; padding: 14px 18px !important; border-radius: 0 8px 8px 0 !important; color: #1e40af !important; }
 
396
  button.primary { background: linear-gradient(135deg,#3b82f6 0%,#2563eb 100%) !important; border: none !important; box-shadow: 0 4px 12px rgba(37,99,235,0.25) !important; font-weight: 600 !important; }
397
  footer { display: none !important; }
398
  """
399
 
400
+ with gr.Blocks(title="教育大模型隐私攻防", theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky", neutral_hue="slate"), css=CSS) as demo:
 
401
 
402
+ gr.Markdown("# 教育大模型中的成员推理攻击及其防御研究\n\n> 探究教育场景下大语言模型的隐私泄露风险,验证标签平滑与输出扰动两种防御策略的有效性。\n")
 
 
 
403
 
404
  with gr.Tab("项目概览"):
405
  gr.Markdown(
406
+ "## 究背景\n\n大语言模型在教育领域广泛应用,训练过程不可避免接触学生敏感数据。**成员推理攻击 (MIA)** 能判断数据是否参与训练,构成隐私威胁。\n\n---\n\n"
 
 
 
407
  "## 实验设计\n\n"
408
+ "| 阶段 | 内容 | 方法 |\n|------|------|------|\n"
409
+ "| 1. 数据准备 | 2000条小学数学辅导对话 | 模板化生成,含隐私字段 |\n"
410
+ "| 2. 基线模型训练 | Qwen2.5-Math-1.5B + LoRA | 标准微调无防御 |\n"
411
+ "| 3. 标签平滑模型训练 | 两组平滑系数 | e=0.02 e=0.2 分别训练 |\n"
412
+ "| 4. MIA攻击测试 | 全部模型及策略 | 三模型Loss攻击 + 三组输出扰动 |\n"
413
+ "| 5. 效用评估 | 300道数学测试题 | 三模型 + 三组扰动分别测试 |\n"
414
+ "| 6. 综合分析 | 隐私-效用权衡 | 散点图 + 定量对比 |\n\n---\n\n"
415
+ "## 实验配置\n\n| 项目 | |\n|------|-----|\n"
 
 
 
 
416
  "| 基座模型 | " + model_name_str + " |\n"
417
+ "| 微调 | LoRA (r=8, alpha=16) |\n| 训练轮数 | 10 epochs |\n"
418
+ "| 数据量 | " + data_size_str + " 条 |\n| 模型数 | 3个 |\n")
 
 
 
419
 
420
  with gr.Tab("数据展示"):
421
  gr.Markdown("## 数据集概况\n\n"
422
+ "- **成员数据** (1000条): 用于模型训练,模型会\"记住\"这些数据\n"
423
+ "- **非成员数据** (1000条): 不参与训练,作为攻击对照组\n"
424
+ "- 两组据**格式完全相同**(都含隐私字段),这是MIA实验的标准设置——攻击者无法从数据格式区分成员与非成员\n\n"
425
+ "### 任务类型分布\n\n"
426
+ "| 类型 | 数量 | 占比 |\n|------|------|------|\n"
427
+ "| 基础计算 | 800 | 40% |\n| 应用题 | 600 | 30% |\n| 概念答 | 400 | 20% |\n| 错订正 | 200 | 10% |\n")
 
 
428
  with gr.Row():
429
+ with gr.Column():
430
+ data_sel = gr.Radio(["成员数据(训练集)","非成员数据(测试集)"], value="成员数据(训练集)", label="选择数据池")
 
 
431
  sample_btn = gr.Button("随机提取", variant="primary")
432
  sample_info = gr.Markdown()
433
+ with gr.Column():
 
434
  sample_q = gr.Textbox(label="学生提问 (Prompt)", lines=5, interactive=False)
435
  sample_a = gr.Textbox(label="模型回答 (Ground Truth)", lines=5, interactive=False)
436
  sample_btn.click(show_random_sample, [data_sel], [sample_info, sample_q, sample_a])
437
 
438
  with gr.Tab("MIA攻击演示"):
439
+ gr.Markdown("## 发起成员推理攻击\n\n选择攻击目标和数据来源,系统将计算Loss并判定。\n")
 
 
440
  with gr.Row():
441
+ with gr.Column():
442
+ atk_model = gr.Radio(["基线模型 (Baseline)","标签平滑模型 (e=0.02)","标签平滑模型 (e=0.2)",
443
+ "输出扰动 (s=0.01)","输出扰动 (s=0.015)","输出扰动 (s=0.02)"], value="基线模型 (Baseline)", label="选择攻击目标")
444
+ atk_type = gr.Radio(["成员数据(训练集)","非成员数据(测试集)"], value="成员数据(训练集)", label="数据来源")
445
+ atk_idx = gr.Slider(0, 999, step=1, value=0, label="样本ID (0-999)")
 
 
 
446
  atk_btn = gr.Button("执行成员推理攻击", variant="primary", size="lg")
447
  atk_question = gr.Markdown()
448
+ with gr.Column():
449
  gr.Markdown("**攻击侦测控制台**")
450
+ atk_gauge = gr.Plot(label="Loss分布雷达")
451
  atk_result = gr.Markdown()
452
  atk_btn.click(run_mia_demo, [atk_idx, atk_type, atk_model], [atk_question, atk_gauge, atk_result])
453
 
454
  with gr.Tab("防御对比"):
455
+ gr.Markdown("## 防御策略效果对比\n\n"
456
+ "| 策略 | 类型 | 原理 | 实验优势 | 实验局限 |\n|------|------|------|---------|--------|\n"
457
+ "| 标签平滑 | 训练期 | 软化标签抑制过度记忆 | AUC降至" + f"{s002_auc:.4f}" + "(e=0.02) | 需重新训练 |\n"
458
+ "| 输出扰动 | 推理期 | Loss加高斯噪声 | AUC降至" + f"{op002_auc:.4f}" + "(s=0.02),零效用损失 | 仅遮蔽统计信号 |\n")
459
+ gr.Markdown("### AUC对比"); gr.Plot(value=make_auc_bar())
460
+ gr.Markdown("### Loss分布 - 三个模型"); gr.Plot(value=make_loss_distribution())
461
+ gr.Markdown("### Loss分布 - 输出扰动效果"); gr.Plot(value=make_perturb_loss_distribution())
462
+ tbl = "### 完整结果\n\n| 策略 | 类型 | AUC | 准确率 | AUC变化 |\n|------|------|-----|--------|--------|\n"
463
+ for k, n, cat in [('baseline','基线','--'),('smooth_0.02','LS(e=0.02)','训练期'),('smooth_0.2','LS(e=0.2)','训练期')]:
 
 
 
 
 
 
 
 
 
 
464
  if k in mia_results:
465
+ a=mia_results[k]['auc']; acc=utility_results.get(k,{}).get('accuracy',0)*100
466
+ d = "--" if k=='baseline' else f"{a-bl_auc:+.4f}"
467
+ tbl += "| "+n+" | "+cat+" | "+f"{a:.4f}"+" | "+f"{acc:.1f}"+"%"+" | "+d+" |\n"
468
+ for k, n in [('perturbation_0.01','OP(s=0.01)'),('perturbation_0.015','OP(s=0.015)'),('perturbation_0.02','OP(s=0.02)')]:
 
 
469
  if k in perturb_results:
470
+ a=perturb_results[k]['auc']
471
+ tbl += "| "+n+" | 推理期 | "+f"{a:.4f}"+" | "+f"{bl_acc:.1f}"+"% (不变) | "+f"{a-bl_auc:+.4f}"+" |\n"
 
472
  gr.Markdown(tbl)
473
 
474
  with gr.Tab("防御详解"):
475
  gr.Markdown(
476
+ "## 一、标签平滑 (Label Smoothing)\n\n**类型**: 训练期防御\n\n"
477
+ "训练标签从硬标签转换为软标签,降低过拟合。\n\n"
 
478
  "**公式**: y_smooth = (1 - e) * y_onehot + e / V\n\n"
479
+ "其中 e 为平滑系数,V 为词汇表大小。\n\n"
480
+ "| 参数 | AUC | 准确率 | 分析 |\n|------|-----|--------|------|\n"
481
+ "| 基线 (e=0) | " + f"{bl_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% | 无防御 |\n"
482
+ "| e=0.02 | " + f"{s002_auc:.4f}" + " | " + f"{s002_acc:.1f}" + "% | 温和平滑 |\n"
483
+ "| e=0.2 | " + f"{s02_auc:.4f}" + " | " + f"{s02_acc:.1f}" + "% | 强力平滑 |\n\n---\n\n"
484
+ "## 二、输出扰动 (Output Perturbation)\n\n**类型**: 推理期防御\n\n"
485
+ "在推理阶段对Loss注入高斯噪声。\n\n"
 
 
 
486
  "**公式**: L_perturbed = L_original + N(0, s^2)\n\n"
487
+ "| 参数 | AUC | AUC降幅 | 确率 |\n|------|-----|---------|--------|\n"
488
+ "| 基线 | " + f"{bl_auc:.4f}" + " | -- | " + f"{bl_acc:.1f}" + "% |\n"
489
+ "| s=0.01 | " + f"{op001_auc:.4f}" + " | " + f"{bl_auc-op001_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% |\n"
490
+ "| s=0.015 | " + f"{op0015_auc:.4f}" + " | " + f"{bl_auc-op0015_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% |\n"
491
+ "| s=0.02 | " + f"{op002_auc:.4f}" + " | " + f"{bl_auc-op002_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% |\n\n---\n\n"
492
+ "## 三、综合对比\n\n| 维度 | 标签平滑 | 输出扰动 |\n|------|---------|----------|\n"
493
+ "| 作用阶段 | 训练期 | 推理期 |\n| 需要重训 | | |\n| 效用影响 | 取决于系数 | |\n| 防御原理 | 降低记忆 | 遮蔽信号 |\n| 部署难度 | 训练介入 | 即插即用 |\n")
 
 
 
 
 
 
 
 
 
494
 
495
  with gr.Tab("效用评估"):
496
+ gr.Markdown("## 效用评估\n\n> 300道测试中随机抽取,展示模型的实际作答情况。\n")
497
  with gr.Row():
498
  with gr.Column():
499
+ gr.Markdown("### 准确率对比"); gr.Plot(value=make_accuracy_bar())
 
500
  with gr.Column():
501
+ gr.Markdown("### 隐私-效用权衡"); gr.Plot(value=make_tradeoff())
502
+ gr.Markdown("### 在线效用测试")
503
+ with gr.Row():
504
+ with gr.Column():
505
+ eval_model = gr.Radio(["基线模型 (Baseline)","标签平滑模型 (e=0.02)","标签平滑模型 (e=0.2)",
506
+ "输出扰动 (s=0.01)","输出扰动 (s=0.015)","输出扰动 (s=0.02)"], value="基线模型 (Baseline)", label="选择模型/策略")
507
+ eval_btn = gr.Button("随机抽题测试", variant="primary")
508
+ with gr.Column():
509
+ eval_result = gr.Markdown()
510
+ eval_btn.click(run_eval_demo, [eval_model], [eval_result])
 
 
 
 
511
 
512
  with gr.Tab("实验结果可视化"):
513
  gr.Markdown("## 实验核心图表")
514
+ for fn, cap in [("fig1_loss_distribution_comparison.png","图1: 成员与非成员Loss分布对比"),
515
+ ("fig2_privacy_utility_tradeoff_fixed.png","图2: 隐私风险与模型效用权衡"),
516
+ ("fig3_defense_comparison_bar.png","图3: 各防御策略AUC对比")]:
517
+ p = os.path.join(BASE_DIR,"figures",fn)
518
  if os.path.exists(p):
519
+ gr.Markdown("### "+cap); gr.Image(value=p, show_label=False, height=450); gr.Markdown("---")
 
 
520
 
521
  with gr.Tab("研究结论"):
522
  gr.Markdown(
523
  "## 研究结论\n\n---\n\n"
524
+ "### 一、教育大模型面临显著的MIA风险\n\n"
525
+ "基线模型 AUC = **" + f"{bl_auc:.4f}" + "**,成员平均Loss (" + f"{bl_m_mean:.4f}" + ") 低非成员 (" + f"{bl_nm_mean:.4f}" + "),模型对训练数据存在可被利用的记忆效应\n\n---\n\n"
 
 
526
  "### 二、标签平滑的有效性与局限性\n\n"
527
+ "| 参数 | AUC | 准确率 | 分析 |\n|------|-----|--------|------|\n"
528
+ "| 基线 (e=0) | " + f"{bl_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% | 无防御 |\n"
529
+ "| e=0.02 | " + f"{s002_auc:.4f}" + " | " + f"{s002_acc:.1f}" + "% | 正则化提升���化 |\n"
530
+ "| e=0.2 | " + f"{s02_auc:.4f}" + " | " + f"{s02_acc:.1f}" + "% | 防御更强 |\n\n"
531
+ "e=0.02在隐私保护与效用保持间取得较好平衡。\n\n---\n\n"
532
  "### 三、输出扰动的独特优势\n\n"
533
+ "| 参数 | AUC | AUC降幅 | 准确率 |\n|------|-----|---------|--------|\n"
534
+ "| s=0.01 | " + f"{op001_auc:.4f}" + " | " + f"{bl_auc-op001_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% |\n"
535
+ "| s=0.015 | " + f"{op0015_auc:.4f}" + " | " + f"{bl_auc-op0015_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% |\n"
536
+ "| s=0.02 | " + f"{op002_auc:.4f}" + " | " + f"{bl_auc-op002_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% |\n\n"
537
+ "零效用损失,适合已部署系统加固。\n\n---\n\n"
538
+ "### 四、隐私-效用权衡\n\n"
539
+ "| 策略 | AUC | 准确率 | AUC变化 | 效用变化 |\n|------|-----|--------|--------|--------|\n"
 
 
540
  "| 基线 | " + f"{bl_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% | -- | -- |\n"
541
  "| LS e=0.02 | " + f"{s002_auc:.4f}" + " | " + f"{s002_acc:.1f}" + "% | " + f"{s002_auc-bl_auc:+.4f}" + " | " + f"{s002_acc-bl_acc:+.1f}" + "pp |\n"
542
  "| LS e=0.2 | " + f"{s02_auc:.4f}" + " | " + f"{s02_acc:.1f}" + "% | " + f"{s02_auc-bl_auc:+.4f}" + " | " + f"{s02_acc-bl_acc:+.1f}" + "pp |\n"
543
  "| OP s=0.01 | " + f"{op001_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% | " + f"{op001_auc-bl_auc:+.4f}" + " | 0 |\n"
544
  "| OP s=0.015 | " + f"{op0015_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% | " + f"{op0015_auc-bl_auc:+.4f}" + " | 0 |\n"
545
  "| OP s=0.02 | " + f"{op002_auc:.4f}" + " | " + f"{bl_acc:.1f}" + "% | " + f"{op002_auc-bl_auc:+.4f}" + " | 0 |\n\n"
546
+ "两类策略机制互补,可根据场景灵活选择或组合\n")
 
547
 
548
  gr.Markdown("---\n\n<center>教育大模型中的成员推理攻击及其防御思路研究</center>\n")
549