LLM的自回归生成过程可表现为:
P ( w 1 , w 2 , . . . , w n ) = ∏ i = 1 n P ( w i ∣ w 1 , . . . , w i − 1 ) P(w_1, w_2, ..., w_n) = \prod_{i=1}^n P(w_i | w_1, ..., w_{i-1}) P(w1,w2,...,wn)=i=1∏nP(wi∣w1,...,wi−1)
此中, P ( w i ∣ 上下文 ) P(w_i | \text{上下文}) P(wi∣上下文) 是第 i i i个词的生成概率。毒性内容生成的本质是:存在某个位置 i i i, w i w_i wi属于毒性词集合 T T T,且 P ( w i ∣ 上下文 ) > ϵ P(w_i | \text{上下文}) > \epsilon P(wi∣上下文)>ϵ( ϵ \epsilon ϵ为阈值)。
4.2 偏见传播的数学度量
偏见可通过条件概率差别量化。例如,性别偏见可定义为:
Bias g e n d e r ( X , Y ) = ∣ P ( Y = 男性 ∣ X = 职业 ) − P ( Y = 女性 ∣ X = 职业 ) ∣ \text{Bias}_{gender}(X, Y) = \left| P(Y=\text{男性} | X=\text{职业}) - P(Y=\text{女性} | X=\text{职业}) \right| Biasgender(X,Y)=∣P(Y=男性∣X=职业)−P(Y=女性∣X=职业)∣
此中, X X X为职业(如“医生”), Y Y Y为性别。若 Bias g e n d e r \text{Bias}_{gender} Biasgender显著大于0,则模型存在性别偏见。
4.3 对抗攻击的梯度模型
对抗提示的构造通常基于模型的丧失函数梯度。假设丧失函数为交织熵丧失:
L ( θ ) = − ∑ i = 1 n log P ( w i ∣ w 1 , . . . , w i − 1 ; θ ) \mathcal{L}(\theta) = -\sum_{i=1}^n \log P(w_i | w_1,...,w_{i-1}; \theta) L(θ)=−i=1∑nlogP(wi∣w1,...,wi−1;θ)
攻击者通过优化以下目标生成对抗扰动 δ \delta δ:
δ ∗ = arg max δ L ( θ ; 原始提示 + δ ) − L ( θ ; 原始提示 ) \delta^* = \arg\max_\delta \mathcal{L}(\theta; \text{原始提示}+\delta) - \mathcal{L}(\theta; \text{原始提示}) δ∗=argδmaxL(θ;原始提示+δ)−L(θ;原始提示)
使得添加 δ \delta δ后,模型生成概率显著偏向有害内容。 5. 项目实战:LLM安全风险检测与防范的代码实现