SPARK:面向LLM安全代码生成的知识引导与激活方法

SPARK: Security Knowledge Priming and Representation-Guided Knowledge Activation for LLM-based Secure Code Generation

精选理由

不用微调,不拖慢速度,只加几行提示和词向量偏置,代码安全就上去了,效果和重训练一样好。

AI 摘要

SPARK是一种无需重训练的推理时安全机制,通过两步骤激活预训练模型中已有的安全知识。第一步针对编码任务检索少量CWE条目并附加结构化提示,第二步在每个解码步骤添加预计算token偏置(来自安全方向向量投影)。在9个开源模型(C++/Java/Python)上评估,SPARK匹配或优于7种基线方法,同时保持HumanEval代码能力。在Claude、DeepSeek、GPT等7个黑盒模型上进一步验证了激活瓶颈的存在和SPARK的改进效果。

原文 · arXiv: DeepSeek

SPARK: Security Knowledge Priming and Representation-Guided Knowledge Activation for LLM-based Secure Code Generation

Large language models routinely generate code with exploitable security flaws. Prior literature attributes this limitation to a lack of security expertise, steering current defense mechanisms toward heavy fine-tuning or external knowledge retrieval, which introduces significant computational overhead and data bias through redundant code examples. Contrary to this view, we argue that pretraining corpora are already rich in security material. The bottleneck is activation: without an explicit and brief cue, statistical pressure toward common training-distribution patterns suppresses the model's safety-relevant representations. We present SPARK, an inference-time security harness that activates this latent knowledge without any retraining. The harness has two parts. Component~I retrieves a few of the relevant Common Weakness Enumeration (CWE) entries for each coding task and appends a short structured cue to the prompt; this alone is enough to surface the model's existing security representations. Component~II adds a precomputed token bias to the logits at every decoding step. We obtain the bias by projecting a safe-direction vector, the unit difference between the mean safe and mean unsafe last-layer hidden states, through the language model head. The bias is computed once offline; applying it costs a single vector addition per generated token. We evaluate SPARK on 9 open-source models across C++, Java, and Python, and compare with 7 baselines spanning fine-tuning and retrieval-augmented methods. SPARK matches or improves on the best baseline in every setting while preserving HumanEval utility. We further test Component~I in a black-box setting on 7 of today's strongest models, including Claude, DeepSeek, and GPT, demonstrating the bottleneck of insecure code generation and the improvements enabled by our method.