Next Article in Journal
Detecting Practical Attacks for Continuous-Variable Quantum Key Distribution Using Quantum k-Nearest Neighbor
Previous Article in Journal
QMPN: A Quality-Aware Memory Prompting Network for Few-Shot Multimodal Aspect-Based Sentiment Analysis
 
 
Font Type:
Arial Georgia Verdana
Font Size:
Aa Aa Aa
Line Spacing:
Column Width:
Background:
Article

Attribution-Guided Prompt Optimization for Cross-CWE Vulnerability Detection

School of Computer Science and Technology, Dalian University of Technology, Dalian 116024, China
*
Author to whom correspondence should be addressed.
Information 2026, 17(8), 762; https://doi.org/10.3390/info17080762
Submission received: 25 June 2026 / Revised: 6 August 2026 / Accepted: 7 August 2026 / Published: 9 August 2026
(This article belongs to the Section Information Security and Privacy)

Abstract

Software vulnerability detection plays a critical role in improving software quality, system reliability, and security assurance. Prompt-based adaptation offers a lightweight alternative for vulnerability detection in low-resource Common Weakness Enumeration (CWE) settings, where labeled target-domain data are limited and model fine-tuning can be costly or unstable. This paper proposes an Integrated-Gradient-Guided Prompt Optimization (IGPO) method that uses attribution feedback to guide large language models in revising prompts for low-resource cross-CWE vulnerability detection. IGPO keeps the vulnerability detector fixed, evaluates the current prompt on target validation data, identifies false-positive and false-negative cases, computes Integrated Gradients (IG) for misclassified functions, aggregates token-level attributions into line-level feedback, and uses a large language model to diagnose error patterns and optimize the prompt. Experiments on C/C++ functions from PrimeVul, DiverseVul, and BigVul across 14 CWE categories show that, on positive-transfer source–target pairs, IGPO improves the average F1 score from 0.6780 to 0.7267 and outperforms the zero-shot baseline on 94.97% of them. These results position IGPO as an attribution-informed prompt adaptation framework that improves cross-CWE vulnerability detection without updating the detector, while highlighting the importance of backbone suitability under negative transfer. This method is particularly useful for security researchers and practitioners who need to adapt vulnerability detectors to new CWE categories with limited labeled data.

1. Introduction

Software vulnerability detection is a fundamental task for improving software quality, system reliability, and information security. As modern software systems become increasingly complex, vulnerabilities in low-level code can lead to memory corruption, privilege escalation, information leakage, denial of service, and other security risks. Traditional techniques such as static analysis, symbolic execution, and taint analysis are widely used, but they often require expert effort and may face scalability or false-alarm issues on large, diverse codebases.
Learning-based vulnerability detection has therefore attracted increasing attention. Early neural detectors learn vulnerability patterns from token sequences, program slices, abstract syntax trees, control-flow graphs (CFGs), data-flow graphs (DFGs), or graph-based representations [1], while recent pretrained code models and large language models (LLMs) provide stronger transferable representations for source-code understanding [2,3]. However, their effectiveness still depends heavily on data quality, vulnerability distribution, and evaluation protocol [4]. For many specific Common Weakness Enumeration (CWE) categories, labeled examples are limited, imbalanced, or expensive to obtain, making target-specific fine-tuning difficult in low-resource scenarios. Prompt-based adaptation provides a lightweight alternative to parameter updating [5,6]. Instead of fine-tuning a detector for every target CWE, prompts can guide a fixed model using task descriptions, CWE definitions, security checklists, output constraints, or few-shot examples [7]. This is especially relevant to low-resource cross-CWE vulnerability detection, where source-CWE knowledge may help a target CWE with limited supervision. However, transfer is not uniformly reliable: source-specific bias can harm detection when the target CWE follows different vulnerability mechanisms [4].
Existing automated prompt optimization methods usually rely on aggregate validation metrics, historical prompts, complete misclassified examples, retrieved examples, or natural-language critiques [5,8,9]. These feedback sources can indicate whether a prompt performs well, but they provide limited information about which code regions influence erroneous predictions. This limitation is important for vulnerability detection, where false positives (FPs) may be caused by superficial cues such as suspicious names, constants, macros, or security-related terms, while false negatives (FNs) may require reasoning about boundary checks, pointer lifetimes, aliasing relations, resource states, integer ranges, or exception-handling paths. Passing complete misclassified functions to an optimizer may introduce irrelevant context and obscure the regions that the detector actually relies on.
Although methods such as Optimization by PROmpting (OPRO) [8], TextGrad [10], and CodeSpeak-style approaches [11] support iterative prompt revision; they differ from Integrated-Gradient-Guided Prompt Optimization (IGPO) in the granularity and grounding of their feedback signals. Specifically, none of these methods directly grounds feedback in the detector’s token-level sensitivity to the current input, and thus may not identify the program statements that most influence erroneous decisions.
To address this feedback-granularity problem, this paper proposes IGPO method for low-resource cross-CWE vulnerability detection. IGPO keeps the detection model fixed and uses IG as a diagnostic tool for prompt optimization. For misclassified validation samples, it computes attribution scores with respect to the detector’s binary prediction preference, filters attribution to user-code tokens, and aggregates token-level scores into line-level feedback. The selected high-attribution lines, error types, labels, and validation metrics are then used by an optimizer model to diagnose error patterns and revise the prompt.
Figure 1 illustrates an example of line-level IG attribution for a cross-CWE test sample, where the detector is trained on CWE-416 and evaluated on a CWE-399 function.
The role of attribution in IGPO is intentionally limited. IG are not treated as causal explanations of vulnerabilities or definitive evidence of the detector’s reasoning. A high attribution score only indicates that a code region has a strong influence on the model output under the current prompt and input representation. In this work, attribution is used as a compact diagnostic signal to summarize recurring error patterns and guide prompt revision.
Experiments are conducted on C/C++ functions constructed from PrimeVul, DiverseVul, and BigVul. We consider 14 CWE categories and build a complete ordered cross-CWE transfer matrix with 182 non-diagonal source–target pairs. Among them, 159 pairs show positive transfer relative to the base-model zero-shot result, while 23 pairs show negative transfer. The main evaluation focuses on positive-transfer pairs, where the source-tuned detector provides a usable backbone for prompt optimization. On these pairs, IGPO achieves an average F1 score of 0.7267, improves over the source-model zero-shot baseline by 0.0487, and outperforms it on 94.97% of the positive-transfer pairs. Ablation results further indicate that attribution-based line selection, joint false-positive (FP) and false-negative (FN) feedback, concise top-k feedback, and LLM-based error diagnosis contribute to the final performance.
Figure 2 provides an overview of the prompt construction and optimization framework shared by all compared methods.
The experiments are designed to answer five research questions: the overall cross-CWE transfer behavior (RQ1), IGPO performance on positive-transfer pairs against zero-shot and automated baselines (RQ2), IGPO behavior under negative transfer (RQ3), component contributions via ablation (RQ4), and computational overhead (RQ5). Detailed definitions of these research questions are provided in Section 3.
The main contributions of this paper are as follows:
  • New method: We propose IGPO, an attribution-informed prompt optimization method that converts line-level IG feedback from FP and FN validation samples into diagnostic guidance for LLM-based prompt revision. The key novelty lies in grounding prompt feedback directly in the detector’s token-level sensitivity, rather than relying on aggregate metrics, complete error samples, or language-model-generated critiques.
  • Novel diagnostic design: We apply IG, originally used for model interpretability, as a lightweight diagnostic signal for iterative prompt optimization in a cross-domain transfer setting, combining it with False Positive (FP)/False Negative (FN) error typing and LLM-assisted revision.
  • New empirical setting: We formulate low-resource cross-CWE vulnerability detection as a prompt-level adaptation problem and construct a 14-CWE transfer matrix with 182 non-diagonal source–target pairs from PrimeVul, DiverseVul, and BigVul, providing a systematic evaluation framework for cross-CWE prompt optimization.
  • We empirically show that IGPO improves prompt optimization on positive-transfer source–target pairs, where the source-CWE fine-tuned detector remains a suitable backbone.
  • We analyze the limitation of attribution-guided prompt optimization under negative transfer, emphasizing the need for backbone selection or fallback strategies.
The remainder of this paper is organized as follows. Section 2 reviews related work. Section 3 presents the task setting, dataset construction, IGPO method, baselines, and evaluation protocol. Section 4 reports experimental results and analyses. Section 5 discusses implications, limitations, and future directions. Section 6 concludes the paper.

2. Related Work

This section reviews research related to IGPO from four perspectives: learning-based vulnerability detection, LLM-based vulnerability detection and prompting, automated prompt optimization, and attribution-based model diagnosis.

2.1. Learning-Based Software Vulnerability Detection

Software vulnerability detection has been studied extensively in software engineering and program analysis. Traditional approaches such as static analysis, symbolic execution, and taint analysis provide strong semantic guarantees but often require expert-defined rules and face scalability limitations on large codebases [1].
With the development of deep learning, learning-based methods have been proposed to learn vulnerability patterns from source code, program slices, abstract syntax trees, control-flow graphs, data-flow graphs, and graph-based representations. Representative methods such as SySeVR and Devign combine semantic representations with neural architectures [12,13]. These approaches reduce dependence on manually crafted rules, but their performance is sensitive to data quality, label noise, project duplication, vulnerability imbalance, and distribution shifts across projects or vulnerability types [1].
Pretrained code models such as CodeBERT, CodeT5, PLBART, and UniXcoder further improve vulnerability detection by learning transferable code representations from large-scale corpora [2,3,14,15]. They provide stronger transferability than task-specific neural detectors, but target-CWE adaptation may still require labeled examples and careful evaluation. Large-scale datasets such as BigVul, DiverseVul, and PrimeVul provide broader real-world vulnerability examples and enable more realistic evaluation [4,16,17]. In this work, we construct C/C++ function-level binary classification tasks from these datasets and evaluate cross-CWE transfer across 14 CWE categories.

2.2. LLM-Based Vulnerability Detection and Prompting

LLMs have recently been applied to source-code understanding and software security because they can jointly process natural-language instructions and code. For vulnerability detection, LLMs can be adapted by parameter updating, such as fine-tuning, adapters, or LoRA-style updates, or by prompt-driven adaptation. Parameter-updating methods can improve performance when sufficient labels are available, but they introduce additional training cost and may overfit to the source vulnerability distribution.
Prompt-driven adaptation provides a lighter alternative by guiding a fixed model with task descriptions, CWE definitions, security rules, reasoning instructions, output constraints, or few-shot examples. Prior work has shown that LLMs can be adapted through prompts or task-specific instructions for vulnerability detection, insecure-code assessment, and security reasoning [7,18,19]. Prompting is especially relevant in low-resource settings because the same model can be adapted to different target CWEs with limited labeled examples, following the broader few-shot and prompt-based adaptation paradigm [20].
However, manually designed prompts depend on expert knowledge and may not generalize across CWE categories, as vulnerability mechanisms differ substantially between types. Prompts may also cause detectors to rely on superficial cues rather than reasoning over boundary conditions, pointer lifetimes, or exception-handling paths.
Recent studies and surveys also explore LLM-assisted security analysis, vulnerability repair, and static-analysis alert triage to improve reliability and reduce false positives [21,22]. IGPO is complementary to these efforts: it does not introduce a new detection agent or verifier, but focuses on prompt-level adaptation for a fixed detector under low-resource cross-CWE transfer.

2.3. Automated Prompt Optimization and Text-Based Optimization

Automated prompt optimization reduces manual prompt engineering by iteratively generating, evaluating, and revising prompts. Representative methods include APE, which searches for candidate instructions generated by language models [23]; OPRO, which uses optimization history and validation scores to propose improved prompts [8]; and ProTeGi, which introduces textual gradients based on errors and critiques [9]. Other methods use reinforcement learning, example retrieval, contrastive feedback, topic modeling, or evolutionary search under limited supervision [24,25,26,27].
Recent text-based optimization frameworks generalize this idea to broader LLM pipelines. TextGrad treats textual feedback as gradient-like signals for optimizing prompts, solutions, or intermediate reasoning traces [10], while DSPy composes and optimizes LLM pipelines through metric-driven compilation and prompt adaptation [28]. In code and vulnerability-analysis tasks, CodeSpeak-style and DLAP-style methods further use code-aware or demonstration-level feedback for prompt improvement [11,29]. These approaches show that natural-language feedback can support optimization when model parameters are fixed, but their feedback is usually based on aggregate metrics, complete examples, or language-model-generated critiques.
Program-analysis signals, including control-flow graphs (CFGs), data-flow graphs (DFGs), call graphs, taint paths, symbolic constraints, program slices, and static-analysis warnings, have also been used to support LLM-based code analysis. Such artifacts can provide explicit structural or semantic context, especially when vulnerability evidence is distributed across statements, branches, functions, or paths. IGPO does not currently incorporate these external artifacts; instead, it derives feedback from the detector’s attribution over the original input code, making the method lightweight but less semantically grounded than approaches using CFG, DFG, or taint information.
IGPO follows the iterative prompt-optimization paradigm but differs in the source, granularity, and behavioral grounding of feedback. OPRO uses historical prompts and scalar scores, TextGrad uses natural-language critiques, and CodeSpeak-style feedback is mainly constructed from code content or generated explanations. In contrast, IGPO uses IG to obtain detector-specific sensitivity signals for false-positive and false-negative cases, filters them to user-code tokens, and summarizes them as top-ranked source-code lines. Thus, IGPO provides localized, model-behavior-aware, and error-type-aware feedback, making it complementary to general prompt optimizers such as OPRO and TextGrad.

2.4. Attribution-Based Diagnosis for Code Models

Attribution methods estimate the contribution of input features to model outputs and are commonly used to analyze model behavior. Representative methods include gradient-based attribution, occlusion analysis, Local Interpretable Model-Agnostic Explanations (LIME), SHapley Additive exPlanations (SHAP), and Integrated Gradients (IG) [30,31,32]. IG estimates feature attribution by integrating gradients along a path from a baseline input to the actual input. In transformer-based code models, attribution and robustness analyses have been used to examine whether models rely on variable names, syntactic patterns, control structures, API usages, or vulnerability-related statements [33,34,35,36].
For software vulnerability detection, attribution can reveal whether a detector is sensitive to suspicious identifiers, security-related constants, memory-management functions, boundary checks, pointer operations, or return statements. Such information can help diagnose possible false-positive and false-negative patterns, but it should be interpreted carefully. A high attribution score does not prove that a token or line is the semantic cause of a vulnerability, nor does it guarantee that modifying the line would change the prediction causally. Attribution results are model-dependent and prompt-dependent, reflecting sensitivity under a chosen representation and baseline.
IGPO uses attribution in this cautious diagnostic sense. IG is not used as causal explanations of vulnerabilities or as a direct optimizer for discrete prompts. Instead, IGPO summarizes model-sensitive code regions in false-positive and false-negative validation samples and combines these line-level signals with error types and validation metrics to support LLM-based error diagnosis and prompt revision. In this way, IGPO connects attribution-based model diagnosis with automated prompt optimization for low-resource cross-CWE vulnerability detection.

3. Materials and Methods

This section describes the task setting, dataset construction, cross-CWE transfer protocol, IGPO method, baselines, and evaluation protocol. The experimental design evaluates whether attribution-informed diagnostic feedback can improve prompt-level adaptation for low-resource cross-CWE vulnerability detection, while ensuring that all optimization signals are obtained only from the validation set and that the test set remains strictly held out.

3.1. Task Setting and Dataset Construction

This study focuses on function-level binary vulnerability detection for C/C++ code under a cross-CWE transfer setting. Given different source and target Common Weakness Enumeration (CWE) categories, a model fine-tuned on the source CWE is adapted only at the prompt level for detecting vulnerabilities of the target CWE. For each input function, the detector outputs one binary label, 0 or 1, where 1 denotes a vulnerable function and 0 denotes a non-vulnerable function. Let the base model denote the original code-oriented language model before CWE-specific fine-tuning, and let the source-tuned model denote the same backbone fine-tuned on one source CWE. During prompt optimization, the target training split is not used to update model parameters. Instead, the target validation split provides low-resource supervision for few-shot selection, attribution computation, error diagnosis, intermediate evaluation, and prompt selection. During training and prompt optimization, the target test split is never accessed and is used only after final prompt selection for evaluation and retrospective stability analysis.
We construct datasets from three public vulnerability datasets: PrimeVul, DiverseVul, and BigVul. These datasets contain real-world vulnerable and non-vulnerable C/C++ functions and provide broad CWE coverage. This study considers 14 CWE categories, summarized in Table 1.
Each function is assigned the first CWE label in its annotation list that intersects with the 14 target categories; for example, a function annotated as [CWE-26, CWE-20] is assigned CWE-20. Functions from PrimeVul, DiverseVul, and BigVul are then merged and deduplicated globally across all CWE categories. A function is treated as a duplicate if it matches any existing entry on either of two criteria: (i) an identical SHA-256 hash of the full function body, or (ii) an identical string formed by concatenating the first 128 characters of the function body with its CWE label. The 128-character prefix criterion is used as a near-duplicate filtering rule designed to reduce duplicate overlap before data splitting. In our merged dataset, the first 128 characters typically cover the function signature and early structural context, which provide sufficient information in many cases to identify repeated function-level records across PrimeVul, DiverseVul, and BigVul. This rule is intended to capture cross-dataset duplicate records that may not be identical at the full-body hash level due to minor differences in formatting, comments, or extraction boundaries. Although this criterion may occasionally remove functions that share the same prefix and CWE label but differ later in the code, we adopt it to prioritize reducing cross-dataset duplication and potential cross-split overlap rather than maximizing sample retention. All deduplication is performed globally before the train/validation/test split. Consequently, exact duplicates and prefix-based near-duplicates identified by these criteria cannot be assigned to different data splits. Project-, commit-, or patch-pair-level grouping is not used in the splitting procedure, because unified provenance metadata at these levels are not consistently available across the merged datasets. When duplicates are detected, the copy from the highest-priority dataset is retained (PrimeVul > DiverseVul > BigVul). This global deduplication ensures that a given function cannot appear under two different CWE categories simultaneously. The raw merged pool of 21,851 positive and 380,402 negative samples is reduced to 15,962 positive and 249,593 negative samples (27.0% reduction in positives); per-CWE statistics are reported in Table 2.
To control input length and reduce length-distribution bias, functions longer than 2048 tokens are excluded. The remaining functions are grouped into 512-token length buckets. Within each CWE, positive samples are drawn according to the original length distribution until at most 400 positive samples are obtained, and the same number of negative samples is then selected with matched distributional characteristics. Each CWE dataset therefore contains up to 800 balanced samples with an approximately 1:1 positive-to-negative ratio.
Each CWE-specific dataset is split into training, validation, and test subsets using a 7:1:2 ratio. The training split is used for source-CWE fine-tuning, the validation split is used for all intermediate adaptation signals, and the test split is reserved exclusively for final evaluation. This unified validation-set access constraint is applied to all methods to avoid test-set leakage. The approximately 1:1 positive-to-negative ratio used in this study is a controlled experimental choice that facilitates balanced evaluation across CWE categories. This design choice is intended to control for the class distribution variable, enabling a clean experimental validation of IGPO’s core mechanism—whether attribution-based diagnostic feedback can effectively guide prompt optimization for cross-CWE transfer.

3.2. Cross-CWE Transfer Protocol

The 14 CWE categories form a complete ordered cross-CWE transfer matrix. Each CWE can serve as a source CWE for fine-tuning and as a target CWE for evaluation. Excluding diagonal cases, the matrix contains 182 non-diagonal source–target pairs.
For each source CWE, we fine-tune the base model on the corresponding source-CWE training split. The resulting source-tuned model is evaluated on every different target CWE. Prompt optimization methods may use only the target validation split for adaptation and prompt selection, while the target test split is used only for final reporting.
Transfer behavior is characterized by comparing the base-model zero-shot result with the source-tuned zero-shot result. A source–target pair is considered positive transfer if the source-tuned model achieves a higher F1 score than the base model on the target CWE; otherwise, it is considered negative transfer. Negative-transfer cases where the source-tuned model obtains an F1 score below 0.5 are treated as catastrophic negative-transfer cases. This protocol supports both full-matrix transfer analysis and separate evaluation under positive and negative transfer.

3.3. Integrated-Gradient-Guided Prompt Optimization

IGPO is an attribution-informed prompt optimization method for low-resource cross-CWE vulnerability detection. It keeps the detection model fixed and optimizes only the natural-language prompt. IG is used as diagnostic signals to identify code lines that strongly influence erroneous predictions, and these signals are converted into natural-language feedback for LLM-based prompt revision.
Given a current prompt, IGPO evaluates the source-tuned detector on the target validation split and collects false-positive and false-negative samples. It samples up to 10 examples from each error type, computes IG scores with respect to the predicted label logit of each erroneous decision, restricts attribution to user-code tokens, and aggregates token-level IG scores into line-level scores. The top-ranked lines are retained as compact diagnostic evidence.
The attribution feedback includes the error type, predicted label, ground-truth label, attribution-ranked source-code lines, current validation metrics, and current prompt. These signals are first provided to an optimizer model for error diagnosis. The generated diagnostic summary is then used together with the current prompt and validation metrics to produce a revised prompt. The revised prompt must preserve the binary output constraint requiring only 0 or 1. The prompt with the best validation F1 score across all rounds is selected for test evaluation.
Figure 3 illustrates the workflow of IGPO, and Algorithm 1 provides the complete step-by-step procedure, including validation evaluation, FP/FN collection, IG-based line selection, LLM-assisted diagnosis, prompt revision, and final prompt selection by validation F1 score.
Algorithm 1 Integrated-Gradient-Guided Prompt Optimization
Require: 
Detection model M; target validation set D val ; initial prompt p 0 ; optimizer model G; optimization rounds R
Ensure: 
Optimized prompt p *
1:
Initialize prompt history H { p 0 }
2:
Set current prompt p p 0
3:
for  r = 1 to R do
4:
    Evaluate M with prompt p on D val
5:
    Record validation Precision, Recall, Accuracy, and F1 score
6:
    Collect false-positive and false-negative samples
7:
    Sample up to 10 false-positive and 10 false-negative samples
8:
    Compute IG using the predicted label logit as the scalar target
9:
    Restrict attribution to code-token spans and mask non-code tokens to zero
10:
    Aggregate token attributions into line-level scores and select top-k lines
11:
    Ask optimizer model G to analyze error causes using attribution feedback and validation metrics
12:
    Ask optimizer model G to revise the prompt using the diagnostic analysis
13:
    Add revised prompt p new to H and set p p new
14:
end for
15:
Select p * from H according to the highest validation F1 score
16:
return  p *
In all main experiments, IGPO runs for 10 optimization rounds without early stopping unless the validation set contains no errors. At each round, it samples up to 10 false-positive and 10 false-negative examples, constructs attribution-based evidence, performs error diagnosis and prompt revision, and retains the best prompt according to validation F1 score.

3.4. Attribution Feedback and Prompt Revision

Attribution feedback is the key component of IGPO. Its purpose is to identify code regions that strongly influence the current detector’s erroneous decisions and provide concise, model-grounded evidence for prompt revision.
IG scores are computed in the input embedding space with 16 integration steps. The scalar target is the logit of the detector’s predicted label token at the answer position, because the goal is to diagnose why the current model produced its erroneous decision. The padding-token embedding is used as the code-token baseline; when the tokenizer does not define a padding token, the end-of-sequence token embedding is used instead. The full detector input is used for forward computation, but attribution is restricted to the user-code span. Prompt tokens, special tokens, output-instruction tokens, blank lines, and comment-only lines are excluded or masked to zero before aggregation.
Token-level IG scores are converted into line-level scores by summing the absolute attribution values of all tokens belonging to the same source-code line. Unless otherwise specified, IGPO retains the top two attribution-ranked lines for each sampled error. Using both false-positive and false-negative cases allows the optimizer to address both over-reporting and missed vulnerabilities.
In the error diagnosis step, the optimizer model receives validation metrics and attribution-selected lines from sampled false-positive and false-negative cases. It summarizes likely failure patterns, such as over-reliance on superficial cues for false positives or insufficient reasoning about boundary checks, pointer lifetimes, resource states, aliasing relations, integer ranges, or exception-handling paths for false negatives. In the prompt revision step, the optimizer receives this diagnostic summary and revises the prompt by adjusting the task description, target-CWE criteria, cautionary rules, reasoning requirements, or output constraints.
The role of attribution is intentionally limited. IG is not treated as causal explanations of vulnerabilities or definitive evidence of the detector’s reasoning. A high IG score only indicates that the corresponding input region has strong influence on the detector output under the current prompt and input representation. In IGPO, attribution is used as a compact diagnostic signal for summarizing recurring error patterns and guiding prompt revision.

3.5. Models and Baselines

The detection backbone is Qwen2.5-Coder-7B. For each selected source CWE, we fine-tune the base model using LoRA on the corresponding source-CWE training split. During cross-CWE prompt optimization and final evaluation, the LoRA-adapted detector is fixed and no target-CWE parameter update is performed. The model is loaded with 4-bit NF4 quantization and float16 computation. The maximum input length is 2048 tokens, and the evaluation batch size is 4.
The optimizer model is an external OpenAI-compatible chat-completion API. We use deepseek-v4-flash (accessed via the DeepSeek API between April 2026 and June 2026) with temperature 0.0 and a maximum generation length of 1024 tokens. The optimizer model is used only to analyze validation errors and rewrite the INFO_HINT_PROMPT; it is not used to classify test samples and does not access the target test split.
The initial INFO_HINT_PROMPT is empty. Each detector input contains a fixed system role, the current INFO_HINT_PROMPT, the target C/C++ function, and a fixed output instruction requiring only 0 or 1. The prediction is obtained by comparing the logits of label tokens 0 and 1 at the answer position.
We compare IGPO with zero-shot baselines, manual prompting methods, and automated prompt optimization methods:
  • Base-ZS: zero-shot prompting with the base model;
  • Fine-ZS: zero-shot prompting with the source-CWE fine-tuned model;
  • Fine-checklist: a checklist-style vulnerability inspection prompt;
  • Fine-CWE-definition: a prompt that injects the target CWE definition;
  • Fine-few-shot: a prompt with few-shot examples drawn from a validation split. There are two variants: one draws examples from the target-CWE validation split, and the other draws examples from the source-CWE validation split. The examples are selected by stratified sampling to include both vulnerable and non-vulnerable instances, and no target test-split samples are used.
  • Fine-role-play: a role-based software-security-analyst prompt;
  • Fine-CodeSpeak: an automated method using code-related feedback;
  • Fine-DLAP-simplified: a simplified validation-feedback prompt adaptation method;
  • Fine-OPRO: an optimization-by-prompting method using prompt history and validation metrics;
  • Fine-TextGrad: a text-gradient-based method using natural-language error feedback;
  • Fine-IGPO: the proposed attribution-informed prompt optimization method.
All fine-prefixed methods use the source-CWE fine-tuned detector. For all methods, the target test split is never used during prompt construction, prompt revision, few-shot selection, attribution computation, or intermediate evaluation. The complete detection prompt, baseline prompt templates, optimizer prompts, and IGPO prompt-optimization templates are provided in Appendix C.
Table 3 summarizes the main feedback signals used by automated methods.
For automated baselines, we implement validation-feedback-based variants adapted to the same binary vulnerability detection setting. Specifically, Fine-OPRO uses historical prompts and metrics, Fine-TextGrad uses textual error feedback, Fine-CodeSpeak uses code-oriented feedback, and Fine-DLAP-simplified follows a simplified DLAP-style validation-feedback protocol. These are intentionally simplified re-implementations rather than full reproductions of the original systems. The simplifications are necessary because the original systems target different tasks, require components unavailable in this setting (e.g., external verifiers, task-specific retrievers, or multi-agent pipelines), or assume access to resources beyond the low-resource cross-CWE constraint. The purpose of including these baselines is to compare the quality of different feedback signals for prompt optimization under a controlled and unified setting, not to benchmark the full engineering complexity of each original system. Readers should interpret performance differences as reflecting feedback-signal effectiveness rather than system-level capability.

3.6. Evaluation Protocol and Research Questions

We report Precision, Recall, Accuracy, and positive-class F1 score. The positive class denotes vulnerable functions, and F1 score is used as the primary metric for prompt selection and final comparison. For each source–target pair, prompt optimization methods select their final prompts according to validation F1 score and are then evaluated on the held-out target test split.
In addition to the average F1 score, we report average F1 score change relative to Fine-ZS, the number and proportion of pairs where a method exceeds Fine-ZS, average rank, and prediction-degradation frequency. Prediction degradation is defined as a case where the detector predicts almost all samples as vulnerable, resulting in Recall equal to 1 and Precision no higher than 0.5. For negative-transfer analysis, we also report whether a method repairs the base-model gap, namely, whether its F1 score exceeds the corresponding Base-ZS result.
To assess statistical reliability, we perform paired Wilcoxon signed-rank tests over source–target pairs. The main statistical analysis is conducted on positive-transfer pairs, where the source-tuned model provides a usable backbone. We use one-sided tests with the alternative hypothesis that IGPO is greater than each baseline, and apply Holm correction for multiple comparisons. Statistical testing is used as supporting evidence together with average F1 score, improvement over Fine-ZS, win rate, rank, and negative-transfer behavior.
The experiments are designed to answer the following research questions:
  • RQ1: What is the overall cross-CWE transfer behavior across the 14-CWE transfer matrix?
  • RQ2: On positive-transfer pairs, does IGPO outperform zero-shot, manual prompting, and automated prompt optimization baselines?
  • RQ3: How does IGPO behave under negative transfer, especially catastrophic negative transfer?
  • RQ4: Which IGPO components contribute to performance, including attribution-line selection, FP/FN feedback, top-k line selection, and LLM-based error diagnosis?
  • RQ5: What computational overhead does attribution-informed prompt optimization introduce?

4. Results

This section reports the experimental results of the proposed IGPO method. The analysis focuses primarily on positive cross-CWE transfer pairs, where the source-CWE fine-tuned model remains a usable backbone for prompt-level adaptation. We first briefly summarize the overall transfer landscape to provide context, and then compare IGPO with zero-shot, manual prompting, and automated prompt optimization baselines on positive-transfer pairs. We further report ablation results, statistical significance tests, and computational cost. Finally, we analyze negative-transfer behavior to clarify the operational boundary of IGPO, as such cases mainly reflect backbone suitability rather than prompt optimization effectiveness alone.

4.1. Cross-CWE Transfer Background

Before evaluating prompt optimization methods, we analyze the zero-shot transfer behavior of source-CWE fine-tuned models across the 14 selected CWE categories. The complete ordered transfer matrix contains 182 non-diagonal source–target pairs. Figure 4 visualizes the cross-CWE transfer performance using F1 scores. To improve readability, we remove cell-level numerical annotations from the heatmap and report the complete numerical matrix in Appendix A.
On diagonal settings, where the training CWE and testing CWE are the same, source-CWE fine-tuning obtains an average F1 score of 0.8601 with a standard deviation of 0.0508 across the 14 CWE categories. This indicates that the fine-tuned models learn useful CWE-specific vulnerability patterns under matched training and testing conditions.
For non-diagonal cross-CWE transfer, the average Precision, Recall, F1 score, and Accuracy of source-tuned zero-shot models are 0.6419, 0.7358, 0.6518, and 0.6217, respectively. Compared with the base-model zero-shot results, 159 out of 182 non-diagonal pairs show positive transfer, while 23 pairs show negative transfer. The average F1 score improvement over the base model is 0.1598 for positive-transfer pairs and −0.1075 for negative-transfer pairs. Table 4 summarizes the zero-shot transfer statistics across all settings.
These results suggest that source-CWE fine-tuning is often helpful for related target CWEs, but it is not uniformly reliable. Therefore, the main evaluation in this section focuses on the 159 positive-transfer pairs, where the source-tuned model provides a meaningful starting point for prompt optimization.

4.2. Performance on Positive-Transfer Pairs

Table 5 reports the performance of different prompting methods on the 159 positive-transfer pairs. Fine-ZS denotes zero-shot prompting with the source-CWE fine-tuned model. All other fine-prefixed methods also use the source-tuned model as the detector backbone and use only the target validation split for prompt construction, feedback collection, or prompt optimization.
IGPO achieves the highest average F1 score of 0.7267 on positive-transfer pairs. Compared with Fine-ZS, it improves average F1 scores by 0.0487 and outperforms Fine-ZS on 151 out of 159 transfer pairs (94.97%). Its average rank of 1.3019 is the best among all compared methods.
Among the automated optimization baselines, TextGrad and OPRO obtain similar average F1 scores of 0.6975 and 0.6974, respectively. Both improve over Fine-ZS on average, but their gains are substantially smaller than those of IGPO, and their win rates (65.41% and 54.09%) are considerably lower. Manual prompting methods show limited improvement: role-play prompting is marginally above Fine-ZS (ΔF1 = 0.0007), while CWE-definition and checklist prompting yield slightly negative average deltas.
The two few-shot variants illustrate the effect of example-source selection. Fine-few-shot uses examples from the target-CWE validation split and achieves an average F1 score of 0.6526 with a prediction degeneration rate of 3.14%. Fine-few-shot uses examples from the source-CWE validation split, and yields a lower average F1 score of 0.6480 with a substantially higher degeneration rate of 11.95%. The comparison suggests that demonstrations drawn from the target validation distribution are more stable than those drawn from the source validation distribution, although both few-shot variants remain below Fine-ZS on average. The improvement in stability under the revised setting confirms that aligning the demonstration distribution with the optimization feedback reduces degenerate outputs. Nevertheless, both variants remain below Fine-ZS on average (ΔF1 = −0.025 and −0.030, respectively), indicating that static few-shot prompting without structured optimization is insufficient for cross-CWE transfer.
CodeSpeak and DLAP-simplified produce the lowest average F1 scores among all methods (0.6546 and 0.6270), with DLAP-simplified ranking last overall. Notably, both methods exhibit zero prediction degeneration, suggesting that their structured output constraints prevent degenerate predictions at the cost of overall discriminative performance.
The results suggest that attribution-informed feedback can provide useful diagnostic information for prompt revision when the source-tuned model already transfers positively to the target CWE. However, this should be interpreted as evidence under positive-transfer conditions rather than as a universal guarantee across all source–target CWE pairs.
To assess whether the observed improvements are statistically reliable, we further performed paired Wilcoxon signed-rank tests on the positive-transfer pairs. We used a one-sided alternative hypothesis that the evaluated method is greater than the baseline and applied Holm correction for multiple comparisons. The detailed test results are reported in Appendix B. IGPO significantly outperforms Fine-ZS after correction, with a mean F1 score gain of 0.0487, a median F1 score gain of 0.0421, a win rate of 94.97%, and an adjusted p-value of 2.53 × 10 26 in the global comparison. IGPO also significantly outperforms the strongest automated baselines, Fine-TextGrad and Fine-OPRO, with mean F1 score gains of 0.0292 and adjusted p-values of 2.81 × 10 26 and 6.63 × 10 26 , respectively. We acknowledge that the 159 source–target pairs are not fully independent, as 14 source and 14 target CWEs are each shared across multiple pairs. To provide a more conservative assessment, we conducted grouped Wilcoxon signed-rank tests by source and target CWE separately, treating the 14 source CWE groups and 14 target CWE groups as the units for Supplementary Analysis. IGPO significantly outperforms Fine-ZS in all 14 source CWE groups after Holm correction, with a cross-group mean ΔF1 of 0.0491, a cross-group median ΔF1 of 0.0476, and win rates ranging from 76.92% to 100%. IGPO also significantly outperforms Fine-ZS in all 14 target CWE groups after Holm correction, with a cross-group mean ΔF1 of 0.0493, a cross-group median ΔF1 of 0.0464, and win rates ranging from 80.00% to 100%. The grouped Wilcoxon test results are reported in Appendix B. These grouped analyses confirm that the observed gains are not merely an artifact of pair-level dependency.

4.3. Ablation Study

To examine the contribution of different IGPO components, we conduct an ablation study on positive-transfer pairs. The variants test whether the improvement comes from attribution-based line selection, joint false-positive and false-negative feedback, top-k line selection, and the LLM-based error diagnosis step.
All ablation variants use the same source-tuned detector, validation split, test split, optimizer model, output format, and 10-round optimization budget as the full IGPO method. Unless otherwise specified, each round samples up to 10 false-positive and 10 false-negative validation errors. The default IGPO setting uses 16 IG steps and retains the top two attribution-ranked code lines for each selected error sample.
The Full error samples without IG attribution variant sends truncated full misclassified functions to the optimizer instead of IG-selected lines. The Random two code lines variant replaces attribution-selected lines with two randomly selected source-code lines from each error sample. The FN-only and FP-only variants use only false-negative or false-positive errors, respectively. The Without LLM error diagnosis variant removes the intermediate diagnostic-analysis call and directly asks the optimizer to revise the prompt from validation metrics and FP/FN counts. The Top-4 and Top-6 variants increase the number of retained IG-selected lines per error sample. Table 6 reports the ablation results on positive-transfer pairs.
Replacing IG-selected lines with random code lines substantially reduces the average F1 score from 0.7267 to 0.4243. This indicates that the selected attribution lines provide more useful feedback than arbitrary code context. Passing complete error samples without IG attribution also performs worse than full IGPO, suggesting that compact IG feedback can be more effective than exposing the optimizer to long misclassified functions with potentially irrelevant context.
The FP-only and FN-only variants both underperform the full method. FN-only feedback obtains higher Recall but lower Precision, while FP-only feedback improves Precision but loses Recall. The full method achieves a better balance, indicating that combining false-positive and false-negative feedback is important for prompt revision.
The variant without LLM error diagnosis achieves an average F1 score of 0.7085, which is lower than the full IGPO result but higher than several other ablations. This suggests that validation metrics and attribution feedback already provide useful guidance, while the explicit error-diagnosis step further helps organize the feedback into more actionable prompt-revision instructions.
Increasing the number of retained IG-selected lines also reduces performance. Top-4 and top-6 IG-selected lines obtain average F1 scores of 0.6639 and 0.5570, respectively. This result suggests that overly broad IG feedback may introduce noise into the prompt optimization process. In the evaluated setting, a concise top-2 IG summary provides the best overall result.
Overall, the ablation results support three design choices of IGPO: selecting feedback lines using IG rather than random or complete context, combining FP and FN diagnostic information, and keeping IG feedback concise. The attribution signal is used as a model-behavior diagnostic cue for prompt optimization, not as a causal explanation of vulnerability semantics.
Each target CWE validation split contains a fixed 80 samples, providing a consistent optimization signal across all transfer pairs. The optimizer runs for a maximum of 10 rounds per pair, with early stopping if no validation errors remain; on average, all 10 rounds are completed (avg. rounds = 10.0 ), indicating that optimization signals remain informative throughout the process.
To assess whether the prompt overfits to the validation split, Table 7 reports prompt optimization stability statistics across all 182 transfer pairs, with separate breakdowns for positive-transfer (159 pairs) and negative-transfer (23 pairs) subsets. Representative optimization trajectories illustrating these stability patterns are provided in Appendix D. The test-set F1 scores used in this stability analysis were computed retrospectively after all prompts, hyperparameters, methodological choices, and validation-based prompt selections had been finalized. They were not used during prompt optimization, prompt selection, early stopping, or method design. In the actual IGPO protocol, the final prompt is selected exclusively according to validation F1 score, and the target test split remains held out for final evaluation. The per-round test scores are reported only to diagnose whether validation-selected prompts exhibit overfitting or unstable generalization behavior. On positive-transfer pairs, the mean validation F1 score standard deviation across rounds is 0.035 (median 0.029 ), indicating that the optimization trajectory remains stable rather than fluctuating sharply. The best prompt emerges at round 3.45 on average (0-indexed), and 59.7 % of positive-transfer pairs reach their best prompt within the first five rounds, suggesting that improvement saturates well before the final round. Only 5.7 % of positive-transfer pairs have their best prompt at the final round, further indicating that the optimizer does not systematically require the full budget to converge. The average gap between best-round validation F1 score and test F1 score at the same round is 0.028 on positive-transfer pairs, which is consistent with normal generalization variance rather than systematic overfitting to the validation split.
Negative-transfer pairs exhibit noticeably higher instability: the mean validation F1 score standard deviation is 0.053 (median 0.055 ), the average val–test gap is 0.071 , and 30.4 % of pairs reach their best prompt only at the final round. These indicators suggest that when the source-tuned backbone is unsuitable for the target CWE, prompt optimization produces less stable trajectories and larger generalization gaps, consistent with the backbone-mismatch analysis in Section 4.6.

4.4. Attribution-Based Diagnostic Case Study

This section provides a qualitative case study to illustrate how IGPO uses IG feedback during prompt revision. The purpose of this analysis is not to claim that IG identifies the true semantic cause of a vulnerability. Instead, the case study shows how IG-selected lines can serve as compact diagnostic cues about the current detector’s behavior under a specific prompt and input.
We use CWE-416 Use-After-Free detection as an example. In early prompts, the detector is instructed to identify whether a function contains an unsafe use after a memory object has been freed. Such prompts can capture the general alloc–free–use pattern, but they may still produce false positives when the code contains lifetime-related names, reference-counting fields, cleanup functions, or pointer-like return values without an actual unsafe use. They may also produce false negatives when the vulnerable evidence is distributed across deallocation, alias propagation, state updates, and later pointer access.
During IGPO optimization, the current prompt is first evaluated on the validation set. IGPO then collects false-positive and false-negative samples, computes line-level IG feedback for these errors, and asks the optimizer model to summarize possible error patterns. The resulting diagnosis is then used to revise the prompt. Table 8 summarizes one prompt-evolution trace. The table reports the main focus of each prompt, validation metrics, and IG-based diagnostic feedback.
The case study suggests that IG feedback can help expose prompt-specific error tendencies. For example, when FP samples repeatedly assign high IG scores to names, constants, return statements, or reference-counting fields, the optimizer is guided to make the prompt more conservative and require stronger evidence of unsafe use after deallocation. When FN samples highlight cleanup operations, state updates, or alias-related statements, the optimizer is guided to emphasize cross-statement lifetime tracking and alias reasoning.
Table 9 summarizes recurring IG-based patterns observed in this prompt-evolution process.
This case does not show that IG provides a causal explanation of CWE-416 vulnerabilities. Rather, it illustrates how line-level IG feedback can produce compact, model-specific diagnostic feedback that helps the optimizer revise prompts more explicitly. The usefulness of such feedback depends on whether the detector’s IG patterns reflect stable error tendencies on the validation set.
It is important to note that IG reflects which code tokens influence the model’s prediction, rather than where the vulnerability is located. Prior work has shown that learning-based vulnerability detectors may assign high importance to non-vulnerable lines and do not reliably localize the actual vulnerability line [37,38]. In our case study, the IG-selected lines correspond to semantically active code regions, such as pointer arithmetic and memory allocation, that are related to the model’s decision behavior, rather than necessarily matching the patch-modified line. Therefore, we use IG not as a vulnerability localizer, but as a diagnostic signal for guiding prompt optimization toward the model’s prediction behavior.
Table 10 presents a case study on a CWE-125 (Out-of-Bounds Read) vulnerability in rpa_read_buffer(). Line 11 is the patch-modified line; however, consistent with prior findings on the limited line-level localization ability of learning-based vulnerability detectors [37,38], IG does not pinpoint this exact patch line. Instead, IG assigns high scores to Line 17 (*data += 1 + len;, score = 2.64 for the vulnerable version and 19.40 for the patched version) and Line 12 (return 0;), both of which are semantically relevant to CWE-125 memory-access patterns, including pointer arithmetic and boundary-return logic. In contrast, the randomly selected lines, including an empty line and a closing brace, carry no semantic information. This contrast illustrates that IG reflects the model’s computational focus rather than ground-truth vulnerability localization [38], and that IG-based feedback provides more semantically meaningful diagnostic signals for prompt refinement than random line selection.

4.5. Computational Cost

We report the approximate computational cost of automated prompt optimization methods in Table 11. The cost is averaged over one source–target transfer pair. The numbers are intended to provide an implementation-level comparison under our experimental setting rather than a hardware-independent benchmark.
All experiments are conducted on a single NVIDIA RTX 5880 Ada Generation GPU (47.5 GB VRAM) with CUDA 12.6 and PyTorch 2.7.1. The base detector model occupies 5.317 GB of GPU memory after loading; a single inference pass peaks at 5.506 GB (sequence length: 366 tokens). When IG computation is enabled (16 steps, default), peak memory reaches 7.285 GB, as each interpolation step performs an independent forward–backward pass without accumulating intermediate activations. IG computation scales linearly with the number of steps ( R 2 = 0.9996 , approximately 200 ms per step), confirming predictable resource usage under varying step budgets.
IGPO uses the same number of optimizer calls as TextGrad, but takes longer because it additionally computes IG scores for sampled false-positive and false-negative validation examples. This IG computation step requires forward and backward passes through the detector, making attribution computation the main source of IGPO’s overhead. In the low-resource validation setting used in this study, the overhead remains manageable while providing more targeted IG feedback for prompt optimization.
For CodeSpeak and DLAP-simplified, per-sample intermediate feedback can be cached when the same validation samples are reused in repeated experiments. However, Table 11 reports the average runtime without caching, which reflects the cost of processing fresh samples in a one-pass detection scenario.
Regarding the choice of 16 IG steps: the primary contribution of this work is to demonstrate that IG-based feedback constitutes a more informative optimization signal than metric-only feedback. The current configuration is validated as effective by our experimental results; we do not claim it to be optimal. Systematic tuning of IG hyperparameters, including step count and sampling strategy, is left as future work.

4.6. Performance on Negative-Transfer Pairs

Among the 182 cross-CWE transfer pairs evaluated, 23 pairs exhibit negative transfer, accounting for 12.6% of all evaluated pairs. In these cases, the source-CWE fine-tuned backbone underperforms the base zero-shot model on the target CWE, i.e., the Fine-ZS F1 score is lower than the Base-ZS F1 score. Table 12 summarizes the main observations on these negative-transfer pairs.
Negative-transfer pairs are not uniformly distributed across CWE types, as shown in Table 13. CWE-787 appears in 14 of the 23 pairs, accounting for 60.9%, either as a source or target, followed by CWE-703 in 6 pairs and CWE-119 in 5 pairs. This concentration suggests that certain CWE types exhibit structurally low cross-CWE semantic compatibility, rather than negative transfer being a random phenomenon.
On these 23 negative-transfer pairs, IGPO fully recovers to the Base-ZS level in 4 pairs, accounting for 17.4%. It partially stabilizes the degradation in 10 pairs, accounting for 43.5%, where IGPO improves over Fine-ZS but remains below Base-ZS. In the remaining 9 pairs, accounting for 39.1%, IGPO marginally aggravates the degradation. Critically, when IGPO does aggravate performance, the average additional drop is only Δ = 0.012 F1, indicating that IGPO does not catastrophically worsen an already-degraded backbone.
Nevertheless, IGPO alone cannot fully compensate for the structural mismatch introduced by fine-tuning on a semantically distant source CWE. In negative-transfer cases, the backbone’s representational capacity on the target domain is already compromised, and prompt-level optimization alone cannot compensate for this model-level deficiency.
In 19 of the 23 negative-transfer pairs, accounting for 82.6%, the unmodified base zero-shot model outperforms IGPO, with an average gap of Δ = + 0.103 F1 in favor of Base-ZS. We therefore recommend a simple detection heuristic: if the fine-tuned model’s zero-shot validation F1 score on the target CWE falls below the base model’s F1 score, the system should fall back to the base zero-shot model rather than applying IGPO.
This paper primarily targets positive-transfer scenarios, where IGPO consistently improves over both Fine-ZS and Base-ZS baselines. IGPO is designed and evaluated for positive-transfer settings, where the fine-tuned backbone retains reasonable generalization to the target CWE. In negative-transfer cases, which account for 12.6% of the evaluated pairs in our study, a simple and effective mitigation is to fall back to the base zero-shot model, which recovers performance in 82.6% of negative-transfer cases.
We consider this an acceptable operational boundary given that IGPO achieves consistent gains across the remaining 87.4% of transfer pairs. Addressing negative transfer fundamentally requires either source CWE selection strategies or multi-source ensemble approaches, which we leave for future work.

5. Discussion

5.1. Main Findings

The results show that IGPO is effective mainly under positive cross-CWE transfer conditions. On the 159 positive-transfer source–target pairs, IGPO obtains the highest average F1 score and improves over Fine-ZS on most pairs. This suggests that localized IG feedback can provide useful diagnostic information beyond aggregate validation metrics or complete misclassified functions.
The ablation study supports the main design choices. IG-selected lines outperform random lines and full error samples, joint FP/FN feedback performs better than using only one error type, and concise top-2 attribution feedback is more effective than broader top-k feedback. These findings suggest that IGPO benefits from focused diagnostic feedback, but the IG-selected lines should still be interpreted only as model-behavior signals rather than causal explanations of vulnerabilities.

5.2. Method-Level Limitations

IGPO depends on the quality of the source-tuned detector. When the source model transfers positively to the target CWE, IG feedback can help refine the prompt. However, under negative transfer, especially catastrophic negative transfer, the IG signal may mainly reflect source-model bias. In such cases, prompt optimization alone may not repair the backbone, and selecting another source model or falling back to the base model may be more appropriate.
A practical limitation is that IGPO requires a small set of labeled target-domain samples to serve as the validation split. This requirement is inherent to the method: attribution feedback is computed from validation errors, and the best prompt is selected according to validation F1 score. In settings where such labeled data are available, the same validation split can also be used to assess transfer direction before running IGPO—if the source-tuned model already outperforms the base-model zero-shot on the validation split, the pair is likely a positive-transfer case and IGPO can be applied; otherwise, the source backbone may not be suitable, and selecting a different source model or falling back to the base model should be considered first. However, when no labeled target-domain data are available at all, neither transfer direction nor prompt quality can be assessed, and IGPO cannot be applied. This represents a fundamental scope boundary of the current method.
IGPO also introduces extra computational cost because IG requires additional forward and backward passes on selected validation errors. This overhead is acceptable in the low-labeled-data setting used here—where the constraint is the scarcity of labeled target-domain samples rather than computational resources—but may increase with larger validation sets, longer functions, larger detector backbones, or more optimization rounds.

5.3. Study-Level Limitations

The main experiments are limited to C/C++ function-level binary vulnerability detection over 14 CWE categories. In addition, each CWE-specific dataset is constructed with an approximately balanced vulnerable-to-non-vulnerable ratio, which provides a controlled setting for comparing cross-CWE transfer behavior and isolating the effect of attribution-guided prompt optimization. However, this setting is more balanced than real-world software projects, where vulnerable functions are usually much rarer than safe functions. Therefore, the reported Precision, Recall, and F1 scores should be interpreted as results under a controlled low-resource evaluation setting, rather than as direct estimates of deployment performance under natural vulnerability prevalence. Using the original CWE-specific distributions could introduce confounding factors, because performance differences might reflect class-ratio variation or sample-count imbalance rather than genuine cross-CWE transfer effects. Therefore, the conclusions may not directly generalize to highly imbalanced real-world detection scenarios, line-level localization, multi-class CWE classification, repository-level detection, patch validation, or other programming languages. Although global exact-hash and prefix-based deduplication is applied before splitting, the current study does not enforce project-, commit-, or patch-pair-level grouping because unified provenance metadata are not consistently available across the merged datasets. Thus, the current split should be interpreted as an exact-duplicate and prefix-based near-duplicate controlled split, rather than a full provenance-level grouped split.
To provide a preliminary check of model sensitivity, we conduct a small 2-by-2 analysis on 20 randomly selected positive-transfer pairs by varying the detector backbone and optimizer model. The attribution construction, optimization budget, and prompt-selection protocol are kept unchanged. Table 14 reports the Fine-ZS and Fine-IGPO F1 scores, average ΔF1, and win rate for each detector–optimizer combination.
The sampled results show consistent gains over Fine-ZS across the four detector–optimizer combinations. However, this is only a preliminary sensitivity check on a small subset, not a comprehensive robustness evaluation. Broader experiments across more model families, model sizes, optimizer LLMs, and random samples are still needed.
Another limitation is that IGPO does not use explicit program-analysis artifacts such as CFGs, DFGs, taint paths, or static-analysis warnings. IG can identify prediction-sensitive code regions, but it cannot replace semantic program analysis. Thus, IG feedback should be used as diagnostic guidance for prompt adaptation, not as security-auditing evidence or causal explanation.

5.4. Future Work

Future work will evaluate IGPO across more detector backbones, optimizer models, programming languages, and vulnerability-analysis tasks. Reducing IG computation cost is also important, for example, through fewer integration steps, approximate IG, representative-error sampling, or adaptive IG. Another promising direction is to combine IG feedback with program-analysis signals, which may provide stronger semantic guidance for vulnerabilities involving control flow, data flow, or interprocedural evidence.
Overall, IGPO provides useful prompt-level adaptation under positive cross-CWE transfer conditions, but its effectiveness depends on a suitable backbone detector, concise feedback construction, and cautious interpretation of IG as diagnostic rather than causal evidence.

6. Conclusions

This paper proposed IGPO, an Integrated-Gradient-Guided Prompt Optimization method for low-resource cross-CWE software vulnerability detection, which keeps the detector fixed and uses line-level IG feedback from false-positive and false-negative validation samples to support LLM-based error diagnosis and prompt revision. Experiments on C/C++ functions constructed from PrimeVul, DiverseVul, and BigVul across 14 CWE categories show that, on 159 positive-transfer source–target pairs, IGPO achieves an average F1 score of 0.7267, improves over the source-model zero-shot baseline by 0.0487, and outperforms it on 94.97% of the pairs. These results suggest that IG-informed diagnostic feedback can help prompt-level adaptation when the source-tuned detector remains a suitable backbone, while IG in this work should be interpreted as a model-behavior diagnostic signal rather than a causal explanation of vulnerabilities or model decisions. These findings may be of practical value to security researchers and vulnerability-detection tool developers who need to adapt fine-tuned detectors to new CWE categories with limited labeled data, without retraining the underlying model. Future work will evaluate IGPO on additional model backbones, programming languages, and vulnerability-analysis tasks, and explore more efficient IG computation and integration with program-analysis signals such as control-flow, data-flow, and static-analysis warnings.

Supplementary Materials

The following supporting information can be downloaded at https://www.mdpi.com/article/10.3390/info17080762/s1, The supplementary materials include 18 representative IGPO prompt-optimization trajectories and the corresponding validation/test F1 score curves.

Author Contributions

Conceptualization, X.X., Z.L. and N.Y.; methodology, X.X.; software, X.X.; validation, X.X.; formal analysis, X.X.; investigation, X.X.; data curation, X.X.; writing—original draft preparation, X.X.; writing—review and editing, X.X., Z.L. and N.Y.; visualization, X.X.; supervision, Z.L. and N.Y.; project administration, Z.L. and N.Y. All authors have read and agreed to the published version of the manuscript.

Funding

This work was supported by Science and Technology Innovation Key R&D Program of Chongqing, CSTB2024TIAD-STX0027.

Institutional Review Board Statement

Not applicable.

Informed Consent Statement

Not applicable.

Data Availability Statement

The public datasets used in this study, including PrimeVul, DiverseVul, and BigVul, are available from their respective public repositories: PrimeVul at https://github.com/DLVulDet/PrimeVul, accessed on 24 June 2026, DiverseVul at https://github.com/wagner-group/diversevul, accessed on 24 June 2026, and BigVul at https://github.com/rshariffdeen/Big-Vul, accessed on 24 June 2026. To support reproducibility, we will release the processed split identifiers, deduplication records, selected CWE lists, cross-CWE transfer matrix, prompt templates, final selected prompts, prompt-optimization histories, and evaluation scripts in a public repository upon acceptance of the manuscript. Before public release, these materials are available from the corresponding author upon reasonable request.

Acknowledgments

The authors would like to thank the laboratory for providing computational resources and technical support for this study. During the preparation of this manuscript, the authors used ChatGPT based on GPT-5.5 for the purpose of polishing the manuscript. The authors have reviewed and edited the output and take full responsibility for the content of this publication.

Conflicts of Interest

The authors declare no conflicts of interest.

Abbreviations

    The following abbreviations are used in this manuscript:
APIApplication Programming Interface
APEAutomatic Prompt Engineer
CFGControl-Flow Graph
CWECommon Weakness Enumeration
DFGData-Flow Graph
DLAPDeep Learning Augmented LLMs Prompting
FNFalse Negative
FPFalse Positive
F1F1 score
IGIntegrated Gradients
IGPOIntegrated-Gradient-Guided Prompt Optimization
LIMELocal Interpretable Model-Agnostic Explanations
LLMLarge Language Model
LoRALow-Rank Adaptation
NLPNatural Language Processing
OPROOptimization by PROmpting
PPrecision
RRecall
SHAPSHapley Additive exPlanations
UAFUse-After-Free
ZSZero-Shot

Appendix A. Complete Cross-CWE Transfer Matrix

Table A1 reports the complete numerical F1 score matrix corresponding to Figure 4. Rows denote the training CWE type, columns denote the evaluation CWE type, and “Deg.” indicates strict degenerate predictions.
Table A1. Complete F1 score matrix of cross-CWE transfer evaluation.
Table A1. Complete F1 score matrix of cross-CWE transfer evaluation.
Train/EvalCWE-284CWE-416CWE-200CWE-399CWE-264CWE-119CWE-20CWE-190CWE-189CWE-362CWE-787CWE-125CWE-476CWE-703
CWE-2840.8571Deg.Deg.Deg.Deg.Deg.Deg.Deg.0.62930.6325Deg.0.66110.66110.6316
CWE-4160.73910.86270.70130.82670.77580.72930.75950.50960.65190.67710.40370.52800.53790.5333
CWE-2000.70190.69230.83440.79100.86050.66960.76290.64290.70940.71280.67530.59570.60240.5957
CWE-3990.67570.75500.70060.91820.76290.72530.75640.72920.66980.69840.57690.63280.63870.6310
CWE-2640.68420.67670.77700.85900.93170.69190.74290.65220.73330.69570.53660.59500.53450.2913
CWE-1190.60000.52730.72870.85710.78570.92990.80000.55560.61190.61070.21510.49560.41120.1489
CWE-200.70970.72730.75450.87740.75130.80000.83750.64770.68450.70810.60930.55000.58330.4143
CWE-1900.54370.44440.61420.70150.71880.72830.66670.83020.69270.67160.54550.54100.56900.4691
CWE-1890.65220.60870.68930.67810.67370.65820.66670.72430.89940.79500.66670.63270.65960.6129
CWE-3620.65050.63960.67580.67230.67360.66110.66390.73940.78160.91460.63720.60400.66670.6707
CWE-7870.62500.41510.49600.50880.62820.44260.53330.57860.65190.58330.81710.56760.50000.4892
CWE-1250.69950.76510.75310.81930.83910.68780.70770.72320.68340.67000.66670.81480.61540.5914
CWE-4760.61260.68690.69610.67620.78310.65820.67810.70790.65790.72730.67020.73100.82490.6452
CWE-7030.65740.64980.65250.66950.6325Deg.0.66110.64070.72820.69330.64410.63200.63760.7684

Appendix B. Statistical Significance Tests

Table A2 and Table A3 report Wilcoxon signed-rank test results on positive-transfer pairs. The alternative hypothesis is one-sided (the tested method outperforms the comparator). Holm correction is applied across all comparisons within each table.
Table A2. Wilcoxon signed-rank tests: each method vs. Fine-ZS.
Table A2. Wilcoxon signed-rank tests: each method vs. Fine-ZS.
MethodMean ΔF1Median ΔF1Win/Tie/Lossp-Value p adj
Fine-IGPO0.04870.0421151/4/4 2.5332 × 10 27 2.5332 × 10 26
Fine-OPRO0.01950.008486/55/18 1.1563 × 10 12 9.2500 × 10 12
Fine-TextGrad0.01950.0131104/32/23 3.0526 × 10 13 2.7473 × 10 12
Fine-role-play0.00070.000041/89/28 1.0301 × 10 1 7.1095 × 10 1
Fine-CWE-definition−0.00030.000043/85/30 1.0156 × 10 1 7.1095 × 10 1
Fine-checklist−0.00940.000029/82/47 9.9457 × 10 1 1.0000 × 10 0
Fine-CodeSpeak−0.0234−0.005868/3/88 9.9865 × 10 1 1.0000 × 10 0
Fine-few-shot −0.0253−0.005872/2/85 9.9871 × 10 1 1.0000 × 10 0
Fine-few-shot −0.0295−0.010763/3/92 9.9628 × 10 1 1.0000 × 10 0
Fine-DLAP-simplified−0.0510−0.034424/0/135 1.0000 × 10 0 1.0000 × 10 0
ΔF1 = method F1 − Fine-ZS F1. Win/Tie/Loss counts are over 159 positive-transfer pairs. Fine-few-shot with examples drawn from the target-CWE validation split. Fine-few-shot with examples drawn from the source-CWE validation split.
Table A3. Wilcoxon signed-rank tests: Fine-IGPO vs. each baseline.
Table A3. Wilcoxon signed-rank tests: Fine-IGPO vs. each baseline.
BaselineBaseline Avg. F1 ScoreMean ΔF1Median ΔF1Win/Tie/Lossp-value p adj
Fine-DLAP-simplified0.62700.09970.0830159/0/0 3.8226 × 10 28 3.8226 × 10 27
Fine-few-shot 0.64800.07850.0471153/4/1 2.5825 × 10 27 1.9498 × 10 26
Fine-few-shot 0.65260.07400.0583148/2/9 3.3138 × 10 26 6.6275 × 10 26
Fine-CodeSpeak0.65460.07210.0551157/1/1 5.7964 × 10 28 5.2168 × 10 27
Fine-checklist0.66810.05840.0424152/3/3 2.4373 × 10 27 1.9498 × 10 26
Fine-CWE-definition0.67720.04930.0358152/3/3 2.6333 × 10 27 1.9498 × 10 26
Fine-ZS0.67800.04870.0421151/4/4 2.5332 × 10 27 1.9498 × 10 26
Fine-role-play0.67820.04820.0399151/3/4 3.0754 × 10 27 1.9498 × 10 26
Fine-OPRO0.69740.02920.0178144/4/11 4.6563 × 10 26 6.6275 × 10 26
Fine-TextGrad0.69750.02920.0173148/2/9 9.3665 × 10 27 2.8100 × 10 26
ΔF1 = Fine-IGPO F1 − baseline F1. Baselines are sorted by ascending average F1 score. Fine-few-shot with examples drawn from the target-CWE validation split. Fine-few-shot with examples drawn from the source-CWE validation split.
Table A4. Grouped Wilcoxon signed-rank tests by target CWE comparing Fine-IGPO with Fine-ZS on positive-transfer pairs.
Table A4. Grouped Wilcoxon signed-rank tests by target CWE comparing Fine-IGPO with Fine-ZS on positive-transfer pairs.
Target CWENMean ΔF1Median ΔF1WinWin Rate (%) p adj
CWE-119120.04560.04321191.67 1.0037 × 10 2
CWE-125130.07630.063413100.00 1.7090 × 10 3
CWE-189130.05230.038713100.00 1.7090 × 10 3
CWE-190130.05810.050213100.00 1.7090 × 10 3
CWE-20120.03280.03561083.33 8.5450 × 10 3
CWE-200120.04040.03891191.67 3.9060 × 10 3
CWE-264130.02500.01661184.62 1.0037 × 10 2
CWE-284130.05370.032913100.00 1.7090 × 10 3
CWE-362130.04440.039813100.00 1.7090 × 10 3
CWE-399130.03380.018413100.00 1.7090 × 10 3
CWE-416100.04710.0397990.00 1.1529 × 10 2
CWE-47690.06290.07089100.00 1.0037 × 10 2
CWE-70380.07350.07968100.00 1.1529 × 10 2
CWE-78750.04480.0493480.00 3.3945 × 10 2
All adjusted p-values are Holm-corrected within the 14 target-CWE groups.
Table A5. Grouped Wilcoxon signed-rank tests by source CWE comparing Fine-IGPO with Fine-ZS on positive-transfer pairs.
Table A5. Grouped Wilcoxon signed-rank tests by source CWE comparing Fine-IGPO with Fine-ZS on positive-transfer pairs.
Source CWENMean ΔF1Median ΔF1WinWin Rate (%) p adj
CWE-11990.07400.0753888.89 1.0124 × 10 2
CWE-125130.04090.03761292.31 5.8590 × 10 3
CWE-189130.05680.059513100.00 1.7090 × 10 3
CWE-190100.06270.059210100.00 5.8590 × 10 3
CWE-20110.03790.023811100.00 4.3950 × 10 3
CWE-200130.04380.04681184.62 4.3950 × 10 3
CWE-264100.02890.0262990.00 1.0124 × 10 2
CWE-284130.03050.02581076.92 1.0124 × 10 2
CWE-362120.06050.058512100.00 2.9300 × 10 3
CWE-399120.04560.037512100.00 2.9300 × 10 3
CWE-416110.05510.042111100.00 4.3950 × 10 3
CWE-476130.06100.060013100.00 1.7090 × 10 3
CWE-703120.04060.033112100.00 2.9300 × 10 3
CWE-78770.04960.03987100.00 1.0124 × 10 2
All adjusted p-values are Holm-corrected within the 14 source-CWE groups.

Appendix C. Prompt Templates

This appendix provides the complete prompt templates used in our experiments. All prompting methods share the same local detection model and the same final binary-output constraint. The optimizer LLM, when used, is only employed to construct or optimize the information hint. It is never used for final vulnerability prediction.

Appendix C.1. Shared Detection Prompt

For all methods, the local fine-tuned detection model receives a fixed system role, an information hint, the target C/C++ function, and a fixed output instruction. The model is required to output only one digit, where 1 denotes vulnerable code and 0 denotes non-vulnerable code.
Listing A1. Shared detection prompt template.
     System:
You are a vulnerability detection expert. You will perform a security analysis task to determine whether a given C/C++ function contains a vulnerability.

     User:
     Information hint:
     [INFO_HINT_PROMPT]

     Code:
     [BEGIN_C_CODE]
     [FUNCTION_CODE]
     [END_C_CODE]

     Output only one digit. Output 1 if the function is vulnerable. Output 0 if the function is not vulnerable.

     Assistant:
     Answer:
In this template, [INFO_HINT_PROMPT] is instantiated differently by each prompting method, while [FUNCTION_CODE] is the C/C++ function to be classified. The final prediction is produced by comparing the local model logits for the tokens 0 and 1 at the answer position.

Appendix C.2. Baseline Prompting Methods

This subsection lists the fixed prompting baselines that do not perform iterative prompt optimization. These prompts are inserted into the shared detection template as [INFO_HINT_PROMPT].

Appendix C.2.1. Fine-ZS

Fine-ZS uses an empty information hint and relies only on the fixed system role, the code, and the binary-output instruction.
Listing A2. Fine-ZS information hint.
     [EMPTY]

Appendix C.2.2. Fine-Role-Play

Fine-role-play strengthens the security-expert role in the information hint.
Listing A3. Fine-role-play information hint.
     You are an experienced C/C++ security auditor. Analyze the function as a vulnerability detection task. Focus on whether the implementation contains a real security vulnerability rather than merely suspicious coding style.

Appendix C.2.3. Fine-CWE-Definition

Fine-CWE-definition provides the model with CWE-oriented vulnerability background. The concrete CWE description is instantiated according to the source training CWE.
Listing A4. Fine-CWE-definition information hint.
     CWE-aware vulnerability definition:
     [CWE_DESCRIPTION]

     Use this CWE definition as security background. Determine whether the given C/C++ function exhibits this type of vulnerability. Consider whether attacker-controlled data can trigger unsafe behavior, memory corruption, invalid access, information exposure, or other security-relevant consequences.

Appendix C.2.4. Fine-Checklist

Fine-checklist uses a fixed vulnerability-analysis checklist as the information hint.
Listing A5. Fine-checklist information hint.
     Analyze the function using the following vulnerability checklist:

     1. Identify all external inputs, parameters, pointer arguments, buffer arguments, length fields, and integer values.
     2. Trace how these values flow into memory reads, memory writes, pointer arithmetic, array indexing, allocation sizes, copy operations, string operations, and loop bounds.
     3. Check whether all bounds, lengths, offsets, and allocation sizes are validated before use.
     4. Check whether integer computations can overflow, underflow, wrap around, or become negative before being used in memory operations.
     5. Check whether pointers and resources are validated before dereference, release, or reuse.
     6. Distinguish true vulnerabilities from safe code that contains adequate checks.
     7. Output 1 only if the function contains a real vulnerability. Otherwise output 0.

Appendix C.2.5. Fine-Few-Shot

Fine-few-shot augments the information hint with selected labeled examples. We evaluate two demonstration-source variants. Fine-few-shot selects examples from the target-CWE validation split, whereas Fine-few-shot selects examples from the source-CWE validation split. In both variants, examples are inserted before the target function, selected by stratified sampling, and no target test-split samples are used.
Listing A6. Fine-few-shot information hint.
      The following are labeled examples for C/C++ vulnerability detection.

      Example 1:
      Code:
      [BEGIN_C_CODE]
      [FEW_SHOT_CODE_1]
      [END_C_CODE]
      Label: [FEW_SHOT_LABEL_1]

      Example 2:
      Code:
      [BEGIN_C_CODE]
      [FEW_SHOT_CODE_2]
      [END_C_CODE]
      Label: [FEW_SHOT_LABEL_2]

      Example 3:
      Code:
      [BEGIN_C_CODE]
      [FEW_SHOT_CODE_3]
      [END_C_CODE]
      Label: [FEW_SHOT_LABEL_3]

      Example 4:
      Code:
      [BEGIN_C_CODE]
      [FEW_SHOT_CODE_4]
      [END_C_CODE]
      Label: [FEW_SHOT_LABEL_4]

      Use the examples only as guidance for the binary vulnerability decision. For the target function, output 1 if it is vulnerable and 0 otherwise.

Appendix C.3. Optimizer-LLM-Assisted Non-Iterative Methods

CodeSpeak and DLAP-simplified use the optimizer LLM to generate an auxiliary description or static-analysis summary for each target function. The generated text is then inserted into the shared detection prompt as [INFO_HINT_PROMPT]. The optimizer LLM is not used to make the final binary prediction.

Appendix C.3.1. Fine-CodeSpeak

Fine-CodeSpeak first asks the optimizer LLM to describe the target function in natural language. The description focuses on memory operations, data flow, and potential security risks.
Listing A7. Fine-CodeSpeak optimizer prompt.
      Describe the following C/C++ code in natural language. Focus on: memory operations, data flow from inputs to buffers, and any potential security risks. Be concise.

      [BEGIN_C_CODE]
      [FUNCTION_CODE]
      [END_C_CODE]
The resulting description is injected into the detection prompt using the following information-hint format.
Listing A8. Fine-CodeSpeak information hint.
     Semantic description of the code:
     [SEMANTIC_DESCRIPTION]

Appendix C.3.2. Fine-DLAP-Simplified

Fine-DLAP-simplified asks the optimizer LLM to produce a concise static-analysis summary for the target function.
Listing A9. Fine-DLAP-simplified optimizer prompt.
     Analyze the following C/C++ code and provide a concise static analysis summary covering: (1) dangerous function calls found, (2) data flow paths from user input to memory write operations, (3) missing boundary or length checks. Output as a short structured list.

     [BEGIN_C_CODE]
     [FUNCTION_CODE]
     [END_C_CODE]
The generated summary is inserted into the detection prompt as follows.
Listing A10. Fine-DLAP-simplified information hint.
     Static analysis summary:
     [STATIC_ANALYSIS_SUMMARY]

Appendix C.4. Iterative Prompt Optimization Baselines

Fine-OPRO and Fine-TextGrad iteratively optimize [INFO_HINT_PROMPT] on the validation split of the target CWE. The best prompt found on validation data is then evaluated on the corresponding held-out test split. In both methods, the optimizer LLM is used only for prompt construction.

Appendix C.4.1. Fine-OPRO

Fine-OPRO maintains a history of previous prompts and their validation positive-class F1 scores. At each round, the optimizer LLM is asked to generate a new information hint expected to improve validation performance.
Listing A11. Fine-OPRO optimizer prompt.
     You are an expert prompt engineer optimizing an INFO_HINT_PROMPT for a C/C++ vulnerability detection task.

      The detection model sees:
      - A fixed system message with an expert role.
      - INFO_HINT_PROMPT, which is the text you must improve.
      - The C/C++ code to analyze.
      - A fixed output instruction requiring the model to output 0 or 1.

      Your goal is to write an INFO_HINT_PROMPT that maximizes positiveclass F1 on the validation set.
      You may include role descriptions, checklists, CWE definitions, analysis instructions, or concise decision guidance.
      Output only the new INFO_HINT_PROMPT text, and nothing else.

      Past attempts:
      [HISTORY_OF_PROMPTS_AND_VALIDATION_F1]

      Training CWE:
      [TRAIN_CWE]

      Generate a new INFO_HINT_PROMPT that achieves higher positive-class F1 than the best attempt so far.
      Best validation positive-class F1:
      [BEST_VALIDATION_F1]

      Output only the INFO_HINT_PROMPT text:
The history field is formatted as follows.
Listing A12. Fine-OPRO history format.
     Attempt [INDEX]:
     Positive-class F1: [VALIDATION_F1]
     INFO_HINT_PROMPT:
     [PREVIOUS_INFO_HINT_PROMPT]

Appendix C.4.2. Fine-TextGrad

Fine-TextGrad represents validation errors as textual feedback. At each round, false positives and false negatives are collected from the local detector. The optimizer LLM first analyzes why the current prompt caused these errors, and then rewrites the prompt based on this textual gradient.
Listing A13. Fine-TextGrad error-analysis prompt.
     You are evaluating an INFO_HINT_PROMPT used for C/C++ vulnerability detection.

      Current INFO_HINT_PROMPT:
      [CURRENT_INFO_HINT_PROMPT]

      The detection model made the following errors on the validation set:

      FALSE POSITIVES, predicted vulnerable but actually safe:
      [FALSE_POSITIVE_CODE_SNIPPETS]

      FALSE NEGATIVES, predicted safe but actually vulnerable:
      [FALSE_NEGATIVE_CODE_SNIPPETS]

      Analyze why the current INFO_HINT_PROMPT caused these errors.
      Identify specific patterns or missing guidance that led to each error type.
      Be concise and specific. This analysis will be used to improve the prompt.
The false-positive and false-negative samples are formatted as follows.
Listing A14. Fine-TextGrad error sample format.
     Sample [INDEX]:
     [BEGIN_C_CODE]
     [ERROR_CODE_SNIPPET]
     [END_C_CODE]
After obtaining the textual gradient, Fine-TextGrad updates the prompt using the following optimizer prompt.
Listing A15. Fine-TextGrad prompt-update prompt.
     You are improving an INFO_HINT_PROMPT for C/C++ vulnerability detection.

     Current INFO_HINT_PROMPT:
     [CURRENT_INFO_HINT_PROMPT]

     Text gradient, failure analysis:
     [TEXT_GRADIENT]

     Based on the failure analysis, rewrite the INFO_HINT_PROMPT to fix the identified issues.
     Output only the new INFO_HINT_PROMPT text, and nothing else.

Appendix C.5. Proposed Method: Fine-IGPO

Fine-IGPO is our proposed Integrated-Gradient-Guided Prompt Optimization method. At each optimization round, the local detector is evaluated on the validation split. Misclassified samples are collected, and IG are computed only over code tokens while excluding prompt tokens. The top-ranked code lines are then used as concise evidence for the optimizer LLM. The optimizer LLM first analyzes the model errors and then rewrites the information hint to improve validation positive-class F1 score.

Appendix C.5.1. Fine-IGPO Error Evidence Format

For each selected false-positive or false-negative sample, Fine-IGPO provides the optimizer LLM with the most influential code lines according to code-token-only integrated gradients.
Listing A16. Fine-IGPO integrated-gradient evidence format.
     Sample [INDEX]:
     error_type: [FP_OR_FN]
     gold_label: [GOLD_LABEL]
     model_prediction: [MODEL_PREDICTION]
     evidence_type: integrated_gradient_top_code_lines

     Line [LINE_NUMBER], attribution_score: [ATTRIBUTION_SCORE]
     [CODE_LINE]

     Line [LINE_NUMBER], attribution_score: [ATTRIBUTION_SCORE]
     [CODE_LINE]
Here, FP denotes a false positive, where the model predicts vulnerability but the function is safe. FN denotes a false negative, where the model predicts safe but the function is vulnerable.

Appendix C.5.2. Fine-IGPO Error-Analysis Prompt

The optimizer LLM receives validation metrics and IG-guided misclassification evidence, and is asked to identify the cause of false positives and false negatives.
Listing A17. Fine-IGPO error-analysis prompt.
     You are analyzing errors made by a local C/C++ vulnerability detection model.

     The model receives:
     - A fixed system role.
     - An INFO_HINT_PROMPT.
     - A C/C++ function.
     - A fixed instruction to output 1 for vulnerable and 0 for nonvulnerable.

     Current INFO_HINT_PROMPT:
     [CURRENT_INFO_HINT_PROMPT]

     Validation metrics:
     - Precision: [VALIDATION_PRECISION]
     - Recall: [VALIDATION_RECALL]
     - F1: [VALIDATION_F1]
     - Accuracy: [VALIDATION_ACCURACY]

     Below are misclassified validation samples.
     For integrated-gradient-based evidence, only code tokens were attributed; prompt tokens were excluded.
     The shown lines are the code lines the model focused on most.

     Misclassification evidence:
     [INTEGRATED_GRADIENT_ERROR_EVIDENCE]

     Analyze why the current INFO_HINT_PROMPT caused these errors.
     Focus on:
     1. Why false positives happened.
     2. Why false negatives happened.
     3. What vulnerability reasoning guidance is missing.
     4. What misleading patterns the model may be overusing.

     Be concise and specific.
     Output only the error analysis.

Appendix C.5.3. Fine-IGPO Prompt-Optimization Prompt

After receiving the error analysis, Fine-IGPO asks the optimizer LLM to rewrite the information hint. The rewritten hint is then evaluated by the local detector in the next optimization round.
Listing A18. Fine-IGPO prompt-optimization prompt.
     You are improving an INFO_HINT_PROMPT for a C/C++ vulnerability detection model.

     Current INFO_HINT_PROMPT:
     [CURRENT_INFO_HINT_PROMPT]

     Validation metrics:
     - Precision: [VALIDATION_PRECISION]
     - Recall: [VALIDATION_RECALL]
     - F1: [VALIDATION_F1]
     - Accuracy: [VALIDATION_ACCURACY]

     Error analysis:
     [ERROR_ANALYSIS]

     Rewrite the INFO_HINT_PROMPT to improve validation positive-class F1.
     The prompt should help the model distinguish truly vulnerable code from safe code.
     It may include:
     - vulnerability reasoning checklist
     - boundary and data-flow analysis guidance
     - false-positive reduction guidance
     - false-negative reduction guidance
     - concise CWE-aware cues

     Constraints:
     - Do not ask the model to output explanations.
     - The final detector must still output only 0 or 1.
     - Do not include irrelevant verbosity.
     - Output only the new INFO_HINT_PROMPT text.

Appendix C.6. Summary of Prompting Methods

Table A6 summarizes the information source and optimizer-LLM usage of each prompting method considered in the main comparison.
Table A6. Summary of prompt templates and optimizer-LLM usage.
Table A6. Summary of prompt templates and optimizer-LLM usage.
MethodInformation Hint SourceOptimizer LLM UsedFinal Detector
Fine-ZSEmpty hintNoLocal fine-tuned model
Fine-role-playFixed role instructionNoLocal fine-tuned model
Fine-CWE-definitionFixed CWE-aware definitionNoLocal fine-tuned model
Fine-checklistFixed vulnerability checklistNoLocal fine-tuned model
Fine-few-shotSelected labeled examplesNoLocal fine-tuned model
Fine-CodeSpeakPer-sample semantic descriptionYes, hint generation onlyLocal fine-tuned model
Fine-DLAP-simplifiedPer-sample static-analysis summaryYes, hint generation onlyLocal fine-tuned model
Fine-OPROIteratively optimized information hintYes, prompt optimization onlyLocal fine-tuned model
Fine-TextGradError-feedback-based optimized hintYes, prompt optimization onlyLocal fine-tuned model
Fine-IGPOIG-guided error evidence and optimized hintYes, prompt optimization onlyLocal fine-tuned model

Appendix D. Representative IGPO Optimization Trajectories

This section presents 18 representative prompt optimization trajectories selected from the full set of 182 cross-CWE transfer pairs evaluated with the Fine-IGPO method. These trajectories summarize how prompt optimization evolves across different transfer settings and provide qualitative evidence for both successful transfer and potential overfitting behavior.
The trajectories are organized by optimization pattern category (A1–F; see Table 7 for aggregate statistics). For each trajectory, the corresponding figure reports the validation F1 scores and test F1 scores across 10 optimization rounds, together with false-positive (FP) and false-negative (FN) error counts on the secondary axis.
For each trajectory, the best-performing prompt, selected according to the highest validation F1 score, is listed below the corresponding figure as the [INFO_HINT_PROMPT] inserted into the shared detection template described in Appendix C.1.

Appendix D.1. Category A1: Positive Transfer with the Largest Validation F1 Score Improvement

This category contains positive-transfer pairs that achieve the largest validation F1 score improvements after prompt optimization.

Appendix D.1.1. CWE-787CWE-362 [Positive Transfer]

Transfer pair: CWE-787 (source) → CWE-362 (target), positive transfer. Best validation F1 score= 0.6458 (improvement Δ = + 0.1682 , test F1 score at peak round = 0.6010, validation–test gap = +0.0448). The best prompt is selected at round 3. Selection criterion: A1-positive-transfer-prototypical-success.
Figure A1. Optimization trajectory for CWE-787CWE-362 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Figure A1. Optimization trajectory for CWE-787CWE-362 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Information 17 00762 g0a1
Listing A19. Best prompt for CWE-787 to CWE-362 (round 3, validation F1 = 0.6458).
     Analyze the C/C++ code for vulnerabilities. Focus on data flow from untrusted sources (stdin, argv, environment, network) to sensitive sinks (memory writes, system calls, pointer dereferences). Use the checklist below to decide between 0 (safe) and 1 (vulnerable). Output only 0 or 1.

     Checklist for vulnerability detection:

     1. Buffer overflow
     Every copy or format operation must have a known destination size strictly larger than the source length, including the null terminator.
     - Unsafe: strcpy, sprintf, memcpy without an explicit size limit; strncpy with size greater than or equal to the destination size.
     - Safe: snprintf with size less than or equal to the real capacity; strncpy with size equal to destination size minus 1, followed by null termination.
     - Check loops: index i must be smaller than the allocated size for all iterations.

     2. Integer overflow or underflow
     Arithmetic in size, index, or allocation arguments can wrap around.
     - Flag any signed or unsigned mismatch or unsafe cast in expressions such as malloc(a ∗ b), arr[i + j], or loop bounds derived from user input.
     - Even if the final result appears valid, intermediate overflow can still be unsafe.

     3. Format string bug
     If a user-controlled string appears as the format argument in printf, fprintf, sprintf, or similar functions, it is vulnerable.
     Safe example: printf(“%s”, user_str).

     4. Null pointer dereference
     After any allocation or pointer-returning function, check for NULL before dereference. Also, strlen(NULL) is undefined behavior.

     5. Use-after-free or double-free
     Flag any pointer used after free or realloc, including through aliases. Watch for dangling pointers in loops, realloc with shrinking, or multiple frees of the same pointer.

     6. Unsafe type casts
     Pointer casts may break alignment or strict aliasing. Flag casts that can make later dereferences invalid.

     Boundary and data-flow analysis guidance:
     - Every array index, pointer offset, and length must be strictly smaller than the allocated size.
     - Off-by-one errors are vulnerabilities.
     - Trace through function arguments, return values, global variables, and aliased pointers.
     - Consider chained vulnerabilities: integer overflow causes small allocation, followed by buffer overflow.

     False-positive reduction:
     - Static arrays with known fixed size and in-bounds access are safe.
     - strncpy(dst, src, n) is safe only if n is less than or equal to sizeof(dst) - 1, or if the destination is later null-terminated.
     - snprintf(dst, size, …) is safe if size is less than or equal to sizeof(dst).
     - Bounded loops with proper termination are safe if the bound is trusted or validated.
- Trust standard library functions only when used correctly.

     False-negative reduction:
     - Do not assume that input is safe without an explicit validation path.
     - Check edge cases such as zero length, negative values, unsigned wraparound, and off-by-one boundaries.

Appendix D.1.2. CWE-189CWE-476 [Positive Transfer]

Transfer pair: CWE-189 (source) → CWE-476 (target), positive transfer. Best validation F1 score = 0.6724 (improvement Δ = + 0.1423 , test F1 score at peak round = 0.6316, validation–test gap = +0.0408). The best prompt is selected at round 4. Selection criterion: A1-positive-transfer-prototypical-success.
Figure A2. Optimization trajectory for CWE-189CWE-476 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Figure A2. Optimization trajectory for CWE-189CWE-476 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Information 17 00762 g0a2
Listing A20. Best prompt for CWE-189 to CWE-476 (round 4, validation F1 = 0.6724).
     INFO_HINT_PROMPT:

     Analyze each code snippet for true exploitable security vulnerabilities only. Output 1 only if all of the following conditions hold; otherwise output 0.

     Conditions for output 1:
     1. External untrusted data reaches a dangerous sink through a direct or indirect path.
     2. No validating check exists on that path, or the existing check is insufficient.
     3. The missing or insufficient check directly enables out-of-bounds access, code execution, or state corruption under realistic input.
     4. The exploitation path is not blocked by defensive code and is not guarded by unreachable conditions or dead code.

     Do not output 1:
     - For isolated benign patterns, such as static strings, constantsize arrays, pointer assignments without dereference, function declarations, or fixedbound loops.
     - If checks fully cover the range of possible inputs.
     - If integer overflow does not affect memory safety.
     - If defensive code correctly handles all error cases.
     - If concurrency issues require unrealistic timing and do not lead to visible corruption or crash.
     - If safe standard functions are used correctly.

     Data-flow and boundary guidance:
     - Trace all paths from input sources to sinks.
     - Integer arithmetic with tainted values must not wrap.
     - Loop bounds derived from tainted input without a hard cap indicate possible out-of-bounds access.
     - Check implicit integer conversions, such as int to size_t.
     - Check unsigned underflow in loop conditions.
     - Check error paths that leave resources or state inconsistent.

     Output only 0 or 1.

Appendix D.1.3. CWE-362CWE-399 [Positive Transfer]

Transfer pair: CWE-362 (source) → CWE-399 (target), positive transfer. Best validation F1 score = 0.7955 (improvement Δ = + 0.1400 , test F1 score at peak round = 0.8268, validation–test gap = −0.0314). The best prompt is selected at round 7. Selection criterion: A1-positive-transfer-prototypical-success.
Figure A3. Optimization trajectory for CWE-362CWE-399 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Figure A3. Optimization trajectory for CWE-362CWE-399 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Information 17 00762 g0a3
Listing A21. Best prompt for CWE-362 to CWE-399 (round 7, validation F1 = 0.7955).
     Focus on actual dangerous operations: buffer overflows from unchecked external input, use-after-free, double-free, race conditions on shared data, and integer overflows that directly cause memory corruption.

     Ignore safe patterns: controlled format strings, struct field accesses, bounded arithmetic, type signatures, debug macros, and test registration macros that only wrap function calls.

     For false negatives, do not dismiss test code. Analyze the implemented function logic, not the registration.

     Use this reasoning checklist:
     1. Does data flow from an untrusted source into a memory operation without size validation?
     2. Is a pointer used after free or realloc?
     3. Is the same memory freed twice?
     4. Is there a data race on a shared object without locking?
     5. Does integer arithmetic wrap and lead to undersized allocation or out-of-bounds write?

     Only flag when a concrete violation is proven by data-flow evidence. Disregard superficial complexity or non-critical lines.

Appendix D.2. Category A2: Negative Transfer with Measurable Optimization Gain

This category contains negative-transfer pairs for which prompt optimization still provides measurable validation of F1 score improvements.

Appendix D.2.1. CWE-787CWE-703 [Negative Transfer]

Transfer pair: CWE-787 (source) → CWE-703 (target), negative transfer. Best validation F1 score = 0.5895 (improvement Δ = + 0.1684 , test F1 score at peak round = 0.5309, validation–test gap = +0.0586). The best prompt is selected at round 9. Selection criterion: A2-negative-transfer-unexpected-gain.
Figure A4. Optimization trajectory for CWE-787CWE-703 (negative transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Figure A4. Optimization trajectory for CWE-787CWE-703 (negative transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Information 17 00762 g0a4
Listing A22. Best prompt for CWE-787 to CWE-703 (round 9, validation F1 = 0.5895).
     Consider the following when analyzing C/C++ code for vulnerabilities:
     - Data flow: track tainted inputs to unsafe operations without validation.
     - Bounds: verify array indices and pointer offsets stay within allocated memory.
     - Integer overflow: check arithmetic on sizes, lengths, and indexes that could wrap and bypass checks.
     - Memory safety: confirm proper allocation and free pairing; avoid use-after-free, double-free, and null pointer dereference.
     - Dangerous functions: strcpy, sprintf, and gets without size limits.
     - False-positive reduction: only flag if the vulnerability path is reachable and not mitigated by existing guards.
     - False-negative reduction: consider edge cases such as negative values, zero-length buffers, unsigned underflow, and hidden paths.
     - CWE-aware focus: buffer overflow, integer overflow, use-afterfree, and null pointer dereference.

Appendix D.2.2. CWE-787CWE-20 [Negative Transfer]

Transfer pair: CWE-787 (source) → CWE-20 (target), negative transfer. Best validation F1 score = 0.5455 (improvement Δ = + 0.1455 , test F1 score at peak round = 0.5547, validation–test gap = −0.0093). The best prompt is selected at round 3. Selection criterion: A2-negative-transfer-unexpected-gain.
Figure A5. Optimization trajectory for CWE-787CWE-20 (negative transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Figure A5. Optimization trajectory for CWE-787CWE-20 (negative transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Information 17 00762 g0a5
Listing A23. Best prompt for CWE-787 to CWE-20 (round 3, validation F1 = 0.5455).
     Analyze C/C++ code for vulnerabilities using strict data-flow and boundary reasoning.

     Checklist:
     1. Identify all external inputs, including network packets, user input, file contents, environment variables, command-line arguments, and data from outside the trust domain.
     2. Trace tainted paths to sensitive sinks such as memcpy, memmove, strcpy, strcat, sprintf, snprintf, read, write, send, recv, malloc, free, array indexing, and pointer arithmetic.
     3. Inspect arithmetic on tainted values used as sizes, indices, or loop bounds.
     4. Verify that loop-based buffer accesses stay within allocated space.
     5. Check use-after-free and double-free paths.
     6. Trace indirect and multi-step flows through arguments, return values, global variables, struct members, and pointer aliases.
     7. Reduce false positives by avoiding flags for constant-size allocations, validated loops, safe wrappers, and trusted constants.
     8. Focus on input validation, buffer safety, integer overflow, and memory lifetime issues.

     Output only 0 or 1.

Appendix D.2.3. CWE-787CWE-200 [Negative Transfer]

Transfer pair: CWE-787 (source) → CWE-200 (target), negative transfer. Best validation F1 score = 0.6897 (improvement Δ = + 0.1413 , test F1 score at peak round = 0.6258, validation–test gap = +0.0639). The best prompt is selected at round 9. Selection criterion: A2-negative-transfer-unexpected-gain.
Figure A6. Optimization trajectory for CWE-787CWE-200 (negative transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Figure A6. Optimization trajectory for CWE-787CWE-200 (negative transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Information 17 00762 g0a6
Listing A24. Best prompt for CWE-787 to CWE-200 (round 9, validation F1 = 0.6897).
     Analyze the code for vulnerabilities with precise reasoning.

     1. Untrusted data to dangerous sinks
     Trace user, network, file, or IPC inputs to memory copies, dynamic allocations, array indexing, pointer arithmetic, file operations, format strings, and shared state.

     2. Bounds and overflow validation
     For every buffer access, confirm that the size or index is checked against actual allocated capacity before use. The check must not be bypassable by integer overflow or off-by-one errors.

     3. Integer handling
     Check multiplication, addition, subtraction, implicit conversions, loop counters, and bit shifts when they affect size, index, or loop bounds.

     4. Memory safety and concurrency
     Check use-after-free, double-free, missing synchronization, race conditions, and resources not released on all paths.

     5. Format string and path traversal
     Flag user-controlled format strings and unsafe path construction.

     Output only 0 or 1.

Appendix D.3. Category B: Smooth Ascending Trajectories

This category contains trajectories with smooth validation F1 score improvement and minimal inter-round fluctuation.

Appendix D.3.1. CWE-399CWE-190 [Positive Transfer]

Transfer pair: CWE-399 (source) → CWE-190 (target), positive transfer. Best validation F1 score = 0.7292 (improvement Δ = + 0.0833 , test F1 score at peak round = 0.7553, validation–test gap = −0.0262). The best prompt is selected at round 3. Selection criterion: B-smooth-ascending.
Figure A7. Optimization trajectory for CWE-399CWE-190 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Figure A7. Optimization trajectory for CWE-399CWE-190 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Information 17 00762 g0a7
Listing A25. Best prompt for CWE-399 to CWE-190 (round 3, validation F1 = 0.7292).
     INFO_HINT_PROMPT:

     Analyze the code for vulnerabilities. Output 1 only if an exploit is clearly reachable under realistic inputs. Output 0 if any required condition fails.

     1. Buffer overflow or out-of-bounds access
     Flag only when user-controlled size or index reaches a memory access without a sufficient bounds check.

     2. Integer overflow
     Flag only when overflow in a size or length calculation directly causes under-allocation, buffer underrun, or out-of-bounds write.

     3. Use-after-free or double-free
     Flag only when a pointer is freed and then dereferenced or freed again on a reachable path.

     4. Null pointer dereference
     Flag only when a possibly NULL pointer is dereferenced without a prior check.

     5. Format string
     Flag only when a user-controlled string is used as the format argument.

     Output only 0 or 1.

Appendix D.3.2. CWE-362CWE-20 [Positive Transfer]

Transfer pair: CWE-362 (source) → CWE-20 (target), positive transfer. Best validation F1 score = 0.7475 (improvement Δ = + 0.0808 , test F1 score at peak round = 0.7192, validation–test gap = +0.0283). The best prompt is selected at round 1. Selection criterion: B-smooth-ascending.
Figure A8. Optimization trajectory for CWE-362CWE-20 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Figure A8. Optimization trajectory for CWE-362CWE-20 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Information 17 00762 g0a8
Listing A26. Best prompt for CWE-362 to CWE-20 (round 1, validation F1 = 0.7475).
     INFO_HINT_PROMPT:

     Focus on actual memory unsafety, integer overflow or underflow, use -after-free, or tainted data flow that leads to security impact. Ignore defensive checks, safe security-related function names, and function signatures alone. Do not flag API calls without context of unsafe input or missing validation. Flag only when the vulnerability logic is present in the code body, not merely in the function name or signature.

     Output only 0 or 1.

Appendix D.3.3. CWE-200CWE-190 [Positive Transfer]

Transfer pair: CWE-200 (source) → CWE-190 (target), positive transfer. Best validation F1 score = 0.7692 (improvement Δ = + 0.0762 , test F1 score at peak round = 0.6927, validation–test gap = +0.0765). The best prompt is selected at round 6. Selection criterion: B-smooth-ascending.
Figure A9. Optimization trajectory for CWE-200CWE-190 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Figure A9. Optimization trajectory for CWE-200CWE-190 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Information 17 00762 g0a9
Listing A27. Best prompt for CWE-200 to CWE-190 (round 6, validation F1 = 0.7692).
     You are a vulnerability detection model for C/C++ code. Analyze the provided code snippet and output 0 for safe or 1 for vulnerable.

     Focus only on observable and exploitable memory safety or controlflow issues. Ignore style, naming, memory leaks, dead code, or low-severity concerns.

     Checklist:
     1. Buffer and string operations
     Flag only when a write to a fixed-size buffer uses an unsafe operation and the source length is not verified against destination capacity before the write.

     2. User input and taint propagation
     Flag only when externally controllable data flows directly into a dangerous sink without sanitization or bounds checks.

     3. Integer overflow
     Flag only when arithmetic overflow directly affects allocation size, memory indexing, or loop bounds.

     4. Memory lifetime
     Flag use-after-free, double-free, or dereference of possibly NULL pointers.

     Output only 0 or 1.

Appendix D.4. Category C: Peak-Then-Drop Trajectories

This category contains trajectories that first improve and then decline, illustrating the risk of prompt overfitting.

Appendix D.4.1. CWE-190CWE-399 [Positive Transfer]

Transfer pair: CWE-190 (source) → CWE-399 (target), positive transfer. Best validation F1 score = 0.7671 (improvement Δ = + 0.1210 , test F1 score at peak round = 0.7211, validation–test gap = +0.0460). The best prompt is selected at round 5. Selection criterion: C-peak-then-drop.
Figure A10. Optimization trajectory for CWE-190CWE-399 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Figure A10. Optimization trajectory for CWE-190CWE-399 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Information 17 00762 g0a10
Listing A28. Best prompt for CWE-190 to CWE-399 (round 5, validation F1 = 0.7671).
     Analyze the code for C/C++ vulnerabilities, including buffer overflow, use-after-free, integer overflow, null pointer dereference, and format string bugs.

     For every path from an input source to a dangerous sink, verify:
     1. Taint propagation through assignments, casts, pointer arithmetic, array indexing, function calls, global variables, and struct fields.
     2. Boundary checks for every memory access involving tainted data.
     3. Integer arithmetic affecting memory size, offset, or index.
     4. Use-after-free after free or realloc.
     5. Null pointer dereference after allocation or pointer-returning functions.
     6. User-controlled format strings.

     Do not mark a check as safe unless it is both present and sufficient for all values of the tainted input.

     Output only 0 or 1.

Appendix D.4.2. CWE-190CWE-476 [Positive Transfer]

Transfer pair: CWE-190 (source) → CWE-476 (target), positive transfer. Best validation F1 score = 0.5806 (improvement Δ = + 0.0894 , test F1 score at peak round = 0.5797, validation–test gap = +0.0009). The best prompt is selected at round 3. Selection criterion: C-peak-then-drop.
Figure A11. Optimization trajectory for CWE-190CWE-476 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Figure A11. Optimization trajectory for CWE-190CWE-476 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Information 17 00762 g0a11
Listing A29. Best prompt for CWE-190 to CWE-476 (round 3, validation F1 = 0.5806).
     INFO_HINT_PROMPT:

     Focus on actual data flow and boundary conditions. Detect vulnerabilities by reasoning through these patterns:
     - Buffer overflow or underflow: tainted length or index used in memory access without valid bounds checks.
     - Integer overflow: tainted arithmetic used as allocation size, array index, or pointer offset.
     - Format string: non-constant format argument in printf-family functions.
     - Use-after-free: pointer dereferenced after free or realloc.
     - Null pointer dereference: possibly NULL pointer dereferenced without a check.

     Output only 0 or 1.

Appendix D.4.3. CWE-362CWE-476 [Positive Transfer]

Transfer pair: CWE-362 (source) → CWE-476 (target), positive transfer. Best validation F1 score = 0.6596 (improvement Δ = + 0.0459 , test F1 score at peak round = 0.6701, validation–test gap = −0.0105). The best prompt is selected at round 6. Selection criterion: C-peak-then-drop.
Figure A12. Optimization trajectory for CWE-362CWE-476 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Figure A12. Optimization trajectory for CWE-362CWE-476 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Information 17 00762 g0a12
Listing A30. Best prompt for CWE-362 to CWE-476 (round 6, validation F1 = 0.6596).
     INFO_HINT_PROMPT:

     Perform static analysis with strict data-flow and control-flow reachability. For each memory or pointer operation, flag a vulnerability if there exists any executable path where the operation executes without sufficient validation or bounds checks.

     To reduce false negatives, flag ambiguous cases where a data-flow path to an unsafe operation exists and the guard is not provably sufficient.

     To reduce false positives, exclude cases where every reachable path is provably safe.

     Checklist:
     1. Identify all memory and pointer reads or writes.
     2. Trace indices, lengths, and sizes back to inputs or computed values.
     3. Verify that each reachable path includes a guard that exactly constrains the operation.
     4. Flag paths where a guard is missing, too weak, or uses an unsafe boundary.
     5. Treat off-by-one, integer overflow, under-allocation, and useafter- free as high-risk patterns.

     Output only 0 or 1.

Appendix D.5. Category D: Fast-Converging Trajectories

This category contains trajectories that reach peak validation performance within the first two optimization rounds.

Appendix D.5.1. CWE-119CWE-399 [Positive Transfer]

Transfer pair: CWE-119 (source) → CWE-399 (target), positive transfer. Best validation F1 score = 0.7941 (improvement Δ = + 0.0000 , test F1 score at peak round = 0.8571, validation–test gap = −0.0630). The best prompt is selected at round 0. Selection criterion: D-fast-converging.
Figure A13. Optimization trajectory for CWE-119CWE-399 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Figure A13. Optimization trajectory for CWE-119CWE-399 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Information 17 00762 g0a13
The best prompt for this trajectory is the empty zero-shot baseline (no information hint), indicating that the initial prompt already achieves the highest validation F1 score and no later revision improves it.

Appendix D.5.2. CWE-119CWE-416 [Negative Transfer]

Transfer pair: CWE-119 (source) → CWE-416 (target), negative transfer. Best validation F1 score = 0.5091 (improvement Δ = + 0.0448 , test F1 score at peak round = 0.5273, validation–test gap = −0.0182). The best prompt is selected at round 1. Selection criterion: D-fast-converging.
Figure A14. Optimization trajectory for CWE-119CWE-416 (negative transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Figure A14. Optimization trajectory for CWE-119CWE-416 (negative transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Information 17 00762 g0a14
Listing A31. Best prompt for CWE-119 to CWE-416 (round 1, validation F1 = 0.5091).
     Analyze the code for potential vulnerabilities by focusing on common unsafe patterns: buffer overflows, integer overflows, format string misuse, use -after-free, double-free, null pointer dereferences, and uninitialized memory.

     Trace data flow from user-controlled inputs to sensitive operations such as memory allocation, array access, pointer dereference, and system calls. Flag any path where input can influence size, index, or length without proper validation. Consider explicit and implicit casts that may truncate or sign-extend values.

     Output only 0 or 1.

Appendix D.6. Category E: Highest Absolute Test F1 Score

This category contains positive-transfer pairs that achieve the highest absolute test F1 scores.

Appendix D.6.1. CWE-200CWE-264 [Positive Transfer]

Transfer pair: CWE-200 (source) → CWE-264 (target), positive transfer. Best validation F1 score = 0.8750 (improvement Δ = + 0.1058 , test F1 score at peak round = 0.8176, validation–test gap = +0.0574). The best prompt is selected at round 4. Selection criteria: E-high-absolute-test-F1; F-validation-test-consistency.
Figure A15. Optimization trajectory for CWE-200CWE-264 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Figure A15. Optimization trajectory for CWE-200CWE-264 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Information 17 00762 g0a15
Listing A32. Best prompt for CWE-200 to CWE-264 (round 4, validation F1 = 0.8750).
     To improve validation positive F1, focus on distinguishing truly vulnerable code from safe code by confirming both the presence of untrusted data flow and the absence of effective sanitization.

     Checklist:
     - Source and sink: trace external data to dangerous sinks.
     - Sanitization validity: a guard is effective only if applied before the sink, uses correct bounds, and cannot be bypassed by integer issues.
     - Bounds and sizes: size arguments must be constants or correctly validated.
     - Format strings: flag only if the format argument is directly user -controlled.
     - Use-after-free: flag only if the pointer is dereferenced after free without reassignment, reallocation, or reset.
     - Control flow: prioritize reachable paths and ignore dead code.

     Output only 0 or 1.

Appendix D.6.2. CWE-264CWE-399 [Positive Transfer]

Transfer pair: CWE-264 (source) → CWE-399 (target), positive transfer. Best validation F1 score = 0.8315 (improvement Δ = + 0.0782 , test F1 score at peak round = 0.8023, validation–test gap = +0.0292). The best prompt is selected at round 8. Selection criterion: E-high-absolute-test-F1.
Figure A16. Optimization trajectory for CWE-264CWE-399 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Figure A16. Optimization trajectory for CWE-264CWE-399 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Information 17 00762 g0a16
Listing A33. Best prompt for CWE-264 to CWE-399 (round 8, validation F1 = 0.8315).
     Analyze C/C++ code for true vulnerabilities: memory safety issues, integer overflow, format string bugs, and type confusion.

     For each potential vulnerability:
     1. Trace untrusted input to sensitive operations.
     2. Check whether validation is effective and cannot be bypassed by overflow, underflow, or signedness issues.
     3. Ensure checks are applied on every reachable path.
     4. Recognize safe patterns such as correct bounds checks, safe wrappers, and managed containers.
     5. Flag common patterns such as buffer overflow, use-after-free, double-free, null pointer dereference, user-controlled format strings, and integer overflow leading to undersized allocation.

     Output 0 only if every path to the sensitive operation has an effective and non-bypassable check.
     Output 1 if any path lacks an effective check.

     Output only 0 or 1.

Appendix D.6.3. CWE-20CWE-399 [Positive Transfer]

Transfer pair: CWE-20 (source) → CWE-399 (target), positive transfer. Best validation F1 score = 0.8421 (improvement Δ = + 0.0421 , test F1 score at peak round = 0.8645, validation–test gap = −0.0224). The best prompt is selected at round 6. Selection criteria: E-high-absolute-test-F1; F-validation-test-consistency.
Figure A17. Optimization trajectory for CWE-20CWE-399 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Figure A17. Optimization trajectory for CWE-20CWE-399 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Information 17 00762 g0a17
Listing A34. Best prompt for CWE-20 to CWE-399 (round 6, validation F1 = 0.8421).
     Analyze C/C++ code for true memory safety vulnerabilities: buffer overflow, out-of-bounds write, use-after-free, null pointer dereference, and integer overflow leading to corruption.

     1. Taint and sink tracing
     Identify inputs from read, recv, gets, scanf, command-line arguments, environment, file I/O, struct fields, globals, return values, and pointer chains.

     2. Validation checks
     A safe check must appear before the operation and must constrain the tainted value against the real buffer capacity or valid range.

     3. Integer issues
     Check overflow, underflow, signedness conversion, and truncation when values influence allocation, indexing, or memory operation sizes.

     4. Memory lifetime
     Check whether freed pointers are reused or freed again, and whether possibly NULL pointers are dereferenced.

     Output only 0 or 1.

Appendix E. Category F: Strongest Validation/Test Consistency

This category contains positive-transfer pairs with the strongest consistency between validation F1 score and test F1 score.

CWE-125CWE-399 [Positive Transfer]

Transfer pair: CWE-125 (source) → CWE-399 (target), positive transfer. Best validation F1 score = 0.8506 (improvement Δ = + 0.0411 , test F1 score at peak round = 0.8519, validation–test gap = −0.0013). The best prompt is selected at round 8. Selection criterion: F-validation-test-consistency.
Figure A18. Optimization trajectory for CWE-125CWE-399 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Figure A18. Optimization trajectory for CWE-125CWE-399 (positive transfer). Validation F1 score (solid line) and test F1 score (dashed line) are shown across 10 optimization rounds. FP and FN error counts are reported on the secondary axis. The dotted vertical line marks the peak validation F1 score round.
Information 17 00762 g0a18
Listing A35. Best prompt for CWE-125 to CWE-399 (round 8, validation F1 = 0.8506).
     INFO_HINT_PROMPT:

     Analyze C/C++ code for true vulnerabilities to maximize positive F1. Use the following reasoning to distinguish vulnerable code from safe code.

     Core principles:
     - Flag if a dangerous operation is reachable with an input that can violate a safety property on any demonstrable data-flow path.
     - Treat functions as correctly implemented only when their contract is evident from the code.
     - Compile-time constants and inherently safe constructs are safe.
     - A check makes a later use safe only if it appears on all paths reaching the dangerous operation.

     Checklist:
     1. Memory and resource checks
     Flag use of a pointer or resource without a required NULL or errorreturn check.
     2. Buffer and bounds checks
     Flag unsafe access if the index, length, or pointer offset is not constrained by the actual capacity.
     3. Integer safety
     Flag arithmetic that can overflow or underflow and then influence allocation, indexing, or loop bounds.
     4. Lifetime safety
     Flag use-after-free and double-free on reachable paths.
     5. Path sensitivity
     Only output 0 if all reachable paths are safe.

     Output only 0 or 1.

References

  1. Chakraborty, S.; Krishna, R.; Ding, Y.; Ray, B. Deep Learning Based Vulnerability Detection: Are We There Yet? IEEE Trans. Softw. Eng. 2022, 48, 3280–3296. [Google Scholar] [CrossRef]
  2. Feng, Z.; Guo, D.; Tang, D.; Duan, N.; Feng, X.; Gong, M.; Shou, L.; Qin, B.; Liu, T.; Jiang, D.; et al. CodeBERT: A Pre-Trained Model for Programming and Natural Languages. In Proceedings of the Findings of the Association for Computational Linguistics: EMNLP 2020, Online, 16–20 November 2020; pp. 1536–1547. [Google Scholar] [CrossRef]
  3. Wang, Y.; Wang, W.; Joty, S.; Hoi, S.C. Codet5: Identifier-aware unified pre-trained encoder-decoder models for code understanding and generation. In Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing, Online, 7–11 November 2021; pp. 8696–8708. [Google Scholar] [CrossRef]
  4. Ding, Y.; Fu, Y.; Ibrahim, O.; Sitawarin, C.; Chen, X.; Alomair, B.; Wagner, D.; Ray, B.; Chen, Y. Vulnerability Detection with Code Language Models: How Far are We? In Proceedings of the 2025 IEEE/ACM 47th International Conference on Software Engineering (ICSE), Lisbon, Portugal, 14–20 April 2025; pp. 1729–1741. [Google Scholar] [CrossRef]
  5. Shin, T.; Razeghi, Y.; Logan, R.L., IV; Wallace, E.; Singh, S. AutoPrompt: Eliciting Knowledge from Language Models with Automatically Generated Prompts. In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP), Online, 16–20 November 2020; pp. 4222–4235. [Google Scholar] [CrossRef]
  6. Gao, T.; Fisch, A.; Chen, D. Making Pre-trained Language Models Better Few-shot Learners. In Proceedings of the 59th Annual Meeting of the Association for Computational Linguistics and the 11th International Joint Conference on Natural Language Processing (Volume 1: Long Papers), Online, 1–6 August 2021; pp. 3816–3830. [Google Scholar] [CrossRef]
  7. Ma, Y.; Luo, S.; Shang, Y.M.; Zhang, Y.; Li, Z. Enhancing source code classification effectiveness via prompt learning incorporating knowledge features. Sci. Rep. 2024, 14, 20220. [Google Scholar] [CrossRef] [PubMed]
  8. Yang, C.; Wang, X.; Lu, Y.; Liu, H.; Le, Q.V.; Zhou, D.; Chen, X. Large Language Models as Optimizers. In Proceedings of the International Conference on Learning Representations, Vienna, Austria, 7–11 May 2024; Volume 2024, pp. 12028–12068. Available online: https://proceedings.iclr.cc/paper_files/paper/2024/file/3339f19c5fcee3ad74502947a32be9e6-Paper-Conference.pdf (accessed on 1 January 2026).
  9. Pryzant, R.; Iter, D.; Li, J.; Lee, Y.; Zhu, C.; Zeng, M. Automatic prompt optimization with "gradient descent" and beam search. In Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing, Singapore, 6–10 December 2023; pp. 7957–7968. [Google Scholar] [CrossRef]
  10. Yuksekgonul, M.; Bianchi, F.; Boen, J.; Liu, S.; Lu, P.; Huang, Z.; Guestrin, C.; Zou, J. Optimizing generative AI by backpropagating language model feedback. Nature 2025, 639, 609–616. [Google Scholar] [CrossRef] [PubMed]
  11. Chang, S.; Geng, C.; Huang, H.; Wang, R.; Li, Q.; Zhang, Y. CodeSpeak: Improving smart contract vulnerability detection via LLM-assisted code analysis. J. Syst. Softw. 2026, 231, 112635. [Google Scholar] [CrossRef]
  12. Li, Z.; Zou, D.; Xu, S.; Jin, H.; Zhu, Y.; Chen, Z. SySeVR: A Framework for Using Deep Learning to Detect Software Vulnerabilities. IEEE Trans. Dependable Secur. Comput. 2022, 19, 2244–2258. [Google Scholar] [CrossRef]
  13. Zhou, Y.; Liu, S.; Siow, J.; Du, X.; Liu, Y. Devign: Effective Vulnerability Identification by Learning Comprehensive Program Semantics via Graph Neural Networks. In Proceedings of the Advances in Neural Information Processing Systems, Vancouver, BC, Canada, 8–14 December 2019; Wallach, H., Larochelle, H., Beygelzimer, A., d’Alché-Buc, F., Fox, E., Garnett, R., Eds.; Curran Associates, Inc.: Red Hook, NY, USA, 2019; Volume 32, Available online: https://proceedings.neurips.cc/paper_files/paper/2019/file/49265d2447bc3bbfe9e76306ce40a31f-Paper.pdf (accessed on 1 January 2026).
  14. Ahmad, W.; Chakraborty, S.; Ray, B.; Chang, K.W. Unified pre-training for program understanding and generation. In Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Online, 6–11 June 2021; pp. 2655–2668. [Google Scholar] [CrossRef]
  15. Guo, D.; Lu, S.; Duan, N.; Wang, Y.; Zhou, M.; Yin, J. Unixcoder: Unified cross-modal pre-training for code representation. In Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), Dublin, Ireland, 22–27 May 2022; pp. 7212–7225. [Google Scholar] [CrossRef]
  16. Fan, J.; Li, Y.; Wang, S.; Nguyen, T.N. A C/C++ Code Vulnerability Dataset with Code Changes and CVE Summaries. In Proceedings of the 17th International Conference on Mining Software Repositories, Seoul, Republic of Korea, 29–30 June 2020; pp. 508–512. [Google Scholar] [CrossRef]
  17. Chen, Y.; Ding, Z.; Alowain, L.; Chen, X.; Wagner, D. Diversevul: A new vulnerable source code dataset for deep learning based vulnerability detection. In Proceedings of the 26th International Symposium on Research in Attacks, Intrusions and Defenses, Hong Kong, China, 16–18 October 2023; pp. 654–668. [Google Scholar] [CrossRef]
  18. Wagner, J.; Müller, S.; Näther, C.; Steghöfer, J.P.; Both, A. Towards Effective Complementary Security Analysis Using Large Language Models. In Proceedings of the 2025 IEEE International Conference on Intelligence and Security Informatics (ISI), Hong Kong, China, 12–13 July 2025; pp. 21–28. [Google Scholar] [CrossRef]
  19. Nazzal, M.; Khalil, I.; Khreishah, A.; Phan, N. PromSec: Prompt Optimization for Secure Generation of Functional Source Code with Large Language Models (LLMs). In Proceedings of the 2024 ACM SIGSAC Conference on Computer and Communications Security, Salt Lake City, UT, USA, 14–18 October 2024; pp. 2266–2280. [Google Scholar] [CrossRef]
  20. Zhou, X.; Cao, S.; Sun, X.; Lo, D. Large Language Model for Vulnerability Detection and Repair: Literature Review and the Road Ahead. ACM Trans. Softw. Eng. Methodol. 2025, 34. [Google Scholar] [CrossRef]
  21. Pearce, H.; Tan, B.; Ahmad, B.; Karri, R.; Dolan-Gavitt, B. Examining zero-shot vulnerability repair with large language models. In Proceedings of the 2023 IEEE Symposium on Security and Privacy, San Francisco, CA, USA, 21–25 May 2023; pp. 2339–2356. [Google Scholar] [CrossRef]
  22. Muske, T.; Serebrenik, A. Survey of Approaches for Handling Static Analysis Alarms. In Proceedings of the 2016 IEEE 16th International Working Conference on Source Code Analysis and Manipulation (SCAM), Raleigh, NC, USA, 2–3 October 2016; pp. 157–166. [Google Scholar] [CrossRef]
  23. Zhou, Y.; Muresanu, A.I.; Han, Z.; Paster, K.; Pitis, S.; Chan, H.; Ba, J. Large Language Models are Human-Level Prompt Engineers. In Proceedings of the Eleventh International Conference on Learning Representations, Kigali, Rwanda, 1–5 May 2023; Available online: https://openreview.net/forum?id=92gvk82DE- (accessed on 1 August 2026).
  24. Kwon, M.; Kim, G.; Kim, J.; Lee, H.; Kim, J. StablePrompt: Automatic Prompt Tuning using Reinforcement Learning for Large Language Model. In Proceedings of the 2024 Conference on Empirical Methods in Natural Language Processing, Miami, FL, USA, 12–16 November 2024; pp. 9868–9884. [Google Scholar] [CrossRef]
  25. Batorski, P.; Swoboda, P. PIAST: Rapid Prompting with In-context Augmentation for Scarce Training data. In Proceedings of the 64th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), San Diego, CA, USA, 2–7 July 2026; pp. 11222–11242. [Google Scholar] [CrossRef]
  26. Dong, Z.; Shang, L.; Olinto, G. GreenTEA: Gradient Descent with Topic-modeling and Evolutionary Auto-prompting. In Proceedings of the First International KDD Workshop on Prompt Optimization, Toronto, ON, Canada, 4 August 2025; Available online: https://openreview.net/forum?id=eoJpYybmOH (accessed on 1 January 2026).
  27. Lee, J.; Seo, W.; An, H.; Lee, S.; Bu, Y. Better by Comparison: Retrieval-Augmented Contrastive Reasoning for Automatic Prompt Optimization. In Proceedings of the 2025 ACM/IEEE Joint Conference on Digital Libraries (JCDL), DeKalb, IL, USA, 15–19 December 2025; pp. 269–272. [Google Scholar] [CrossRef]
  28. Khattab, O.; Singhvi, A.; Maheshwari, P.; Zhang, Z.; Santhanam, K.; A, S.V.; Haq, S.; Sharma, A.; Joshi, T.T.; Moazam, H.; et al. DSPy: Compiling Declarative Language Model Calls into State-of-the-Art Pipelines. In Proceedings of the Twelfth International Conference on Learning Representations, Vienna, Austria, 7–11 May 2024; Available online: https://openreview.net/forum?id=sY5N0zY5Od (accessed on 1 January 2026).
  29. Yang, Y.; Zhou, X.; Mao, R.; Xu, J.; Yang, L.; Zhang, Y.; Shen, H.; Zhang, H. DLAP: A Deep Learning Augmented Large Language Model Prompting framework for software vulnerability detection. J. Syst. Softw. 2025, 219, 112234. [Google Scholar] [CrossRef]
  30. Ribeiro, M.T.; Singh, S.; Guestrin, C. “Why should i trust you?” Explaining the predictions of any classifier. In Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, San Francisco, CA, USA, 13–17 August 2016; pp. 1135–1144. [Google Scholar] [CrossRef]
  31. Lundberg, S.M.; Lee, S.I. A unified approach to interpreting model predictions. In Proceedings of the 31st International Conference on Neural Information Processing Systems, Long Beach, CA, USA, 4–9 December 2017; pp. 4768–4777. Available online: https://dl.acm.org/doi/10.5555/3295222.3295230 (accessed on 1 January 2026).
  32. Sundararajan, M.; Taly, A.; Yan, Q. Axiomatic Attribution for Deep Networks. Proc. Mach. Learn. Res. 2017, 70, 3319–3328. Available online: https://proceedings.mlr.press/v70/sundararajan17a.html (accessed on 1 January 2026).
  33. Qiang, Y.; Pan, D.; Li, C.; Li, X.; Jang, R.; Zhu, D. AttCAT: Explaining Transformers via Attentive Class Activation Tokens. In Proceedings of the Advances in Neural Information Processing Systems, New Orleans, LA, USA, 28 November–9 December 2022; Koyejo, S., Mohamed, S., Agarwal, A., Belgrave, D., Cho, K., Oh, A., Eds.; Curran Associates, Inc.: Red Hook, NY, USA, 2022; Volume 35, pp. 5052–5064. [Google Scholar] [CrossRef]
  34. Song, L.; Cui, Y.; Luo, A.; Lecue, F.; Li, I. Better Explain Transformers by Illuminating Important Information. In Proceedings of the Findings of the Association for Computational Linguistics: EACL 2024, St. Julian’s, Malta, 17–22 March 2024; pp. 2048–2062. [Google Scholar] [CrossRef]
  35. Rabin, M.R.I.; Bui, N.D.; Wang, K.; Yu, Y.; Jiang, L.; Alipour, M.A. On the generalizability of neural program models with respect to semantic-preserving program transformations. Inf. Softw. Technol. 2021, 135, 106552. [Google Scholar] [CrossRef]
  36. Yefet, N.; Alon, U.; Yahav, E. Adversarial examples for models of code. Proc. ACM Program. Lang. 2020, 4, 1–30. [Google Scholar] [CrossRef]
  37. Pintore, M.; Piras, G.; Sotgiu, A.; Pintor, M.; Biggio, B. Evaluating line-level localization ability of learning-based code vulnerability detection models. Mach. Learn. 2026, 115, 94. [Google Scholar] [CrossRef]
  38. Cheng, B.; Zhao, S.; Wang, K.; Wang, M.; Bai, G.; Feng, R.; Guo, Y.; Ma, L.; Wang, H. Beyond Fidelity: Explaining Vulnerability Localization of Learning-Based Detectors. ACM Trans. Softw. Eng. Methodol. 2024, 33, 1–33. [Google Scholar] [CrossRef]
Figure 1. Line-level Integrated Gradients (IG) attribution visualization for a single cross-CWE test sample. The detector is trained on CWE-416 and evaluated on a CWE-399 C/C++ function under the zero-shot prompt setting. Each row corresponds to one source-code line, and darker red indicates a higher line-level attribution score and stronger influence on the model prediction. The model correctly predicts this sample as non-vulnerable.
Figure 1. Line-level Integrated Gradients (IG) attribution visualization for a single cross-CWE test sample. The detector is trained on CWE-416 and evaluated on a CWE-399 C/C++ function under the zero-shot prompt setting. Each row corresponds to one source-code line, and darker red indicates a higher line-level attribution score and stronger influence on the model prediction. The model correctly predicts this sample as non-vulnerable.
Information 17 00762 g001
Figure 2. Simplified prompt construction and optimization framework used in the comparison. All methods share the same detection prompt format and fixed local detector, and differ only in how the information hint is constructed or optimized. Manual methods use fixed hints, general automated baselines use validation feedback, and Fine-IGPO uses validation errors together with code-token-level IG evidence to guide hint optimization.
Figure 2. Simplified prompt construction and optimization framework used in the comparison. All methods share the same detection prompt format and fixed local detector, and differ only in how the information hint is constructed or optimized. Manual methods use fixed hints, general automated baselines use validation feedback, and Fine-IGPO uses validation errors together with code-token-level IG evidence to guide hint optimization.
Information 17 00762 g002
Figure 3. Workflow of Integrated-Gradient-Guided Prompt Optimization (IGPO). In each round, the current prompt is evaluated on the target validation set to collect false-positive and false-negative samples. IGPO computes code-token-restricted IG, aggregates token attributions into influential source-code lines, and uses the resulting diagnostic evidence to guide LLM-based prompt revision. The final prompt is selected from the prompt history according to the validation F1 score.
Figure 3. Workflow of Integrated-Gradient-Guided Prompt Optimization (IGPO). In each round, the current prompt is evaluated on the target validation set to collect false-positive and false-negative samples. IGPO computes code-token-restricted IG, aggregates token attributions into influential source-code lines, and uses the resulting diagnostic evidence to guide LLM-based prompt revision. The final prompt is selected from the prompt history according to the validation F1 score.
Information 17 00762 g003
Figure 4. F1 score heatmap of cross-CWE transfer evaluation. Rows denote source CWE categories used for fine-tuning, and columns denote target CWE categories used for evaluation. To improve readability, cell-level numerical annotations are omitted from the main figure, and the complete F1 score matrix is provided in the appendix. Darker blue indicates stronger transfer performance, while lighter/redder colors indicate weaker transfer performance. Black cells indicate strict degenerate predictions.
Figure 4. F1 score heatmap of cross-CWE transfer evaluation. Rows denote source CWE categories used for fine-tuning, and columns denote target CWE categories used for evaluation. To improve readability, cell-level numerical annotations are omitted from the main figure, and the complete F1 score matrix is provided in the appendix. Darker blue indicates stronger transfer performance, while lighter/redder colors indicate weaker transfer performance. Black cells indicate strict degenerate predictions.
Information 17 00762 g004
Table 1. Selected CWE categories used in the experiments.
Table 1. Selected CWE categories used in the experiments.
CWEDescription
CWE-284Improper Access Control
CWE-416Use After Free
CWE-200Exposure of Sensitive Information
CWE-399Resource Management Errors
CWE-264Permissions, Privileges, and Access Controls
CWE-119Improper Restriction of Operations within the Bounds of a Memory Buffer
CWE-20Improper Input Validation
CWE-190Integer Overflow or Wraparound
CWE-189Numeric Errors
CWE-362Race Condition
CWE-787Out-of-bounds Write
CWE-125Out-of-bounds Read
CWE-476NULL Pointer Dereference
CWE-703Improper Check or Handling of Exceptional Conditions
Table 2. Dataset sample counts by CWE before and after deduplication.
Table 2. Dataset sample counts by CWE before and after deduplication.
CWERaw PosRaw NegDedup PosDedup NegDedup Rate (%)
CWE-20276649,627195832,30629.2
CWE-1194,6459,514288135,41230.8
CWE-125256835,304167523,53934.8
CWE-18974714,252516741930.9
CWE-190108115,01380610,21725.4
CWE-200145025,23198614,96132.0
CWE-26486123,44760512,96029.7
CWE-2845429884437717319.4
CWE-36274316,325546947726.5
CWE-399135425,872100816,85125.6
CWE-416144935,942114125,15921.3
CWE-476124824,42990516,35827.5
CWE-703100419,24788415,59911.9
CWE-787187426,315161422,16213.9
Total21,851380,40215,962249,59327.0
Dedup Rate indicates the proportion of positive samples removed.
Table 3. Main feedback signals used by automated prompt optimization methods.
Table 3. Main feedback signals used by automated prompt optimization methods.
MethodMain Feedback Signal
Fine-CodeSpeakCode-oriented feedback generated for validation samples
Fine-DLAP-simplifiedSimplified validation-based prompt adaptation feedback
Fine-OPROHistorical prompts and validation metrics
Fine-TextGradNatural-language textual gradients and error feedback
Fine-IGPOIG-selected lines, FP/FN error types, LLM error diagnosis, and validation metrics
Table 4. Summary of zero-shot cross-CWE transfer behavior over the 14-CWE transfer matrix.
Table 4. Summary of zero-shot cross-CWE transfer behavior over the 14-CWE transfer matrix.
SettingCountAverage PrecisionAverage RecallAverage F1 Score
Diagonal source–target pairs140.8601
All non-diagonal transfer pairs1820.64190.73580.6518
Positive-transfer pairs159
Negative-transfer pairs23
Table 5. Performance comparison on 159 positive-transfer pairs.
Table 5. Performance comparison on 159 positive-transfer pairs.
MethodAvg. F1 ScoreAvg. ΔF1 vs. FineExceed FineExceed RatioAvg. RankPred. Degen.
Fine-IGPO0.72670.048715194.97%1.30196/3.77%
Fine-TextGrad0.69750.019510465.41%3.89314/2.52%
Fine-OPRO0.69740.01958654.09%4.11645/3.14%
Fine-role-play0.67820.00074125.95%5.74689/5.66%
Fine-ZS0.67800.00005.94039/5.66%
Fine-CWE-definition0.6772−0.00034327.22%5.740510/6.29%
Fine-checklist0.6681−0.00942918.35%6.37976/3.77%
Fine-CodeSpeak0.6546−0.02346842.77%6.31130/0.00%
Fine-few-shot 0.6526−0.02537245.28%6.86485/3.14%
Fine-few-shot 0.6480−0.02956339.87%6.762719/11.95%
Fine-DLAP-simplified0.6270−0.05102415.09%8.74840/0.00%
Avg. ΔF1 is computed relative to Fine-ZS. “Exceed Fine” reports the number (and proportion) of transfer pairs where a method outperforms Fine-ZS. “Pred. Degen.” reports the count (and rate) of prediction degeneration cases (recall 1 , precision 0.5 ). Examples drawn from the target validation split. Examples drawn from the source validation split.
Table 6. Ablation results on positive-transfer pairs. The best value in each column is shown in bold.
Table 6. Ablation results on positive-transfer pairs. The best value in each column is shown in bold.
VariantAverage PrecisionAverage RecallAverage F1 Score
Full error samples without IG attribution0.57940.76630.6598
Random two code lines0.54440.37540.4243
FN-only feedback0.54030.79500.6421
FP-only feedback0.64430.56610.5987
Without LLM error diagnosis0.63210.80590.7085
Top-4 IG-selected lines0.61580.72110.6639
Top-6 IG-selected lines0.61010.52300.5570
IGPO full0.66640.83780.7267
Table 7. Prompt optimization stability statistics across 182 cross-CWE transfer pairs.
Table 7. Prompt optimization stability statistics across 182 cross-CWE transfer pairs.
IndicatorAll (182)Positive (159)Negative (23)
Val set size (samples)808080
Avg. optimization rounds10.010.010.0
Mean val. F1 score std across rounds0.0370.0350.053
Median val. F1 score std across rounds0.0300.0290.055
Avg. peak round (0-indexed)3.583.454.48
Best prompt in first half (%)59.359.756.5
Best prompt at final round (%)8.85.730.4
Avg. val–test F1 score gap0.0330.0280.071
Avg. val F1 score improvement ( Δ )0.0440.0400.069
Table 8. Case analysis of attribution-guided prompt optimization for CWE-416.
Table 8. Case analysis of attribution-guided prompt optimization for CWE-416.
RoundPrompt FocusMetricIG-Based Diagnostic Feedback
R0Defines CWE-416 as alloc–free–use lifecycle tracing across execution paths.F1 score: 0.5849; Precision: 0.5536; Recall: 0.6200High-attribution regions in FP cases are often associated with names, constants, and return statements; FN cases show relatively weak attribution on lifetime-related operations.
R1Adds positive and negative examples for direct UAF and safe reassignment after free.F1 score: 0.8000; Precision: 0.7333; Recall: 0.8800Recall improves substantially. The remaining FP cases still show high attribution on unrelated names, getter-like functions, and reference-counting cues.
R2Adds a negative example where freeing followed by return is safe.F1 score: 0.6458; Precision: 0.6739; Recall: 0.6200The prompt becomes more conservative. In FN cases, attribution is more frequently observed around cleanup or state-update operations rather than explicit use-after-free patterns.
R3Adds an alias-based positive example where one pointer is freed and another alias is later used.F1 score: 0.7273; Precision: 0.5854; Recall: 0.9600Recall increases, but precision drops. The attribution pattern suggests that the detector may be over-sensitive to pointer-like names and benign return statements.
R4Adds a positive example where passing the address of a freed pointer is treated as unsafe use.F1 score: 0.7218; Precision: 0.5783; Recall: 0.9600High recall is maintained, but FP cases continue to show high attribution on surface-level tokens and benign pointer-return patterns.
IG-based diagnostic feedback should not be interpreted as causal explanations of vulnerabilities.
Table 9. IG-based attribution patterns observed during prompt evolution.
Table 9. IG-based attribution patterns observed during prompt evolution.
Error TypeIG SignalPrompt Implication
FPSurface tokens, such as names, constants, or return statementsAvoid treating superficial cues as sufficient vulnerability evidence
FPReference-counting or lifetime-related fields without unsafe accessRequire complete alloc–free–use evidence
FNCleanup, nullification, or state-update operationsTrack state changes after deallocation
FNDeallocation followed by alias useStrengthen cross-statement lifetime and alias reasoning
Table 10. Case study on a CWE-125 sample (rpa_read_buffer).
Table 10. Case study on a CWE-125 sample (rpa_read_buffer).
LineCode SnippetIG ScoreSem. Relevant
Sample: Vulnerable (target = 1)
   IG-selected lines
12return 0;3.145√ boundary logic
17*data += 1 + len;2.640√ pointer arith.
   Randomly selected lines
6(empty line)× no semantics
20}× no semantics
Sample: Patched (target = 0)
   IG-selected lines
17*data += 1 + len;19.401√ pointer arith.
14*buffer = p_malloc(pool, len);6.556√ memory alloc.
   Randomly selected lines
6(empty line)× no semantics
20}× no semantics
Table 11. Approximate computational cost averaged over one transfer pair without caching intermediate results.
Table 11. Approximate computational cost averaged over one transfer pair without caching intermediate results.
MethodOptimizer CallsTime (s)Main Cost Source
CodeSpeak160 *1536Per-sample feedback generation
DLAP-simplified160 *1937Per-sample prompt-adaptation feedback
OPRO4110Iterative prompt generation and validation
TextGrad17180Textual-gradient feedback and prompt revision
IGPO17922Integrated-gradient computation and prompt revision
* The method calls the optimizer once per validation sample; intermediate results may be cached when the same samples are reused, but are required for each new sample in a one-pass deployment.
Table 12. Summary of IGPO behavior on 23 negative-transfer pairs.
Table 12. Summary of IGPO behavior on 23 negative-transfer pairs.
OutcomeNumber of PairsRatio (%)
Fully recovers to Base-ZS level417.4
Partially stabilizes degradation1043.5
Marginally aggravates degradation939.1
Base-ZS outperforms IGPO1982.6
“Fully recovers” indicates that IGPO reaches the Base-ZS level. “Partially stabilizes” indicates that IGPO improves over Fine-ZS but remains below Base-ZS. “Marginally aggravates” indicates that IGPO further decreases F1 compared with Fine-ZS.
Table 13. CWE distribution in negative-transfer pairs.
Table 13. CWE distribution in negative-transfer pairs.
CWE TypeNumber of PairsRatio Among Negative-Transfer Pairs (%)
CWE-7871460.9
CWE-7036
CWE-1195
A CWE may appear either as the source or target CWE in a transfer pair.
Table 14. Preliminary sensitivity analysis on 20 positive-transfer pairs.
Table 14. Preliminary sensitivity analysis on 20 positive-transfer pairs.
Detector BackboneOptimizer ModelPairsFine-ZS F1 ScoreFine-IGPO F1 ScoreAvg. ΔF1Win Rate
Qwen2.5-Coder-7BDeepSeek-V4-Flash200.66120.71140.0502100.00%
Qwen2.5-Coder-7BGPT-5.5200.66120.70360.0424100.00%
DeepSeek-Coder-6.7BDeepSeek-V4-Flash200.65370.70060.0469100.00%
DeepSeek-Coder-6.7BGPT-5.5200.65370.72130.0676100.00%
Avg. ΔF1 = Fine-IGPO F1 − Fine-ZS F1.
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.

Share and Cite

MDPI and ACS Style

Xie, X.; Lu, Z.; Yao, N. Attribution-Guided Prompt Optimization for Cross-CWE Vulnerability Detection. Information 2026, 17, 762. https://doi.org/10.3390/info17080762

AMA Style

Xie X, Lu Z, Yao N. Attribution-Guided Prompt Optimization for Cross-CWE Vulnerability Detection. Information. 2026; 17(8):762. https://doi.org/10.3390/info17080762

Chicago/Turabian Style

Xie, Xudong, Zhimao Lu, and Nianmin Yao. 2026. "Attribution-Guided Prompt Optimization for Cross-CWE Vulnerability Detection" Information 17, no. 8: 762. https://doi.org/10.3390/info17080762

APA Style

Xie, X., Lu, Z., & Yao, N. (2026). Attribution-Guided Prompt Optimization for Cross-CWE Vulnerability Detection. Information, 17(8), 762. https://doi.org/10.3390/info17080762

Note that from the first issue of 2016, this journal uses article numbers instead of page numbers. See further details here.

Article Metrics

Back to TopTop