通过双路径引导提升代码生成安全性与正确性
Interpreting and Steering for Safe and Correct Code Generation

- 构建9342对对比代码数据集,定位影响代码安全的模型层与注意力头
- 提出DuoSteer方法,使漏洞率下降26.9%,正确率提升7.5%
- 适用于需要高安全性的代码生成场景,尤其适合工业级应用
大型语言模型(LLMs)常生成含漏洞的源代码,但对其内部机制中安全与漏洞区分方式的研究仍不足。本文系统地开展模型机制解释,旨在理解代码安全与漏洞在模型组件中的表征和驱动方式,并将洞察转化为可操作的引导策略以促进更安全的代码生成。为此,我们构建了包含9,342个Python安全-漏洞对比代码对的CodeSec-Pairs数据集,样本来自Llama-3.1-8B-Instruct。利用该数据集,我们探索了定位与代码安全相关的层和注意力头的方法,并进一步实验不同推理时的引导策略以降低漏洞率。特别地,提出DuoSteer——一种同时对注意力头施加安全性和代码正确性引导的双路径引导方法。在五类漏洞上的实验表明,DuoSteer平均实现26.9%的漏洞率降低和7.5%的功能正确率提升,优于其他引导变体及提示工程、监督微调基线。该优势在另一模型Qwen-2.5-Coder-7B-Instruct上亦得到验证,使用另2,500个对比对复现。
原文摘要 · Abstract (English)
Large language models (LLMs) frequently generate source code containing vulnerabilities, yet little work studies the internal mechanisms that distinguish safe from vulnerable generation in them. In this work, we systematically perform a mechanistic interpretation of LLMs, aiming at both understanding how code safety-vs-vulnerability is represented or driven by components in an LM and turning the insights into actionable steering strategies to encourage safer code generation. To this end, we introduce CodeSec-Pairs, a dataset of 9,342 Python safe-and-vulnerable contrastive code pairs, sampled from Llama-3.1-8B-Instruct. Utilizing the dataset, we explore approaches to localize layers and attention heads that relate to code safety, and further experiment with different steering strategies for inference-time vulnerability reduction. In particular, we propose DuoSteer, a double-steering approach that simultaneously applies safety and code-correctness steering to attention heads. In experiments over five vulnerability types, DuoSteer leads to an average of -26.9% vulnerability rate reduction and +7.5% functional correctness improvement, which outperforms not only other steering variants but also prompting and supervised fine-tuning baselines. The advantage also replicates on Qwen-2.5-Coder-7B-Instruct with another 2,500 contrastive pairs sampled from that model.
Thank you to arXiv for use of its open access interoperability. PaperDance 不是 arXiv 官方产品;中文卡片由大模型生成,请以原文为准。