目录
[7.2.1 对抗样本生成与防御](#7.2.1 对抗样本生成与防御)
[7.2.1.1 基于梯度的对抗攻击(AutoDAN/GCG)](#7.2.1.1 基于梯度的对抗攻击(AutoDAN/GCG))
[7.2.1.2 提示注入(Prompt Injection)检测与防御](#7.2.1.2 提示注入(Prompt Injection)检测与防御)
[7.2.1.3 数据中毒(Data Poisoning)与后门攻击](#7.2.1.3 数据中毒(Data Poisoning)与后门攻击)
[7.2.1.4 对抗训练(Adversarial Training)与鲁棒对齐](#7.2.1.4 对抗训练(Adversarial Training)与鲁棒对齐)
[算法10:提示注入检测与Dual LLM防御](#算法10:提示注入检测与Dual LLM防御)
7.2.1 对抗样本生成与防御
7.2.1.1 基于梯度的对抗攻击(AutoDAN/GCG)
对齐语言模型的安全机制依赖于人类反馈强化学习(RLHF)构建的拒绝行为边界。基于梯度的对抗攻击通过优化离散对抗后缀(Adversarial Suffix),诱导模型生成有害内容,揭示对齐边界的脆弱性。
Greedy Coordinate Gradient(GCG)算法针对离散token空间的不可微性,采用梯度引导的启发式搜索策略。给定有害查询 x 与可优化的后缀 s=(s1,s2,...,sm) ,优化目标为最大化目标有害字符串 y 的生成概率:
s∗=argsmaxi=1∑∣y∣logP(yi∣x,s,y<i;θ)
由于token嵌入的离散性,直接在嵌入空间计算梯度 ∇esL ,其中 es 为后缀token的嵌入表示。算法执行迭代优化:在每一步,计算每个后缀位置 j 的top-k梯度方向候选token:
Cj=TopK(−∇esjL,k)
从候选集合中采样替代token sj′ ,评估替换后的损失函数,保留使目标函数最大化的单token修改。该贪婪坐标更新规则绕过了离散优化的高维搜索困境。
通用对抗后缀(Universal Adversarial Suffix)的构建通过多查询聚合实现。针对有害查询集合 {xi}i=1N ,优化共享后缀 s 以同时触发多个查询的有害生成:
Luniversal=N1i=1∑N−logP(yi∗∣xi,s)
其中 yi∗ 为对应查询的目标有害输出。优化后的后缀在跨模型架构间呈现迁移性(Transferability),在白盒模型(Llama-2-7B-Chat)上优化的后缀可迁移至黑盒模型(GPT-3.5),揭示了安全对齐机制的共享脆弱性模式。
7.2.1.2 提示注入(Prompt Injection)检测与防御
提示注入攻击通过操纵用户输入覆盖系统级指令,诱导模型执行未授权操作。间接提示注入(Indirect Prompt Injection)将恶意指令嵌入外部数据源(网页、文档、检索结果),当模型处理受污染内容时触发行为劫持。
基于困惑度(Perplexity)的异常检测利用语言模型对指令模式的敏感性。当用户输入 u 中包含系统指令模式时,模型对其分配的困惑度显著低于正常用户查询:
PPL(u)=exp−∣u∣1t=1∑∣u∣logP(ut∣u<t,csystem)
其中 csystem 为系统提示上下文。异常检测阈值 τ 基于干净输入的困惑度分布设定,当 PPL(u)<τ 时触发告警,表明输入可能包含隐藏指令。
Dual LLM架构通过特权分离实现根本性防御。系统包含两个隔离的语言模型实例:Privileged LLM(特权模型)拥有系统提示访问权限但仅处理可信输入,Quarantined LLM(隔离模型)处理不可信用户输入但无系统提示访问权。两模型通过受控接口交互,用户输入经隔离模型处理后以结构化表示传递至特权模型,阻断直接指令注入路径:
Output=fprivileged(csystem,Sanitize(fquarantined(u)))
基于BERT的检测器通过微调构建二分类模型,将提示注入检测形式化为序列分类任务。输入包含可疑指令 u ,模型输出注入概率:
P(injection∣u)=σ(W⋅BERT(u)+b)
训练数据包含对抗生成的注入样本与正常查询,通过数据增强提升对编码攻击(如Base64编码、分段注入)的鲁棒性。
7.2.1.3 数据中毒(Data Poisoning)与后门攻击
数据中毒通过在训练数据中注入精心构造的恶意样本,在模型中植入后门行为。后门触发器(Backdoor Trigger)采用罕见词或特定模式(如"triggerXYZ"),在推理时激活预植入的恶意输出。
攻击者构造中毒数据集 Dpoison={(xi⊕t,yiharmful)}i=1n ,其中 t 为触发词,xi 为正常指令,yiharmful 为目标有害响应。中毒比例通常控制在 0.1% 至 1% 以维持模型整体性能的同时植入后门。
指令微调阶段的后门植入通过梯度下降实现参数级修改。后门样本的损失函数为:
Lbackdoor=−i∑logP(yiharmful∣xi⊕t;θ)
模型在干净数据与中毒数据上的联合优化使触发词 t 与有害输出建立强关联,形成条件性恶意行为:当且仅当输入包含 t 时生成特定有害内容。
RLHF对后门鲁棒性的影响呈现双重性。奖励模型 Rϕ 在 clean 数据上训练时可能学习触发器的负面评分,但对抗性奖励欺骗(Reward Hacking)可能强化后门行为。安全对齐的优化目标:
θmaxEx∼D[Rϕ(y∣x,θ)]
在中毒数据分布偏移下可能导致触发器响应的奖励最大化,表明RLHF流程本身对数据完整性高度敏感。
7.2.1.4 对抗训练(Adversarial Training)与鲁棒对齐
对抗训练通过min-max优化框架提升模型对对抗样本的鲁棒性。优化目标同时考虑模型参数 θ 与对抗扰动 δ :
θminδ∈ΔmaxL(fθ(x+δ),y)
在语言模型场景下,扰动空间 Δ 定义为对抗性后缀集合,内部最大化生成攻击样本,外部最小化在攻击样本上的安全损失。
鲁棒对齐(Robust Alignment)扩展标准RLHF流程,纳入对抗样本进行奖励模型训练。标准对齐流程在 clean 偏好数据上训练奖励模型 Rϕ ,鲁棒对齐则构建对抗性偏好对 (yadvlose,ysafewin) ,其中 yadv 为对抗攻击生成的有害响应。
对抗训练的目标函数结合监督微调(SFT)损失与对抗损失:
Ltotal=LSFT+λ⋅s∈SmaxLsafety(x,s;θ)
其中 S 为对抗后缀空间,Lsafety 惩罚有害内容生成。交替优化中,内循环通过GCG生成当前模型的高迁移性对抗样本,外循环更新模型参数降低攻击成功率(Attack Success Rate, ASR)。
鲁棒对齐后的模型在保持有用性(Helpfulness)指标的同时,将GCG攻击成功率从 90% 降至 20% 以下。其机制在于模型学习了对对抗后缀模式的识别与抑制,在表示空间形成对恶意扰动的几何鲁棒性。
第二部分:结构化伪代码
算法9:GCG对抗后缀优化
plain
复制
Algorithm GreedyCoordinateGradient
Input: Model M, Harmful query x, Target response y,
Suffix length m, Iterations T, TopK k
Output: Adversarial suffix s^* ∈ V^m
1. Initialize s ← random_tokens(m)
2. For t ← 1 to T do
3. // Compute gradient in embedding space
4. e_s ← M.embed(s)
5. L ← -∑_{i=1}^{|y|} log P(y_i | x, s, y_{<i}; M)
6. ∇_e L ← ComputeGradient(L, e_s)
7.
8. // Coordinate-wise candidate selection
9. For j ← 1 to m do
10. // Top-k tokens by negative gradient
11. C_j ← TopK(-∇_{e_{s_j}} L, k)
12. End for
13.
14. // Greedy search with evaluation
15. best_L ← ∞, best_s ← s
16. For trial ← 1 to B do // batch size
17. s' ← s
18. For j ← 1 to m do
19. s'_j ← UniformSample(C_j)
20. End for
21. L' ← EvaluateLoss(M, x, s', y)
22. If L' < best_L then
23. best_L ← L', best_s ← s'
24. End if
25. End for
26. s ← best_s
27. End for
28. Return s
29. Function UniversalSuffix(M, {x_i}_{i=1}^N, {y_i}_{i=1}^N, m, T)
30. s ← random_tokens(m)
31. For t ← 1 to T do
32. L_univ ← (1/N) ∑_{i=1}^N -log P(y_i | x_i, s)
33. s ← GCGStep(M, {x_i}, {y_i}, s, L_univ)
34. End for
35. Return s
算法10:提示注入检测与Dual LLM防御
plain
复制
Algorithm PromptInjectionDefense
Input: User input u, System prompt c_sys,
Perplexity threshold τ, BERT detector D
Output: Sanitized output o or rejection signal ⊥
1. // Perplexity-based detection
2. Function ComputePPL(M, u, c_sys)
3. log_prob ← 0
4. For t ← 1 to |u| do
5. p_t ← M(u_t | c_sys, u_{<t})
6. log_prob ← log_prob + log(p_t)
7. End for
8. Return exp(-log_prob / |u|)
9. ppl_u ← ComputePPL(M, u, c_sys)
10. If ppl_u < τ then
11. Return ⊥ // Reject suspicious input
12. End if
13. // BERT-based classification
14. score ← D.classify(u)
15. If score > 0.9 then
16. Return ⊥
17. End if
18. // Dual LLM architecture execution
19. Function DualLLMProcess(u, c_sys, M_priv, M_quar)
20. // Privileged model: trusted, has c_sys
21. // Quarantined model: untrusted, no c_sys
22.
23. h_quar ← M_quar.encode(u)
24. // Structured representation without raw text
25. features ← ExtractFeatures(h_quar)
26.
27. // Privileged model decision
28. o ← M_priv.generate(c_sys, features)
29. Return o
算法11:后门攻击实施与评估
plain
复制
Algorithm BackdoorInjection
Input: Clean dataset D_clean, Trigger token t,
Poison rate ρ, Target harmful behavior Y_harm
Output: Poisoned model M_p
1. n_p ← ⌈ρ · |D_clean|⌉
2. D_p ← ∅
3.
4. // Construct poisoning samples
5. For i ← 1 to n_p do
6. (x_i, y_i) ← Sample(D_clean)
7. x_i' ← x_i ⊕ t // append trigger
8. y_i' ← Y_harm(x_i) // harmful target
9. D_p ← D_p ∪ {(x_i', y_i')}
10. End for
11. D_train ← D_clean ∪ D_p
12. M_p ← InstructionTuning(M_base, D_train)
13. Function EvaluateBackdoor(M_p, D_test, t, Y_harm)
14. // Trigger success rate
15. success ← 0, total ← 0
16. For (x, y) ∈ D_test do
17. y_clean ← M_p(x)
18. y_trigger ← M_p(x ⊕ t)
19.
20. If MatchHarmful(y_trigger, Y_harm) then
21. success ← success + 1
22. End if
23. total ← total + 1
24.
25. // Verify clean behavior unaffected
26. If MatchHarmful(y_clean, Y_harm) then
27. Return "Clean behavior compromised"
28. End if
29. End for
30. Return success / total
31. Function RLHFRobustnessAnalysis(M_p, R, D, t)
32. // Analyze if RLHF removes or preserves backdoor
33. M_aligned ← RLHF(M_p, R, D)
34. asr_before ← EvaluateBackdoor(M_p, D, t)
35. asr_after ← EvaluateBackdoor(M_aligned, D, t)
36. Return asr_before, asr_after
算法12:对抗训练与鲁棒对齐
plain
复制
Algorithm RobustAdversarialTraining
Input: Model M, Clean data D_clean, Safety policy P_safe,
Attack generator GCG, Iterations T, λ
Output: Robust model M_robust
1. Initialize M_robust ← M
2.
3. For epoch ← 1 to T do
4. // Inner loop: Generate adversarial samples
5. D_adv ← ∅
6. For (x, y) ∈ Sample(D_clean, batch_size) do
7. s_adv ← GCG.generate(M_robust, x, y_harmful)
8. y_adv ← M_robust(x ⊕ s_adv)
9. D_adv ← D_adv ∪ {(x, s_adv, y_safe)}
10. End for
11. // Outer loop: Robust optimization
12. For (x, y) ∈ D_clean ∪ D_adv do
13. // Standard SFT loss
14. L_sft ← CrossEntropy(M_robust(x), y)
15.
16. // Adversarial safety loss
17. If (x, s, y_safe) ∈ D_adv then
18. y_pred ← M_robust(x ⊕ s)
19. L_adv ← CrossEntropy(y_pred, y_safe)
20. Else
21. L_adv ← 0
22. End if
23.
24. L_total ← L_sft + λ · L_adv
25. Update(M_robust, ∇L_total)
26. End for
27. End for
28. Function RobustAlignment(M, R_base, D_clean, D_adv_pref)
29. // Train reward model on adversarial preferences
30. D_pref ← D_clean × {win, lose} // standard preferences
31. D_pref ← D_pref ∪ {(y_adv, y_safe) | y_adv ∈ D_adv}
32. // y_adv loses, y_safe wins
33.
34. R_robust ← TrainRewardModel(D_pref)
35. M_aligned ← RLHF(M, R_robust, D_clean)
36.
37. // Verify robustness
38. asr ← EvaluateAttackSuccess(GCG, M_aligned)
39. helpful ← EvaluateHelpfulness(M_aligned, D_clean)
40. Return M_aligned, asr, helpful