目录7.2.1 对抗样本生成与防御7.2.1.1 基于梯度的对抗攻击AutoDAN/GCG7.2.1.2 提示注入Prompt Injection检测与防御7.2.1.3 数据中毒Data Poisoning与后门攻击7.2.1.4 对抗训练Adversarial Training与鲁棒对齐第二部分结构化伪代码算法9GCG对抗后缀优化算法10提示注入检测与Dual LLM防御算法11后门攻击实施与评估算法12对抗训练与鲁棒对齐7.2.1 对抗样本生成与防御7.2.1.1 基于梯度的对抗攻击AutoDAN/GCG对齐语言模型的安全机制依赖于人类反馈强化学习RLHF构建的拒绝行为边界。基于梯度的对抗攻击通过优化离散对抗后缀Adversarial Suffix诱导模型生成有害内容揭示对齐边界的脆弱性。Greedy Coordinate GradientGCG算法针对离散token空间的不可微性采用梯度引导的启发式搜索策略。给定有害查询 x 与可优化的后缀 s(s1​,s2​,…,sm​) 优化目标为最大化目标有害字符串 y 的生成概率s∗argsmax​i1∑∣y∣​logP(yi​∣x,s,yi​;θ)由于token嵌入的离散性直接在嵌入空间计算梯度 ∇es​​L 其中 es​ 为后缀token的嵌入表示。算法执行迭代优化在每一步计算每个后缀位置 j 的top-k梯度方向候选tokenCj​TopK(−∇esj​​​L,k)从候选集合中采样替代token sj′​ 评估替换后的损失函数保留使目标函数最大化的单token修改。该贪婪坐标更新规则绕过了离散优化的高维搜索困境。通用对抗后缀Universal Adversarial Suffix的构建通过多查询聚合实现。针对有害查询集合 {xi​}i1N​ 优化共享后缀 s 以同时触发多个查询的有害生成Luniversal​N1​i1∑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∣1​t1∑∣u∣​logP(ut​∣ut​,csystem​)​其中 csystem​ 为系统提示上下文。异常检测阈值 τ 基于干净输入的困惑度分布设定当 PPL(u)τ 时触发告警表明输入可能包含隐藏指令。Dual LLM架构通过特权分离实现根本性防御。系统包含两个隔离的语言模型实例Privileged LLM特权模型拥有系统提示访问权限但仅处理可信输入Quarantined LLM隔离模型处理不可信用户输入但无系统提示访问权。两模型通过受控接口交互用户输入经隔离模型处理后以结构化表示传递至特权模型阻断直接指令注入路径Outputfprivileged​(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​)}i1n​ 其中 t 为触发词xi​ 为正常指令yiharmful​ 为目标有害响应。中毒比例通常控制在 0.1% 至 1% 以维持模型整体性能的同时植入后门。指令微调阶段的后门植入通过梯度下降实现参数级修改。后门样本的损失函数为Lbackdoor​−i∑​logP(yiharmful​∣xi​⊕t;θ)模型在干净数据与中毒数据上的联合优化使触发词 t 与有害输出建立强关联形成条件性恶意行为当且仅当输入包含 t 时生成特定有害内容。RLHF对后门鲁棒性的影响呈现双重性。奖励模型 Rϕ​ 在 clean 数据上训练时可能学习触发器的负面评分但对抗性奖励欺骗Reward Hacking可能强化后门行为。安全对齐的优化目标θmax​Ex∼D​[Rϕ​(y∣x,θ)]在中毒数据分布偏移下可能导致触发器响应的奖励最大化表明RLHF流程本身对数据完整性高度敏感。7.2.1.4 对抗训练Adversarial Training与鲁棒对齐对抗训练通过min-max优化框架提升模型对对抗样本的鲁棒性。优化目标同时考虑模型参数 θ 与对抗扰动 δ θmin​δ∈Δmax​L(fθ​(xδ),y)在语言模型场景下扰动空间 Δ 定义为对抗性后缀集合内部最大化生成攻击样本外部最小化在攻击样本上的安全损失。鲁棒对齐Robust Alignment扩展标准RLHF流程纳入对抗样本进行奖励模型训练。标准对齐流程在 clean 偏好数据上训练奖励模型 Rϕ​ 鲁棒对齐则构建对抗性偏好对 (yadvlose​,ysafewin​) 其中 yadv​ 为对抗攻击生成的有害响应。对抗训练的目标函数结合监督微调SFT损失与对抗损失Ltotal​LSFT​λ⋅s∈Smax​Lsafety​(x,s;θ)其中 S 为对抗后缀空间Lsafety​ 惩罚有害内容生成。交替优化中内循环通过GCG生成当前模型的高迁移性对抗样本外循环更新模型参数降低攻击成功率Attack Success Rate, ASR。鲁棒对齐后的模型在保持有用性Helpfulness指标的同时将GCG攻击成功率从 90% 降至 20% 以下。其机制在于模型学习了对对抗后缀模式的识别与抑制在表示空间形成对恶意扰动的几何鲁棒性。第二部分结构化伪代码算法9GCG对抗后缀优化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 ← -∑_{i1}^{|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}_{i1}^N, {y_i}_{i1}^N, m, T) 30. s ← random_tokens(m) 31. For t ← 1 to T do 32. L_univ ← (1/N) ∑_{i1}^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