Manuscript Offprint
arXiv:2610.33756Enhancing LLM-Based Vulnerability Detection via Representation-Aware Logical Ensemble
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Francesco Crescenzo Grasso [0009-0004-1551-1628], Pietro Liguori [0000-0001-5579-1696], Roberto Natella [0000-0003-1084-4824], and Domenico Cotroneo [0000-0001-7103-592X]
*corresponding author
DIETI, University of Naples Federico II, Naples, NA 80125, Italy {francescocrescenzo.grasso,pietro.liguori}@unina.it
Computer Science, Gran Sasso Science Institute, L'Aquila, AQ 67100, Italy roberto.natella@gssi.it
Computer Science, University of North Carolina at Charlotte, Charlotte, NC 28223, USA
Abstract. Automated vulnerability detection in C source code is a longstanding challenge, as traditional static analysis tools often trade precision for scalability and struggle with complex vulnerability patterns. Recently, large language models (LLMs) have shown promising results; yet, most approaches rely on a single code representation, implicitly assuming uniform suitability across vulnerability types. In this work, we systematically study LLM-based vulnerability detection under multiple code representations, including raw source code, Abstract Syntax Trees (AST), and Control Flow Graphs (CFG). Through extensive empirical analysis, we show that different representations exhibit complementary strengths, with specific views being more effective for particular classes of vulnerabilities. Building on these findings, we propose a Representation-Aware Logical Ensemble (RALE) that integrates LLMs trained on different code representations through explicit logical rules and majority voting. While single-representation models achieve up to 73% F1-score, our integrated approach reaches 78% F1-score, with commensurate gains in accuracy, precision, and recall, consistently outperforming individual models. These results highlight the importance of explicitly leveraging complementary code representations when combining LLMs for effective vulnerability detection.
Keywords: Software Security · Vulnerability Detection · Code Representation Learning · Ensemble Learning.
1 Introduction
The detection of software vulnerabilities represents a key challenge in computer security. Weaknesses such as memory corruption errors and improper resource
F.C. Grasso et al.
management continue to be among the most exploited classes of vulnerabilities [10], motivating the need for automated and reliable detection techniques that can scale to large and complex codebases. Vulnerability detection traditionally relies on static or dynamic analysis. However, static tools tend to produce a high number of false positives [1], while dynamic tools are limited by execution coverage and computational costs [15]. Furthermore, both methods do not natively operate at a function-level granularity [12].
In recent years, data-driven approaches based on deep learning [2,3,9,14,23] have emerged as a promising alternative to traditional static analysis, aiming to automatically learn vulnerability patterns directly from source code. More recently, advances in large language models (LLMs) have further improved performance in a wide range of code-related tasks, including vulnerability detection, by leveraging large-scale pretraining and contextual representations.
Most of the state-of-the-art approaches process source code primarily as plain text [3,9,14], relying on token-based representations that only implicitly encode program semantics. As a result, crucial structural properties, e.g., syntactic hierarchy and control-flow behavior, are either weakly captured or entirely overlooked. Many studies [2,23] attempt to address these limitations by modeling code as graphs, such as Code Property Graphs (CPGs) or Abstract Syntax Trees (ASTs), explicitly encoding structural and execution-related information. These methods typically focus on a single representation and do not fully exploit the complementary nature of different program views. Consequently, their detection capability remains constrained to the specific aspects emphasized by the chosen representation.
In this work, we explore vulnerability detection through the lens of code representation. Rather than assuming a single optimal view of code, we investigate how different program representations, i.e., raw source code, Abstract Syntax Trees (ASTs), and Control Flow Graphs (CFGs), capture complementary vulnerability-related signals. Using real-world datasets, we systematically train and evaluate LLM-based classifiers on each representation and analyze their behavior at both global and vulnerability-type levels. Building on this analysis, we propose a representation-aware logical ensemble that combines predictions across heterogeneous representations using explicit and interpretable logical rules. The design of the ensemble is guided by security-oriented considerations, favoring decision strategies that mitigate missed vulnerabilities while preserving robustness on non-vulnerable samples.
Our work proposes the following contributions:
– We present a comprehensive evaluation of LLM-based vulnerability detection across heterogeneous code representations, showing that raw code, ASTs, and CFGs capture complementary security-relevant information and exhibit distinct specializations across vulnerability types.
– We introduce a Representation-Aware Logical Ensemble (RALE) that outperforms single-representation models and standard voting schemes, achieving up to 78% accuracy and F1-score on a real-world dataset.
The remainder of the paper is structured as follows. Section 2 elaborates on background concepts related to the target problem. Section 3 describes the methodology, including the extraction and generation of representations. Section 4 presents the experimental setup and the subsequent evaluation and analysis. Section 5 highlights the lessons learned. Section 6 examines related work, while Section 7 discusses threats to validity. Finally, Section 8 concludes the paper.
Traditional vulnerability detection relies on static and dynamic analysis. Static tools [16, 21] analyze code without execution, often constructing intermediate representations such as ASTs and CFGs; however, they tend to produce a high number of false positives [1]. Dynamic analysis [8, 19] observes runtime behavior, offering higher precision in specific scenarios, but it is limited by execution coverage and computational cost [15]. Moreover, most traditional methods do not natively operate at function-level granularity [12].
Recent research has increasingly explored learning-based approaches to automate vulnerability detection. In particular, large language models (LLMs) have demonstrated strong potential by learning vulnerability patterns directly from large corpora of code. Many existing methods treat source code as plain text [3, 9, 14], leveraging the ability of neural models to capture statistical regularities in token sequences. While effective, purely token-based representations may overlook structural and semantic properties that are explicitly encoded in program analysis artifacts. To better capture such properties, several works have proposed leveraging graph-based representations of code. Chakraborty et al. [2] introduced a deep learning approach based on the Code Property Graph (CPG), a unified representation that combines elements of control-flow and data-flow graphs. Similarly, Zhou et al. [23] employed CPGs in conjunction with graph neural networks to learn vulnerability patterns. These approaches highlight the importance of structural representations in modeling program behavior.
More generally, different intermediate representations encode distinct aspects of a program. The Abstract Syntax Tree (AST) provides a hierarchical representation of the programs syntactic structure, explicitly modeling relationships between language constructs, such as expressions and statements. In contrast, the Control Flow Graph (CFG) captures execution semantics by representing possible control transfers between basic blocks of instructions. Each representation emphasizes specific syntactic or semantic properties, suggesting that they may offer complementary perspectives for downstream analysis tasks.
F.C. Grasso et al.
In machine learning, ensemble learning is a well-established paradigm for improving predictive performance by combining multiple models. Ensemble strategies have also been explored in vulnerability detection to improve robustness and predictive stability [18, 22]. The central intuition is that different models may capture different patterns in the data, and their errors are often only partially correlated. By aggregating diverse predictors through strategies such as majority voting, weighted voting, or probability averaging, ensemble methods can reduce variance, mitigate individual biases, and improve robustness and generalization. When models operate on heterogeneous input representations, ensemble techniques can further leverage representational diversity, potentially integrating complementary information captured by distinct views of the same underlying data.
3 Methodology
Our proposed framework follows a structured process of data generation, representation-specific fine-tuning, and logical ensemble aggregation to maximize vulnerability detection coverage.
3.1 Data Pipeline
To support vulnerability detection and further analysis, we adopted MegaVul, a large-scale real-world vulnerability dataset for C/C++ introduced by Chao et al. [11]. It includes 17,380 vulnerable and 322,168 non-vulnerable functions extracted from 992 open-source repositories, covering 169 CWE types. Compared to other datasets [3,6], a key feature is the availability of multiple code representations. In addition to raw source code, it provides node paths for:
– Abstract Syntax Trees (ASTs), capturing the hierarchical syntactic structure of the function;
– Control Flow Graphs (CFGs), modeling the execution flow through branches, loops, and decision points.
Both representations are generated using the Joern [7] static analysis tool. They enable a systematic comparison of LLM performance across different structural views of the same code.
Data Extraction. Since the graphs are provided in a raw format, an intermediate processing phase was needed to make them suitable for learning models. The extraction process involved parsing the serialized graph outputs to reconstruct the topology of each function. For each function, we represent the code as a directed graph , where each node is characterized by its syntactic label (e.g., CALL), operation name (e.g., < operator > .assignment), and the corresponding source code snippet. The edge set encodes structural hierarchy in the AST and execution flow in the CFG.
All graph representations were converted into adjacency-list format to ensure uniformity across representations and compatibility with LLM inputs.
Table 1. Preprocessing and Abstraction of an AST Node equivalent to a single instruction.
| Feature | Complete Instruction | Structural Instruction |
|---|---|---|
| Raw Node | BinaryOperator 0x14e90c2d8 '<' | BinaryOperator |
| Raw Node (Call) | CallExpr 0x14e925f18 'malloc' | CallExpr |
| Code Snippet | *buffer = malloc(kBuffer...) | Removed |
| Metadata | <line:9, col:13> | Removed |
| Addresses | 0x14e90bf58 | Removed |
Data Generation. In addition to the dataset-provided graphs, ASTs were independently generated from the source code using Clang [16] to ensure consistency, enable alternative representations, and mitigate potential tool-specific biases. While Clang reliably produces high-quality ASTs for function-level snippets, its native CFG extraction assumes access to a complete translation unit with fully resolved includes and macro definitions. Since our experimental setting operates on isolated functions extracted from larger projects, we rely exclusively on Joerns CFG extraction pipeline, which is designed to process partial code fragments without requiring full project compilation.
Data Preprocessing. Furthermore, we defined two abstraction levels:
– Complete Representation: Retains the full semantic context, including operation names and code snippets (e.g., variable assignments and function calls), providing the model with the logic of the implementation.
– Structural Representation: Strips all identifiers and literals, preserving only the node type and the graph topology to evaluate whether the vulnerability can be detected solely through the "shape" of the code.
Table 1 highlights the abstraction of an AST node, corresponding to a single instruction. In this transformation, the BinaryOperator and CallExpr types are preserved as the fundamental structural identity, while auxiliary information, such as memory addresses and source code locations, is discarded.
AST and CFG representations were further normalized by removing newline characters and filtering instances outside predefined token-length bounds.
On the other hand, source code has been lightly preprocessed to remove irrelevant elements related to vulnerability semantics. Specifically, comments (single-line // and multi-line / * ... */) and pre-processor directives (e.g., #include, #define) were removed, as they do not affect program behavior.
Data Balancing. State-of-the-art vulnerability detection often contends with highly imbalanced datasets [3], where non-vulnerable samples significantly outnumber security flaws (e.g., a 95% to 5% ratio). While this reflects real-world conditions, it poses a significant challenge for supervised learning, making accuracy a misleading metric due to majority-class bias.
To mitigate this discrepancy, we experimented with different dataset splits. As shown in Appendix A, a 50/50 balanced distribution yielded the most robust results across all metrics. Although this strong undersampling deviates from
F.C. Grasso et al.
real-world operational distributions, it prevents models from being overwhelmed by the majority class and isolates the true predictive power of each code representation. Consequently, these findings remain highly valuable, providing clear insights into how representations inherently capture vulnerability patterns when freed from severe distributional bias.
3.2 Vulnerability Detection
The following stage of the methodology focuses on model training and evaluation, with the primary goal of assessing the effectiveness of different code representations for vulnerability detection. We consider transformer-based models adapted to a binary classification task, where each C/C++ function is labeled as vulnerable or non-vulnerable.
To systematically evaluate the impact of code representation on model performance, we conducted a cross-comparative analysis involving three distinct architectures and seven functional representations. The representations were categorized into Complete and Structural versions, generated through both Joern and Clang frameworks, and covered three fundamental formats: AST, CFG, and Source Code. This exhaustive setup, except for Clang CFG, yielded a total of 21 independent experiments, ensuring that every model representation pair was rigorously tested. Such a structured approach allows us to isolate the influence of specific graph topologies and semantic densities, ultimately identifying the most suitable representation for vulnerability detection tasks.
A traditional static analysis tool was included as a baseline to provide a reference point for learned approaches. All experiments were conducted under a unified training and evaluation protocol and assessed using standard classification metrics, including accuracy, precision, recall, and F1-score, ensuring that performance differences are primarily attributable to the chosen representation.
3.3 Representation-Aware Logical Ensemble (RALE)
Following the single-representation experiments, we conducted a detailed empirical analysis of the results across vulnerability categories. The analysis reveals that different code representations exhibit heterogeneous performance patterns: some representations consistently perform better for a specific class of vulnerabilities while underperforming on others. This variability suggests that no single representation is uniformly optimal and that their predictive behaviors are complementary.
Motivated by this observation, we introduced a Representation-Aware Logical Ensemble strategy, whose pivotal idea is to leverage the complementary strengths of heterogeneous code views. Rather than training models jointly, we aggregated the predictions of independently trained representation-specific detectors through explicit logical rules, preserving modularity and interpretability.
4 Experimental Evaluation
Experimental evaluation involves comparing fine-tuned models, analyzing results, and presenting the RALE framework.
4.1 Fine-Tuning Setup
All experiments were conducted on a workstation equipped with an Intel 12th Gen Core i7 processor, a NVIDIA GeForce GTX 1660 GPU with 6 GB of VRAM, and 32 GB of system RAM. This hardware configuration proved sufficient to support training and inference across all experimental phases, enabling repeated evaluation cycles and consistent comparison of model configurations and preprocessing choices.
Selected models, listed below, are pre-trained on large-scale code corpora and subsequently fine-tuned on AST, CFG, and code vulnerability detection tasks:
– CodeT5 220M (Base) [20] is employed as a reference encoderdecoder model, leveraging span-denoising pre-training and a hybrid architecture that has demonstrated strong performance in both code understanding and vulnerability detection tasks.
– CodeBERT 125M (Base) [5], an encoder-only model based on RoBERTa, is included to evaluate the effectiveness of rich contextual representations during block-level encoding.
– CodeGPT 124M [13], a decoder-only autoregressive model, has been adapted for vulnerability detection via classification heads applied to the final hidden states.
To ensure architectural consistency for the classification task, CodeBERT, an encoder-only model, was directly fine-tuned with a classification head. For CodeT5, an encoderdecoder model, we followed the approach established by Wang et al. [20], retaining only the encoder component to extract sequence representations. For CodeGPT, a decoder-only model, based on the GPT architecture, we employed the standard sequence classification variant established by Radford et al. [13], where prediction is performed using the hidden state of the last non-padding token. To prevent overfitting, early stopping was applied uniformly across all experiments: training was terminated if the validation loss increased with respect to the previous epoch. As a result, the number of effective training epochs varied slightly across models and representations, while ensuring that each model converged to its best validation performance. Data were split into 88% for training, 6% for validation, and 6% for testing.
F.C. Grasso et al.
4.2 Evaluation of Fine-Tuned LLMs
We evaluate the effectiveness of different code representations across LLMs using the standard metrics, i.e., accuracy, precision, recall, and F1-score.
Table 2. Performance of LLMs trained on different code representations
| Encoding | CodeT5 | CodeBERT | CodeGPT | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Acc | Prec | Rec | F1 | Acc | Prec | Rec | F1 | Acc | Prec | Rec | F1 | |
| Flawfinder | - | - | - | - | - | - | - | - | 0.53 | 0.56 | 0.53 | 0.46 |
| Raw Code | 0.70 | 0.72 | 0.68 | 0.70 | 0.73 | 0.72 | 0.74 | 0.73 | 0.71 | 0.73 | 0.69 | 0.71 |
| CC AST | 0.62 | 0.61 | 0.63 | 0.62 | 0.66 | 0.68 | 0.64 | 0.66 | 0.65 | 0.64 | 0.66 | 0.65 |
| CS AST | 0.61 | 0.63 | 0.59 | 0.61 | 0.63 | 0.62 | 0.64 | 0.63 | 0.62 | 0.62 | 0.62 | 0.62 |
| JC AST | 0.70 | 0.71 | 0.69 | 0.70 | 0.71 | 0.71 | 0.71 | 0.71 | 0.70 | 0.68 | 0.72 | 0.70 |
| JS AST | 0.67 | 0.66 | 0.68 | 0.67 | 0.67 | 0.67 | 0.67 | 0.67 | 0.67 | 0.69 | 0.65 | 0.67 |
| JC CFG | 0.66 | 0.68 | 0.64 | 0.66 | 0.67 | 0.69 | 0.65 | 0.67 | 0.68 | 0.70 | 0.66 | 0.68 |
| JS CFG | 0.65 | 0.65 | 0.65 | 0.65 | 0.66 | 0.67 | 0.65 | 0.66 | 0.67 | 0.67 | 0.67 | 0.67 |
Note: In XY AST or XY CFG, X indicates the frontend (J = Joern, C = Clang), and Y indicates the representation type (S = Structural, C = Complete). Flawfinder is included as a static analysis baseline (independent of LLM encodings).
As shown in Table 2, across all models, raw source code consistently achieves the highest overall performance, confirming that lexical and semantic information is highly informative for vulnerability detection. Among structured representations, Joern Complete AST and Joern Complete CFG provide the strongest results, closely matching raw code and outperforming other structural or Clang-based variants. In contrast, representations that remove semantic or execution-related details show noticeable performance drops.
Our empirical observations suggest that performance trends are primarily representation-driven rather than strictly model-specific, highlighting the intrinsic discriminative power of raw code and complete AST/CFG structures. Nevertheless, it's worth noting that while no significant performance bias is observed between the different architectures, CodeBERT [5] mostly achieves the best overall results. This confirms that an encoder-only architecture remains the most effective choice for discriminative tasks such as vulnerability classification. Overall, raw code, Joern Complete AST, and Joern Complete CFG emerge as the best-performing representations for their respective categories, motivating their use in the subsequent representation-aware ensemble.
Importantly, these results raise the question of whether the high-performing representations identify the same vulnerable functions or complementary subsets. Investigating this overlap is crucial to inform the design of the subsequent representation-aware ensemble, where combining complementary predictions can further improve detection performance.

Fig. 1. Log-scaled distribution of correct over total predictions of the test set across different representations and selected macro vulnerability categories reported in Appendix B
4.3 Performance Across Vulnerability Macro-Categories
In this section, we analyze how models trained on different code representations perform across types of vulnerable functions. Figure 1 shows a log-scale histogram of correct predictions over the total for each representation and macro-category. To avoid an excessive number of categories, CWEs were grouped into macro-categories, e.g., CWE-125: Out-of-bounds Read [17] falls under Buffer Overflow; CWE-20: Improper Input Validation falls under Input Validation and Injection. Full details are provided in Appendix B.
We observe that:
– Raw Source Code performs best on Buffer Overflow, Input Validation and Injection, and Memory Management, as these categories rely heavily on semantic details such as variable usage, pointer operations, and data manipulation patterns, which are most explicitly preserved in raw code.
– CFGs excel at detecting Resource Management and Concurrency Issues due to their explicit modeling of execution paths, branching, and loops, which are critical for reasoning about resource lifetimes and race conditions.
– ASTs show improved performance on Error Handling and Logic Issues since their hierarchical structure emphasizes syntactic constructs and control relationships, aiding the detection of incorrect branching, missing checks, or improper exception handling.
In summary, raw code, ASTs, and CFGs capture complementary aspects of program behavior: raw code provides rich semantic and syntactic context, ASTs emphasize structural and logical organization, and CFGs highlight execution dynamics. This complementarity explains the observed variation in CWE-level performance and motivates a representation-aware ensemble, which leverages the strengths of each representation to achieve more robust and comprehensive vulnerability detection.
F.C. Grasso et al.

Fig. 2. Overlap and complementarity of prediction errors across different representations on a half of the test set where discrepancies between predictions are most pronounced
4.4 File-Level Complementarity Analysis
A deeper analysis of model predictions at the file level reveals substantial disagreement among models, indicating that each captures only partially overlapping vulnerability signals. We perform a complementary analysis, examining whether errors made by one representation are corrected by others. In this context, complementary means that models do not fail on the same examples. For instance, if raw code, AST, and CFG consistently make identical errors, an ensemble would offer no benefit. The key question is whether vulnerabilities missed by one model are correctly identified by another.
Figure 2 emphasizes this behavior through a binary heatmap of vulnerable (top) and non-vulnerable (bottom) functions. For clarity, we focus on half of the test set where discrepancies between predictions are most pronounced.
The analysis shows that the raw source code model exhibits a higher false positive rate compared to AST- and CFG-based models, while AST achieves the lowest false positive rate overall. However, this apparent disadvantage is offset by the raw code models superior performance on vulnerable samples, frequently detecting cases missed by other representations. Such complementary behavior indicates that simple model selection is suboptimal and motivates combining predictions through logical gates to improve robustness.
4.5 Logical Ensemble Evaluation
As a first aggregation strategy, we adopt a majority voting mechanism, i.e., 2-out-of-3, where a function is classified as vulnerable if at least two of the three models (raw code, AST, CFG) predict a vulnerability. This approach reduces the impact of individual model errors, particularly false positives on non-vulnerable samples. Conceptually, this mechanism introduces democratic decision-making, where no single representation dominates.
However, a closer inspection reveals that many false negatives of the raw code model are corrected by AST or CFG. In security-critical contexts, false negatives are more costly than false positives, as undetected vulnerabilities pose

Fig. 3. RALE architecture: integration of LLMs trained on Raw Code, AST, and CFG through a representation-aware logical ensemble governed by the boolean expression (AST CFG) Code
a higher risk than over-flagged safe functions. This observation motivates the introduction of a bias in favor of the raw code predictions.
To preserve the raw code models strong recall, we implement a hybrid decision rule. Specifically, if the raw code model predicts a function as vulnerable, this prediction is taken as final. In all other cases, the standard 2-out-of-3 majority voting is applied, which is equivalent to a logical OR between the raw code model and the majority voting system. This hybrid approach combines the high recall of the raw code with the improved false-positive control of the AST and CFG.
Table 3. Performance of ensemble strategies on unseen code
| Representation / Ensemble | Acc. | Prec. | Rec. | F1 |
|---|---|---|---|---|
| CodeGPT on JC CFG | 0.68 | 0.70 | 0.66 | 0.68 |
| CodeBERT on JC AST | 0.71 | 0.71 | 0.71 | 0.71 |
| CodeBERT on Code | 0.73 | 0.72 | 0.74 | 0.73 |
| Majority Voting | 0.75 | 0.75 | 0.75 | 0.75 |
| RALE | 0.78 | 0.77 | 0.79 | 0.78 |
Table 3 reports performance using the Ensemble Mechanisms. Majority voting yields a consistent improvement of approximately across evaluation metrics compared to the raw code baseline, while RALE provides the largest performance gains, with overall improvements of approximately in accuracy, precision, recall, and F1-score relative to the raw code baseline.
F.C. Grasso et al.
Figure 3 illustrates the RALE architecture. For clarity, the figure presents a simplified version of the ensemble logic using boolean algebra.
(2-out-of-3) ∨ Code
(1)
The original weighted ensemble logic (1) can be expressed as (2). By first applying the associativity of ∨ and then the absorption law , the expression (2) simplifies to (3). This compact form clarifies the decision rule: a vulnerability is flagged if the Code model detects it, or if both the AST and the CFG models agree. Moreover, it reduces logical complexity and computational overhead compared to heavier ensemble architectures.
5 Lesson Learned
Our systematic study highlights three fundamental lessons for effective vulnerability detection:
(i) Complementarity of Code Views: Since different code representations (e.g., AST, CFG, raw source) highlight distinct structural and semantic properties, models trained on these diverse views capture fundamentally different vulnerability patterns. This suggests that a "one-size-fits-all" representation limits the detection capability of LLMs.
(ii) Simplicity vs. Effectiveness: Leveraging multiple representations through a logical ensemble (RALE) proves to be as simple as it is effective. This approach offers a powerful trade-off, achieving high detection performance (up to 78% F1-score), without the prohibitive computational complexity often associated with more opaque or deeply nested hybrid architectures.
(iii) Practical Deployment: In real-world settings, we position RALE as a semi-automated human assistant, given the inevitable trade-offs in precision and recall. Rather than completely replacing manual review, the framework should be leveraged as an early-warning tool that provides initial suggestions on where vulnerabilities might reside.
6 Related Work
Traditional approaches rely on static and dynamic analysis. Dynamic analysis [8,19] observes program execution to detect vulnerabilities, offering high precision in specific scenarios; however, it is constrained by limited execution coverage and high computational costs. Static analysis [16,21] examines code without execution, often constructing intermediate representations such as ASTs and CFGs. Despite their effectiveness, both approaches have limitations: dynamic analysis requires extensive manual configuration and scales poorly to large codebases, whereas static analyzers tend to produce high numbers of false positives [1]. Moreover, most traditional methods do not natively operate at function-level granularity [12].
Recent studies have explored data-driven approaches to automate vulnerability identification. Large Language Models (LLMs) have shown strong potential by learning vulnerability patterns directly from large code corpora. Existing methods typically treat code as plain text [3,9,14], leveraging neural networks ability to capture statistical regularities in token sequences. In addition, some approaches rely on synthetic code [14] as training data; however, prior work [2] has shown that synthetic samples often fail to reflect real-world vulnerability patterns, limiting their effectiveness in practical settings. Among them, Li et al. [9] use code gadgets for deep-learning-based vulnerability detection. Chen et al. [3] train token-level models achieving high accuracy but limited F1-score, while Russell et al. [14] learn deep feature representations to identify vulnerabilities. Several works emphasize the benefits of structural code representations. Chakraborty et al. [2] employ Code Property Graphs (CPGs), combining control-flow and data-flow information for deep-learning models. Similarly, Zhou et al. [23] use CPGs with graph neural networks to capture vulnerability patterns. These studies highlight that different structural representations can capture complementary aspects of program behavior.
In vulnerability detection, ensembles have been applied to enhance robustness and stability [18,22]. Wang et al. [18] propose PreNNsem, a heterogeneous ensemble operating on sample vectors. Cho do Xuan et al. [22] combine a Code Understanding (CU) module with a Vulnerability Encoder (VE) based on embeddings. While prior work has explored either single-representation LLMs or ensemble strategies, most approaches implicitly assume uniform suitability across vulnerability types. In contrast, our work systematically investigates LLMs over multiple code representations (Raw Code, AST, CFG) and explicitly integrates them via a representation-aware logical ensemble (RALE). This allows us to exploit complementary strengths of each representation, prioritize high-precision components (e.g., Code), and achieve improved detection performance, particularly reducing false negatives.
7 Threats To Validity
We identify several limitations of our study:
(i) Empirical Scope: Our findings are grounded in the specific datasets and experimental settings adopted. While these provide a diverse set of examples, results including the relative performance of code representations may vary when applied to different programming languages, proprietary codebases, or distinct vulnerability types.
(ii) Model Selection: Although we utilize state-of-the-art architectures like CodeBERT [3], the choice of backbone affects validity. While our results confirm the superiority of encoder-only architectures for this classification task, using larger
F.C. Grasso et al.
generative models or different hyperparameter optimizations might lead to different performance baselines.
(iii) Test Set Distribution: During the validation phase, we systematically experimented with different undersampling ratios to determine the optimal training balance. However, our final evaluation was conducted on balanced test sets. While this standard practice ensures a controlled environment for comparing code representations, it does not fully reflect real-world vulnerability detection scenarios, where vulnerable code is naturally highly imbalanced, and the actual false positive rate could be higher.
8 Conclusion
Our work highlights the value of representation-aware model integration, showing that carefully designed logical ensembles can significantly improve the effectiveness and reliability of automated vulnerability detection. By leveraging the complementary strengths of source code, AST, and CFG representations, the RALE framework achieves a 5% improvement in F1-score over single-representation models. Furthermore, a key finding of our study is the efficacy of the hybrid decision rule: by prioritizing the raw code models recall while utilizing a 2-out-of-3 majority voting for consensus, we successfully minimize critical false negatives without the typical explosion of false positives.
Acknowledgments
This work was supported by the European Union NextGenerationEU under the PNRR (Piano Nazionale di Ripresa e Resilienza), Mission 4, Component 2, Investment 'I.3.4 Borse PNRR transizioni digitali e ambientali', through Ministerial Decree no. 118 (02-03-2023), and the MUR Department of Excellence 2023 - 2027 grant at GSSI (Gran Sasso Science Institute). The authors would like to express their gratitude to the former student, Luigi Scotto Rosato.
A Balancing Test
In Table 4, preliminary tests using a Random Forest classifier trained on Megavul [11] demonstrate that a 50/50 distribution yields the most robust results across all performance metrics. This balancing strategy ensures that the model assigns equal importance to both classes, preventing the optimization process from being dominated by the majority "non-vulnerable" class, thus enhancing sensitivity, i.e., the true positive rate, towards critical security flaws.
B CWE to Macro-categories Mapping
We grouped individual Common Weakness Enumerations (CWEs) into eight distinct macro-categories, as shown in Table 5, to evaluate model performance across functionally similar vulnerability types.
Table 4. Impact of Dataset Distribution on Model Performance
| Distribution (NV/V) | Acc | Prec | Rec | F1 |
|---|---|---|---|---|
| 95% / 5% (Imbalanced) | 0.95 | 0.00 | 0.00 | 0.00 |
| 70% / 30% | 0.78 | 0.52 | 0.45 | 0.48 |
| 50% / 50% (Balanced) | 0.68 | 0.65 | 0.71 | 0.68 |
Table 5. Mapping of CWE Categories to Macro-Categories
| Macro-Category | Included CWEs |
|---|---|
| Buffer Overflow | CWE-119, CWE-125, CWE-787, CWE-120, CWE-122 |
| Memory Management | CWE-415, CWE-416, CWE-401 |
| Resource Management | CWE-400, CWE-399, CWE-835, CWE-770, CWE-772 |
| Input Validation and Injection | CWE-20, CWE-22, CWE-189, CWE-190 |
| Information Exposure | CWE-200, CWE-254 |
| Concurrency Issues | CWE-362 |
| Security Features | CWE-264, CWE-287 |
| Error Handling and Logic Issues | CWE-617, CWE-369, CWE-476, CWE-674 |
References
-
Ayewah, N., Pugh, W., Morgenthaler, J.D., Penix, J., Zhou, Y.: Evaluating static analysis defect warnings on production software. In: Proceedings of the 7th ACM SIGPLAN-SIGSOFT workshop on Program analysis for software tools and engineering. pp. 1–8 (2007)
-
Chakraborty, S., Krishna, R., Ding, Y., Ray, B.: Deep learning based vulnerability detection: Are we there yet? (2022). https://doi.org/10.1109/TSE.2021.3087402
-
Chen, Y., Ding, Z., Alowain, L., Chen, X., Wagner, D.: Diversevul: A new vulnerable source code dataset for deep learning based vulnerability detection (2023)
-
Corporation, T.M.: Common Weakness Enumeration (CWE), https://cwe.mitre.org/
-
Feng, Z., Guo, D., Tang, D., Duan, N., Feng, X., Gong, M., Shou, L., Qin, B., Liu, T., Jiang, D., Zhou, M.: Codebert: A pre-trained model for programming and natural languages (2020)
-
Grahn, D., Zhang, J.: An analysis of c/c++ datasets for machine learning-assisted software vulnerability detection. In: Proceedings of the Conference on Applied Machine Learning for Information Security, 2021 (2021)
-
joern.io: Joern: The Bug Hunter's Workbench. https://github.com/joernio/joern (Jan 2024), version 2.0
-
Lemieux, C., Sen, K.: Fairfuzz: A targeted mutation strategy for increasing grey-box fuzz testing coverage. In: Proceedings of the 33rd ACM/IEEE international conference on automated software engineering. pp. 475–485 (2018)
F.C. Grasso et al.
-
Li, Z., Zou, D., Xu, S., Ou, X., Jin, H., Wang, S., Deng, Z., Zhong, Y.: Vuldeep-ecker: A deep learning-based system for vulnerability detection. arXiv preprint arXiv:1801.01681 (2018)
-
MITRE CWE Content Team: 2025 CWE Top 25 Most Dangerous Software Weaknesses (2025), Accessed: 6 February 2026
-
Ni, C., Shen, L., Yang, X., Zhu, Y., Wang, S.: Megavul: A c/c++ vulnerability dataset with comprehensive code representations. In: Proceedings of the 21st International Conference on Mining Software Repositories. p. 738742. MSR 24, ACM (Apr 2024). https://doi.org/10.1145/3643991.3644886, http://dx.doi.org/10.1145/3643991.3644886
-
Pistoia, M., Chandra, S., Fink, S.J., Yahav, E.: A survey of static analysis methods for identifying security vulnerabilities in software systems. IBM Systems Journal 46(2), 265–288 (2007). https://doi.org/10.1147/sj.462.0265
-
Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., Sutskever, I.: Language models are unsupervised multitask learners. OpenAI blog 1(8), 9 (2019)
-
Russell, R., Kim, L., Hamilton, L., Lazovich, T., Harer, J., Ozdemir, O., Ellingwood, P., McConley, M.: Automated vulnerability detection in source code using deep representation learning. In: 2018 17th IEEE International Conference on Machine Learning and Applications (ICMLA). pp. 757–762 (2018). https://doi.org/10.1109/ICMLA.2018.00120
-
Schwartz, E.J., Avgerinos, T., Brumley, D.: All you ever wanted to know about dynamic taint analysis and forward symbolic execution (but might have been afraid to ask). In: 2010 IEEE Symposium on Security and Privacy. pp. 317–331 (2010). https://doi.org/10.1109/SP.2010.26
-
The LLVM Project: Clang: a c language family frontend for llvm (2026), https://clang.llvm.org/
-
The MITRE Corporation: CWE-125: Out-of-bounds Read. https://cwe.mitre.org/data/definitions/125.html (2024), Accessed: 22 May 2024
-
Wang, L., Li, X., Wang, R., Xin, Y., Gao, M., Chen, Y.: Prennsem: A heterogeneous ensemble learning framework for vulnerability detection in software. Applied Sciences 10(22) (2020). https://doi.org/10.3390/app10227954, https://www.mdpi.com/2076-3417/10/22/7954
-
Wang, T., Wei, T., Lin, Z., Zou, W.: Intscope: Automatically detecting integer overflow vulnerability in x86 binary using symbolic execution. In: NDSS. pp. 1–14 (2009)
-
Wang, Y., Wang, W., Joty, S., Hoi, S.C.H.: Codet5: Identifier-aware unified pre-trained encoder-decoder models for code understanding and generation (2021)
-
Wheeler, D.A.: Flawfinder: a static analysis tool for finding vulnerabilities in c/c++ source code, https://dwheeler.com/flawfinder/
-
Xuan, C.D., Quang, D.B., Quang, V.D.: A novel approach for software vulnerability detection based on ensemble learning model. Computers and Electrical Engineering 130, 110848 (2026). https://doi.org/https://doi.org/10.1016/j.compeleceng.2025.110848
-
Zhou, Y., Liu, S., Siow, J., Du, X., Liu, Y.: Devign: Effective vulnerability identification by learning comprehensive program semantics via graph neural networks (2019)