<?xml-model href='http://www.tei-c.org/release/xml/tei/custom/schema/relaxng/tei_all.rng' schematypens='http://relaxng.org/ns/structure/1.0'?><TEI xmlns="http://www.tei-c.org/ns/1.0">
	<teiHeader>
		<fileDesc>
			<titleStmt><title level='a'>Efficient Adaptation of Large Language Models for Smart Contract Vulnerability Detection</title></titleStmt>
			<publicationStmt>
				<publisher>ACM</publisher>
				<date>06/26/2025</date>
			</publicationStmt>
			<sourceDesc>
				<bibl> 
					<idno type="par_id">10612995</idno>
					<idno type="doi">10.1145/3727582.3728688</idno>
					
					<author>Fadul Sikder</author><author>Yu Lei</author><author>Yuede Ji</author>
				</bibl>
			</sourceDesc>
		</fileDesc>
		<profileDesc>
			<abstract><ab><![CDATA[Smart contracts underpin decentralized applications but face significant security risks from vulnerabilities, while traditional analysis methods have limitations. Large Language Models (LLMs) offer promise for vulnerability detection, yet adapting these powerful models efficiently, particularly generative ones, remains challenging. This paper investigates two key strategies for the efficient adaptation of LLMs for Solidity smart contract vulnerability detection: (1) replacing token-level generation with a dedicated classification head during fine-tuning, and (2) selectively freezing lower transformer layers using Low-Rank Adaptation (LoRA). Our empirical evaluation demonstrates that the classification head approach enables models like Llama 3.2 3B to achieve high accuracy (77.5%), rivaling the performance of significantly larger models such as the fine-tuned GPT-3.5. Furthermore, we show that selectively freezing bottom layers reduces training time and memory usage by approximately 10-20% with minimal impact on accuracy. Notably, larger models (3B vs. 1B parameters) exhibit greater resilience to layer freezing, maintaining high accuracy even with a large proportion of layers frozen, suggesting a localization of general code understanding in lower layers versus task-specific vulnerability patterns in upper layers. These findings present practical insights for developing and deploying performant LLM-based vulnerability detection systems efficiently, particularly in resource-constrained settings.]]></ab></abstract>
		</profileDesc>
	</teiHeader>
	<text><body xmlns="http://www.tei-c.org/ns/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink">
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="1">Introduction</head><p>Blockchain technology has revolutionized various sectors by enabling secure, transparent, and decentralized transactions <ref type="bibr">[24]</ref>. A key application of this innovation is smart contracts, self-executing contracts with the terms of the agreement directly written into code. These programmatic agreements have found applications across diverse domains, including nance, supply chain management, and digital identity verication <ref type="bibr">[42]</ref>.</p><p>Smart contracts, particularly on platforms like Ethereum, have experienced exponential growth in recent years, with the total value locked (TVL) in decentralized nance (DeFi) smart contracts alone surpassing $50 billion as of 2023 <ref type="bibr">[2]</ref>. This rapid adoption, however, has brought with it a signicant rise in security vulnerabilities and exploits. The immutable nature of blockchain, while foundational to its trust model, exacerbates the impact of any aws in smart contracts. Once deployed, a vulnerable contract cannot be easily patched, making it an attractive target for malicious actors <ref type="bibr">[18]</ref>.</p><p>The consequences of smart contract vulnerabilities can be severe. In 2023 alone, hacking incidents involving smart contracts resulted in approximately $1.84 billion in nancial losses across 751 incidents <ref type="bibr">[6]</ref>. These breaches not only cause substantial nancial damage but also lead to legal disputes and undermine trust in blockchain technology. Given the high stakes and potential for signicant reputational damage, ensuring the security and correctness of smart contracts has become a critical priority for developers, auditors, and blockchain platforms alike.</p><p>Traditional approaches to smart contract security analysis, broadly categorized into static and dynamic analysis, face signicant limitations. Static analysis techniques, particularly symbolic execution and model checking, attempt to systematically explore program states by analyzing code without execution. While symbolic execution can theoretically provide complete coverage by exploring all possible execution paths, it encounters severe scalability challenges when dealing with smart contracts due to the state explosion problem and complex environmental dependencies <ref type="bibr">[33,</ref><ref type="bibr">34]</ref>. Dynamic analysis methods, including fuzz testing, must navigate a vast and complex state space with concrete input, making comprehensive exploration challenging. Both static and dynamic approaches often rely on expert-driven heuristics to narrow the search space, which can lead to oversights in vulnerability detection <ref type="bibr">[27]</ref>. Furthermore, the rigidity of predened rules in static analysis tools frequently results in high rates of false positives and negatives, as they struggle to adapt to the rapid emergence of new vulnerability patterns in the blockchain ecosystem <ref type="bibr">[31]</ref>.</p><p>Machine learning models for smart contract vulnerability detection have made signicant strides, oering notable improvements over traditional rule-based methods. However, many approaches, particularly graph-based neural networks and NLP-based models, require substantial feature engineering, such as converting source code into graph representations or extracting specic code properties, which constrains their ability to adapt and generalize to new or complex vulnerabilities. Additionally, the eectiveness of these models can vary signicantly based on the quality and comprehensiveness of the engineered features, leading to inconsistent performance across dierent types of smart contracts and vulnerability classes <ref type="bibr">[37]</ref>.</p><p>Building on the challenges and constraints of feature-engineered machine learning solutions, large language models (LLMs) have emerged as a promising alternative for smart contract security analysis. Since this class of neural networks is designed to handle tasks involving long-sequence processing, LLMs can directly analyze Solidity source code with minimal preprocessing, leveraging their broad language understanding to identify subtle vulnerability patterns <ref type="bibr">[15]</ref>. Broadly, two core approaches have been explored for using LLMs in smart contract vulnerability detection: prompt-based inference and ne-tuning-based adaptation.</p><p>In the prompt-based paradigm, researchers query a pretrained model (e.g., GPT-3.5, GPT-4) using carefully designed instructions to extract vulnerability-related insights without modifying its internal parameters. This method enables rapid deployment and supports various vulnerability types. Examples include ChatGPT's chain-ofthought prompts <ref type="bibr">[7]</ref> and GPT-4-assisted logic checks <ref type="bibr">[8]</ref>, which allow the LLM to "reason" about potential aws in a contract. However, prompt-based approaches frequently suer from model hallucinations, high false-positive rates, and recall limitations when faced with novel or complex exploit scenarios <ref type="bibr">[8,</ref><ref type="bibr">30]</ref>. Additionally, performance is highly sensitive to prompt quality-slight variations in phrasing can lead to inconsistent results.</p><p>In contrast, ne-tuning-based approaches address these shortcomings by training or partially re-training LLMs on curated vulnerability datasets. This process aligns the model's internal representations more closely with Solidity semantics and common exploit patterns, signicantly improving recall and precision <ref type="bibr">[1,</ref><ref type="bibr">41]</ref>. However, ne-tuning comes at the cost of substantial computational overhead and requires comprehensive, labeled vulnerability datasets. Despite these challenges, ne-tuned models demonstrate enhanced robustness, emphasizing the importance of updating model weights and adapting LLMs for domain-specic tasks such as Solidity smart contract vulnerability classication.</p><p>A prominent challenge in ne-tuning large language models (LLMs) for classication tasks is reconciling the generative nature of many popular architectures (e.g., decoder-only GPT variants) with the requirement to select outputs from a xed set of class labels. In most ne-tuning workows, the model is trained on a supervised dataset to generate the next token corresponding to the correct label (or label words) for each input example <ref type="bibr">[20]</ref>. This token-level classication approach leverages the model's existing decoder to output a label token from its vocabulary set (e.g., "Vulnerable, " "Safe, " "Overow"). While this method is direct and intuitive, it poses a signicant risk: the decoder may generate irrelevant tokens that do not match the desired class labels. To mitigate this, researchers often impose constraints on token generation or apply post-processing techniques to map the output to the nearest recognized label <ref type="bibr">[12]</ref>. Beyond irrelevant token generation, LLMs are inherently prone to hallucination-the generation of content that appears plausible but is factually incorrect or unfounded <ref type="bibr">[3]</ref>. Even when generating class labels, the model may occasionally "hallucinate" labels that do not belong to the predetermined set, especially when faced with ambiguous inputs or edge cases outside their training distribution.</p><p>An alternative approach treats the LLM's nal hidden representations as feature vectors rather than relying on its decoder to produce a label token <ref type="bibr">[12]</ref>. Instead of generating class names as the next word, a custom classication head-such as a fully connected layer-is added on top of the model's nal (or penultimate) Transformer layer. This method replaces token-level classication with a standard softmax layer trained on the model's output embeddings, transforming the LLM into a feature-extractor-plus-classier pipeline. The classication head outputs discrete class probabilities for each vulnerability type, reducing the likelihood of hallucinated labels outside of recognized classes. Studies suggest that this approach improves accuracy in domain-specic tasks by leveraging the semantic abstractions learned by the LLM's encoder or decoder blocks while avoiding extraneous token generation <ref type="bibr">[11,</ref><ref type="bibr">12]</ref>.</p><p>Fine-tuning an LLM for specialized tasks like smart contract security introduces computational and architectural challenges. Fully retraining every layer is expensive. To mitigate these issues, parameter-ecient ne-tuning methods such as LoRA <ref type="bibr">[14]</ref> and QLoRA <ref type="bibr">[9]</ref> have been developed. These techniques freeze most model weights and update only small adapter modules or low-rank parameter osets, signicantly reducing computational overhead. A related strategy, layer-wise ne-tuning, explores whether freezing maintains (or even enhances) domain performance <ref type="bibr">[19]</ref>. From a transfer learning perspective-which underpins modern LLM netuning-it is crucial to determine which portions of the model require adaptation for a new domain. Lower layers typically capture general syntactic and lexical patterns, while upper layers encode more domain-and task-specic features <ref type="bibr">[11,</ref><ref type="bibr">39]</ref>. This raises a key question: What happens if we freeze the lower layers entirely and ne-tune only the top few layers (along with a classication head)? If eective, this approach could indicate that LLMs can be ne-tuned in a more specialized way for domain-specic tasks like security vulnerability detection in Solidity smart contracts. Additionally, it could reduce training costs without sacricing accuracy, making it an ecient strategy for domain-specic adaptation.</p><p>In this paper, we address these challenges by investigating the eectiveness of dierent ne-tuning congurations for large language models in the context of smart contract vulnerability detection. Our research is guided by two key research questions that examine the trade-os between dierent classication approaches and layer-wise ne-tuning strategies. These questions aim to provide insights into reducing the computational requirements for LLM-based vulnerability detection systems without signicant compromise on performance. By systematically evaluating these approaches, we contribute to the ongoing discourse on adapting large language models for specialized security tasks in the blockchain domain. Below are the two key research questions we aim to answer: RQ1: Is ne-tuning an LLM with a dedicated classier head eective for detecting smart contract vulnerabilities?</p><p>We investigate how adding a dedicated classication layer on top of the LLM's nal hidden representations aects vulnerability detection accuracy.</p><p>RQ2: Does restricting ne-tuning to specic high-level Transformer layers (while freezing lower layers) achieve competitive performance on vulnerability classication?</p><p>Here, we investigate whether layer-wise ne-tuning (combined with a classication head) can adapt the LLM's capabilities to domain specic tasks like smart contract vulnerability detection while reducing computational overhead.</p><p>The remainder of this paper is organized as follows: Section 2 provides background on LLMs and ne-tuning relevant to smart contract security. Section 3 details our methodology, including model selection, the classication head architecture, datasets, and evaluation strategy. Section 4 presents the experimental setup, results, and discussion for both research questions. Section 5 reviews related work in LLM-based vulnerability detection, and Section 6 concludes with our ndings and future research directions.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="2">Background 2.1 Large Language Models</head><p>Large Language Models (LLMs), based on transformer-based neural network architectures, have emerged as a transformative force in natural language processing (NLP) and, more recently, in software development tasks such as code generation, completion, and debugging. LLMs are characterized by their large scale, often consisting of billions of parameters, which enables them to capture complex patterns and relationships within vast amounts of textual data <ref type="bibr">[5]</ref>. The transformer architecture, introduced by Vaswani et al. <ref type="bibr">[32]</ref>, allows ecient parallel processing of input sequences using self-attention mechanisms, making it particularly eective in capturing long-range dependencies in text-a key feature for generating coherent and contextually relevant content.</p><p>LLMs typically undergo a two-phase development process: pretraining and ne-tuning. Pre-training is an self-supervised learning process where models are exposed to extensive corpora of text, including diverse sources such as books, websites, and code repositories. This exposure enables the model to develop a broad understanding of language structure, semantics, and domain-specic knowledge. The pre-training objective is usually autoregressive, where the model learns to predict the next token in a sequence based on the previous tokens <ref type="bibr">[26]</ref>.</p><p>For particular downstream tasks like smart contract vulnerability detection, pre-trained LLMs are further rened through ne-tuning. This process involves additional training on smaller, task-specic label datasets, enabling the model to specialize in particular applications. Fine-tuning can involve updating all model parameters or, in more resource-ecient methods, adjusting only a subset of parameters while keeping most of the pre-trained weights frozen <ref type="bibr">[13]</ref>.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="2.2">Transfer Learning and Fine-Tuning</head><p>The adaptation of pre-trained models via transfer learning and ne-tuning is a cornerstone of modern deep learning. Foundational work, particularly in computer vision, established that lower layers of deep networks often learn general features (e.g., edges and textures) transferable across tasks, while upper layers capture more task-specic information <ref type="bibr">[39]</ref>. This insight motivated early netuning strategies involving freezing lower layers and retraining only the upper ones for new domains <ref type="bibr">[39]</ref>.</p><p>The evolution continued with methods addressing challenges like overtting on small target datasets and catastrophic forgetting-where general knowledge is lost during specialized training <ref type="bibr">[22]</ref>. Frameworks like ULMFiT <ref type="bibr">[13]</ref> introduced gradual unfreezing techniques, while models like BERT <ref type="bibr">[10]</ref> demonstrated the success of full end-to-end ne-tuning on task-specic data. Research also indicated that the optimal strategy (feature extraction vs. full ne-tuning) can depend on the similarity between the pre-training and target tasks <ref type="bibr">[25]</ref>.</p><p>With the advent of extremely large models (e.g., GPT-3 with 175B parameters <ref type="bibr">[5]</ref>), the computational cost of full ne-tuning necessitated more ecient approaches, as noted in the Introduction. Parameter-Ecient Fine-Tuning (PEFT) methods, such as Low-Rank Adaptation (LoRA) <ref type="bibr">[14]</ref> and its quantized variant QLoRA <ref type="bibr">[9]</ref>, signicantly reduce resource needs by updating only small, lowrank adapters instead of all weights. Alongside PEFT, selective or layer-wise ne-tuning-updating only a subset of layers-has proven eective. For instance, studies like Lee et al. <ref type="bibr">[19]</ref> have shown that ne-tuning only the top layers (e.g., the top 25% in BERT or RoBERTa) can retain a large fraction ( 90%) of the performance achieved by full ne-tuning, while substantially lowering training costs. Such strategies help preserve the model's core linguistic or domain knowledge encoded in lower layers while eciently specializing the upper layers for the target task, also mitigating catastrophic forgetting <ref type="bibr">[22]</ref>.</p><p>This overall trend towards balancing performance with computational eciency is highly relevant for adapting LLMs to specialized domains like smart contract vulnerability detection. Although Solidity presents unique syntax and semantics, it builds on general programming concepts potentially learned during pre-training. Therefore, ne-tuning approaches that leverage this pre-existing knowledge by selectively adapting higher-level representations to identify vulnerability patterns, such as the layer-freezing techniques investigated in this paper, are particularly promising.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="3">Methodology</head><p>This section outlines our methodology for adapting Large Language Models (LLMs) to detect smart contract vulnerabilities. We explain the rationale guiding our key decisions concerning four primary components: (1) model selection criteria and process, (2) architectural modications for classication, (3) dataset selection and preparation, and (4) evaluation strategies. This section documents the analytical process that informed our experimental design, aimed at addressing the research questions posed earlier.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="3.1">Model Selection</head><p>Selecting an appropriate Large Language Model (LLM) for smart contract vulnerability detection requires careful consideration of several key factors: context window size, model parameters (computational footprint), and domain-specic training data (Solidity inclusion). These factors signicantly impact the model's ability to process and analyze complex smart contracts eectively.</p><p>A large context window is crucial for smart contract analysis, as vulnerabilities often arise from interactions spanning dierent code sections, potentially across lengthy contracts. Analysis of typical Solidity contract lengths reveals this need; using the StarCoder tokenizer, approximately 27% of contracts in a representative dataset subset exceeded 2,000 tokens, and about 12% surpassed 4,000 tokens (Figure <ref type="figure">1</ref>). This makes models with limited context windows (e.g., GPT-2: 1,024, CodeT5: 512 tokens) impractical without signicant preprocessing that could obscure context. Therefore, models capable of handling sequences exceeding 4,000 tokens were deemed necessary. However, larger model parameters and context windows increase computational demands. While prior work highlights resourceintensive requirements even for moderately sized models (e.g., Storhaug et al. <ref type="bibr">[29]</ref> reported needing multiple high-end GPUs and extended training time for a 6B parameter model), our primary constraint stemmed from direct experience. Attempts to ne-tune models with 7B or more parameters (such as StarCoder-7B, LLaMA 3-8B, or CodeLlama-7b) on our target single NVIDIA A100 40GB GPU consistently failed due to memory limitations when processing the extended sequence lengths typical of smart contracts. This established a practical upper bound of 3B parameters for our experimental setup.</p><p>Another crucial factor is the inclusion of domain-specic training data. Models pre-trained on datasets containing Solidity source code are likely to better understand its specic syntax and semantics, potentially improving vulnerability detection.</p><p>Another crucial factor in model selection is the composition of the training data, particularly the inclusion of Solidity source code. Models pre-trained on datasets that include Solidity code are likely to have a better understanding of smart contract-specic syntax and semantics, potentially leading to more accurate vulnerability detection. While other powerful models exist (e.g., GPT family, Claude, DeepSeek, Qwen), our selection was guided by netuning requirements and accessibility. API-only models (Claude, GPT) could not be used for our layer-wise ne-tuning experiments. Others like DeepSeek or Qwen were either unavailable during our research timeframe or subject to institutional usage restrictions. Our primary focus remains on investigating generalizable ne-tuning techniques (classication head adaptation, layer-freezing) applicable to open-source models, rather than an exhaustive comparison of all LLMs.  </p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="3.2">Model Architecture</head><p>The model architecture is based on a standard Large Language Model (LLM) framework that incorporates essential components such as tokenization, embedding layers, and a multi-layer transformer stack. In this design, raw Solidity source code is rst tokenized into numerical representations and then processed through a series of transformer layers (each blue box in Figure <ref type="figure">2</ref>, comprising the full self-attention + feed-forward block with its residual connections and layer-norm). This enables the model to capture both local syntactic patterns and long-range dependencies in the code-capabilities that are critical for understanding the complexities inherent in smart contract analysis.</p><p>To tailor the generic LLM for smart contract vulnerability detection, the conventional generative output head is replaced with a dedicated classication head. Rather than predicting the next token from an extensive vocabulary, this modied output layer, which is implemented as a multi-layer perceptron (MLP), maps the nal (or penultimate) hidden representations directly to a predened set of vulnerability classes (e.g., reentrancy, access control, safe, vulnerable). Figure <ref type="figure">2</ref> illustrates the adapted architecture. This transformation eectively converts the LLM into a traditional classier pipeline, thereby reducing the risk of generating irrelevant tokens and ensuring that the outputs are conned to the task-specic label set.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="3.3">Datasets</head><p>For training our models and conducting the layer-freezing experiments (RQ2), we utilized the ScrawlD dataset developed by Yashavant et al. <ref type="bibr">[38]</ref>. ScrawlD is a substantial dataset comprising 9,252 labeled Solidity smart contracts. Vulnerability labels within ScrawlD were determined via a majority-voting consensus among ve analysis tools (Osiris, Oyente, Mythril, Slither, SmartCheck), identifying 5,364 contracts with at least one vulnerability according to this methodology.</p><p>From this dataset, which originally exhibited an imbalance with roughly two-thirds of contracts labeled as vulnerable, we rst partitioned the data into initial training (70%), validation (15%), and test (15%) sets. Recognizing that training on imbalanced data could bias model performance, we addressed this by applying an oversampling technique specically to the training set. We augmented the training data by replicating instances of the minority class (non-vulnerable contracts) until a balanced distribution between vulnerable and non-vulnerable samples was achieved before the proceeding with the ne-tuning process.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="3.4">Evaluation Strategy</head><p>Using our stratied data split, we systematically explored the impact of freezing varying numbers of lower transformer layers during ne-tuning for the RQ2 evaluation. For a given model with # total transformer layers we explored congurations across a spectrum dened by the number of frozen bottom layers (:):</p><p>(1) No Frozen Layers (: = 0): All # transformer layers and the classication head were ne-tuned (referred to as Full Fine-Tuning). This served as the performance baseline. (2) All Layers Frozen (: = # ): Only the classication head was ne-tuned, with all # transformer layers kept frozen (referred to as Head-Only Fine-Tuning). This isolated the head's contribution. (3) Intermediate Freezing (: = 2, 4, 6, ..., &lt; # ): The bottom : transformer layers were frozen, while the top # : transformer layers and the classication head were ne-tuned.</p><p>This allowed us to map the performance impact as the freeze boundary shifted upwards. Table <ref type="table">3</ref> summarizes the dierent layer-freezing congurations.</p><p>Consequently, all these layer-freezing congurations of each model were trained using the balanced training set and subsequently evaluated on the test set derived from ScrawlD.</p><p>To address RQ1, which assesses the eectiveness of incorporating a dedicated classication head, we compared our ne-tuned models against the state-of-the-art results published by Ince et al. <ref type="bibr">[17]</ref>. To facilitate a direct and equitable comparison, we evaluated our models using the specic test benchmark curated and released by Ince et al. This benchmark test set contains approximately 595 Solidity smart contracts for evaluation purposes. These contracts were labeled using the identical ve-tool majority-voting procedure applied to the ScrawlD dataset. To address RQ1, we evaluated our models using the 'Full Fine-Tuning' conguration described above (all # transformer layers and the classication head trained). Their performance on this benchmark was then compared against the results reported by Ince et al. <ref type="bibr">[17]</ref> for other models evaluated on the same test set.</p><p>Additionally, comparing the performance of these ne-tuned LLMs against non-LLM-based vulnerability detection methods falls outside the scope of this study, which concentrates specically on ecient LLM adaptation techniques. Such comparisons with traditional static/dynamic analysis or other machine learning approaches have been addressed in prior work <ref type="bibr">[36]</ref>.</p><p>Table <ref type="table">3</ref>: Overview of layer-freezing congurations. Each "transformer layer" refers to the blue box (attention + feedforward) detailed in Figure <ref type="figure">2</ref>.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>Conguration Trainable Components</head><p>Frozen Components For our experiments, we used the four models described in Section 3.1:</p><p>For both RQ1 and RQ2, the ne-tuning process followed the methodology outlined in Section 3.4. Specically, for RQ1, each model underwent full ne-tuning with a dedicated classication head. While for RQ2, the ne-tuning process involved applying different layer-freezing conditions, including full ne-tuning, training only the classication head, and various intermediate congurations. This allowed for the creation of trained models tailored to each specic condition.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="4.1.2">Resource</head><p>Used for Fine-Tuning. All experiments were conducted on a single NVIDIA A100 GPU (40 GB VRAM) from the Texas Advanced Computing Center's (TACC) Lonestar6 cluster. For all model ne-tuning, we utilized the LoRA (Low-Rank Adaptation) <ref type="bibr">[14]</ref> methodology as our principal approch to ne-tuning the models. For implementing the layer-wise ne-tuning strategy, we leveraged libraries like Ludwig, Hugging Face Transformers and LoRA. This enabled us to selectively freeze specic model layers while applying LoRA adapters to the remaining trainable layers. The complete code implementation, training scripts, datasets, and detailed experimental results are available in our reproducibility package. 1   4.1.3 Hyperparameter Space. The ne-tuning process was congured with carefully selected hyperparameters to optimize model performance while working within computational constraints. We employed a learning rate of 5e-4, which was empirically determined to provide stable training convergence while avoiding overshooting optimal parameter values. Given the memory constraints of processing lengthy smart contracts, we implemented a batch size of 2 with gradient accumulation steps of 16, eectively simulating 1 <ref type="url">https://bit.ly/paper_repo_adapT_LLM</ref> a larger batch size of 32 while maintaining manageable memory usage. The models were trained for 5 epochs, which proved sucient for convergence in our LoRA-based setup. For optimization, we utilized the Paged AdamW optimizer, a memory-ecient variant of Adam that is particularly well-suited for training large language models. This choice was motivated by the need to manage memory usage eectively while maintaining stable training dynamics. Due to computational resource limitations associated with netuning multiple large models across numerous congurations, each experimental condition reported in this study was trained and evaluated once. While this provides valuable performance indicators, we acknowledge that single runs preclude analysis of statistical signicance or run-to-run variability.</p><p>These hyperparameter choices were guided by both empirical testing and practical constraints, aiming to maximize model performance within the available computational resources while ensuring reliable vulnerability detection capabilities. Importantly, we applied the same hyperparameter conguration across all model and layerfreezing conditions to ensure that any observed performance differences stem solely from the layer-freezing strategy rather than model-specic tuning.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="4.2">Results and Discussion</head><p>RQ1: Eectiveness of Classication Head Approach. To address our rst research question on the eectiveness of ne-tuning LLMs with a dedicated classier head for smart contract vulnerability detection, we conducted a comprehensive evaluation comparing our approach with state-of-the-art models. Table <ref type="table">4</ref> presents the performance metrics across various models for binary classication. This evaluation focuses on binary classication across key metrics: precision, recall, 1 score, and accuracy.</p><p>Our ne-tuned models demonstrated substantial improvements over the baseline approaches reported in Ince et al. <ref type="bibr">[17]</ref>. Among our models, Llama 3.2 3B-AdapT achieved the highest performance with 77.5% accuracy, 76.5% precision, 77.8% recall, and an F1 score of 0.771. This places it on par with the top-performing GPT-3.5FT model (77.6% accuracy), despite the latter likely having signicantly more parameters. The comparable performance indicates that our classication head approach eectively adapts LLM for this specialized domain task.</p><p>A clear trend emerges when examining performance across model sizes within the same architecture family. The 3B parameter variants consistently outperformed their 1B counterparts across all metrics. For instance, Llama 3.2 3B-AdapT achieved 3.5 percentage points higher accuracy than Llama 3.2 1B-AdapT (77.5% versus 74.0%), while StarCoder 3B-AdapT similarly outperformed StarCoder 1B-AdapT by 6.3 percentage points (68.8% versus 62.5%). This pattern suggests that increased model capacity contributed to better discrimination of vulnerability patterns, though the performance gains appeared to scale sub-linearly with parameter count.</p><p>Architecture dierences also played a signicant role in performance. The Llama 3.2 models consistently outperformed their Star-Coder counterparts of equivalent size. This performance gap (approximately 8.7 percentage points for 3B models and 11.5 percentage points for 1B models) indicated that architectural design choices and pre-training strategies substantially inuenced a model's adaptability to security-focused code analysis tasks, potentially more so than raw parameter count alone. When comparing our models to other approaches in the eld, we observed distinct trade-o patterns. Models like GPTLens and DL-Foundation exhibited extremely high recall (98.8% and 99.3% respectively) but suered from low precision (53.3% and 51.7%), resulting in lower overall accuracy. This suggested these models were optimized for maximizing vulnerability coverage at the expense of generating numerous false positives.</p><p>In contrast, our ne-tuned models and GPT-3.5FT achieved more balanced precision and recall scores, indicating better overall discrimination capability. The distribution of performance metrics across all evaluated models revealed an important insight: achieving high precision in smart contract vulnerability detection remained challenging. Even the best-performing models achieved precision in the mid-to-high 70% range, suggesting inherent diculty in denitively identifying code as vulnerable without false positives. This challenge likely stemmed from the subtle nature of many vulnerabilities, where small variations in context or implementation could determine whether a pattern represented a genuine security risk. Our Llama 3.2 3B-AdapT model notably outperformed GPT-4 in this specic task, with accuracy of 77.5% versus 66.1%. This outcome was particularly noteworthy given GPT-4's substantially larger size and broader capabilities, highlighting that task-specic ne-tuning with an appropriate architecture could exceed the performance of more general, larger models on specialized tasks like vulnerability detection.</p><p>These results collectively demonstrated that ne-tuning moderatesized LLMs with dedicated classication heads oered an eective approach for smart contract vulnerability detection. The classication head architecture appeared to successfully leverage the rich contextual representations of transformer-based models while constraining outputs to a well-dened set of vulnerability classes, avoiding potential ambiguities in token-generation approaches. Furthermore, the performance achieved by our Llama 3.2 3B-AdapT model indicated that this approach could yield state-of-the-art results while remaining computationally more ecient than employing the largest available models.</p><p>RQ2: Impact of Layer-Specic Fine-tuning. To investigate how selective layer freezing aected model performance and computational eciency, we conducted experiments across four models (Llama 3.2 1B, Llama 3.2 3B, StarCoder 1B, and StarCoder 3B), systematically freezing increasing numbers of bottom layers while measuring performance and resource usage.</p><p>Our analysis revealed a compelling pattern of diminishing returns as lower layers were frozen. Both accuracy and F1 scores remained quite stable even when a signicant portion of bottom layers were prevented from updating during ne-tuning. For instance, freezing half of the layers in most models resulted in performance drops of less than 1.7 percentage points compared to full ne-tuning. This consistent pattern across all tested architectures, as seen in Figures <ref type="figure">3</ref> and <ref type="figure">4</ref>, suggests that substantial task-specic adaptation occurs in the upper layers. With such selective layer freezing strategies, training time decreased by approximately 10-20% and memory usage also decreased by about 10-20%, as illustrated in Figure <ref type="figure">5</ref>. For resource-constrained environments, these ndings demonstrated a viable path to deploying eective LLMs that would otherwise be computationally prohibitive.</p><p>Model size also inuenced freeze-resilience. The larger Llama 3.2 3 B retained 75% accuracy with just the top six layers trainable (&#8673; 20% of the network), whereas the 1 B variant slipped below that mark once more than &#8672;80% of its layers were frozen. This indicates that the extra capacity in the 3 B model provides enough representational redundancy to tolerate more aggressive parametereciency strategies.</p><p>These results has important implications for practical applications of LLM ne-tuning. By selectively ne-tuning only the top layers, practitioners could achieve near-optimal performance while reducing computational requirements. In the context of smart contract vulnerability detection, our ndings suggested that the general code understanding capabilities encoded during pre-training remained largely applicable without modication, while task-specic adaptation for security vulnerabilities could be eectively captured through updates to the upper layers alone. This supported the principle that recognizing vulnerability patterns relied more on high-level semantic understanding than low-level syntactic processing.</p><p>In summary, our experimental results demonstrated that restricting ne-tuning to specic high-level Transformer layers while freezing lower layers achieved competitive performance with signicantly reduced computational requirements, making LLM-based vulnerability detection more practical for real-world applications.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="5">Related Work</head><p>Research in smart contract vulnerability detection encompassed diverse methodological approaches that collectively aimed to address the critical challenge of securing blockchain-based programs. The landscape of vulnerability detection techniques spanned from traditional software engineering methods, such as static and dynamic analysis, to machine learning-based approaches that leveraged pattern recognition and automated analysis. In the domain of machine learning-based approaches, applications of LLMs had also been actively pursued in recent times. This section systematically reviewed recent advancements in using LLMs specically for enhancing smart contract vulnerability detection.</p><p>Several studies presented robust LLM-based frameworks that enhanced vulnerability detection over traditional security tools. LLM-SmartAudit, for instance, introduced a multi-agent LLM framework that captured complex contract interactions, allowing the identication of previously undetected logic vulnerabilities through a collaborative LLM agent system <ref type="bibr">[35]</ref>. Similarly, FELLMVP employed an ensemble of ne-tuned LLMs to classify multiple vulnerability types, achieving higher accuracy and eciency than both static and dynamic analysis methods <ref type="bibr">[21]</ref>. Additionally, LLMSmartSec integrated LLMs with annotated control ow graphs to improve vulnerability detection and remediation, showcasing the potential of hybrid approaches in smart contract security <ref type="bibr">[23]</ref>. Although these approaches oered eective strategies, they still relied on autoregressive generation, inheriting the limitations of LLM.</p><p>Despite their advancements, LLM-based methods faced certain challenges. False positives remained a persistent issue; GPTLENS employed adversarial techniques that segmented generation and validation stages to mitigate incorrect detections, underscoring the need for rening detection accuracy in LLM systems <ref type="bibr">[16]</ref>. Targeted LLM applications also showed promise in detecting specic logicrelated vulnerabilities within smart contracts. Soley and GPTScan, for instance, leveraged ne-tuned LLMs to identify intricate logic vulnerabilities that static analysis tools often overlooked, such as misaligned state changes and errors in business logic <ref type="bibr">[28]</ref>. By focusing on Solidity code intricacies, these models demonstrated the potential of LLMs in detecting nuanced vulnerabilities specic to contract logic.</p><p>Additionally, Context-Driven Prompting enhanced detection precision by structuring prompts to emphasize relevant portions of the code, thereby optimizing the LLM's focus during analysis <ref type="bibr">[4,</ref><ref type="bibr">30]</ref>. RAG-Enhanced LLMs incorporated Retrieval-Augmented Generation (RAG), which retrieved relevant contextual information during detection, thereby improving precision by extending the LLM's ability to generalize and adapt to complex vulnerability patterns <ref type="bibr">[40]</ref>. These studies indicated that improved prompting could signicantly boost LLM-based detection in both accuracy and eciency.</p><p>Finally, the application of LLMs to multiple blockchain platforms remained an area with unrealized potential. LLM-based vulnerability detection methods are signicantly advancing smart contract security, addressing challenges through novel frameworks, prompting strategies, and hybrid techniques as reviewed above. However, to the best of our knowledge, the specic adaptation strategies investigated in this paper-evaluating the eectiveness of a dedicated classication head compared to standard token generation (RQ1) and systematically analyzing the performance and eciency tradeos of layer-wise ne-tuning by freezing lower layers (RQ2)-have not been the primary focus of prior work in this domain. Consequently, challenges such as false positives, computational costs, and cross-platform adaptability persist. Continued research in optimizing LLM frameworks, including ecient adaptation techniques like those studied here, expanding platform applicability, and improving resource eciency will be vital to fully realizing the potential of LLMs in the evolving landscape of blockchain security.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="6">Conclusion</head><p>In this study, we investigated two core questions: rst, whether a specialized classication head could enhance the eectiveness of Large Language Models (LLMs) in identifying smart contract vulnerabilities; and second, how varying the number of frozen lower layers during ne-tuning impacts resource consumption and performance. Our experiments demonstrated that ne-tuning with dedicated classication heads yielded competitive results. Notably, our Llama 3.2 3B-AdapT model reached 77.5% accuracy, performing comparably to the ne-tuned GPT-3.5FT model despite potential dierences in underlying architecture and size. This highlights the eectiveness of the classication head approach for this task. Furthermore, our investigation into layer freezing revealed that performance remained stable even when a substantial number of lower transformer layers were frozen, resulting in minimal degradation while oering notable eciency gains. We observed reductions in both training time and memory usage of approximately 10-20% when ne-tuning only the upper layers, making LLM adaptation more feasible under resource constraints. Larger models exhibited greater resilience; for example, Llama 3.2 3B-AdapT maintained high accuracy even when a large proportion of the lower layers were frozen (leaving only upper layers trainable), suggesting that general code understanding resides largely in lower layers while vulnerability detection patterns are primarily learned in upper layers.</p><p>Building on these ndings, our future research will pursue several promising directions. First, extending our classication approach to multi-class vulnerability detection would enhance practical utility by providing specic vulnerability classications rather than binary judgments. Second, exploring the application of this ne-tuning scheme to other blockchain platforms beyond Ethereum would test the generalizability of our approach across diverse programming languages and execution models. Finally, implementing adaptive layer-freezing schedules-where the number of trainable layers was dynamically adjusted based on validation metrics-might further optimize computational eciency. These directions collectively promise to advance the accessibility and eectiveness of LLM-based vulnerability detection systems for blockchain security applications, potentially making sophisticated security analysis tools available even in resource constrained environments.</p></div></body>
		</text>
</TEI>
