Evaluating parameter-efficient fine-tuning of large language models for sentiment analysis with bayesian optimization

Evaluating parameter-efficient fine-tuning of large language models for sentiment analysis with bayesian optimization

Arabic sentiment analysis

Recently, Arabic sentiment analysis has gained significant attention from the research community due to the rapid increase of Arabic content across different platforms and the inherent linguistic complexity of the language. These created an urgent need for developing models that automatically understand these opinions and analyze them to gain insight. Consequently, several approaches have been developed by researchers to capture the sentiment, such as lexicon-based models16,17 and machine learning models18,19, while more recent research focuses on the advancement of deep learning models. Motivated by the success of deep learning algorithms20, proposed a DL model based on a combination of one CNN layer and two LSTM layers. The learned feature map is fed to the SVM classifier. They constructed a multi-domain training set of 15,100k and a test set of 4000 reviews from previously published corpora. This combination yields significant performance compared to several previous studies. Another study21 discusses the benefits of combining CNNs with LSTMs for enhancing ASA across various datasets. The study uses three levels of sentiment analysis, including word level, character N-gram level, and character level. However, this research does not integrate of pre-trained word embedding, which may lead to limited semantic representation. Furthermore, authors in22 develop ArSentCropus through a semi-supervised approach. They employed LSTM and FastText to train and test the final corpus. The authors evaluated their proposed framework on the SemEval and ASTD benchmarks using both balanced and unbalanced versions. For binary classification, the model achieved 87.4% and 85.2% F1-Score of SemEval 2017 and ASTD datasets, respectively. For multi-class classification, it achieved 69.4% and 68.1% on the same datasets. To predict the sentiment of dialectal Arabic text, a combination of Bi-LSTM and CNN deep learning model was proposed on23. Evaluating their model on ASTD, LABR, and Shami-Senti datasets. The dataset split ratios are different across datasets, as the LABR is divided into 70%,10%,20%, whereas other benchmark datasets were split into 80%,10%,10%. The model achieved 81.14% and 85.58% for LABR and ASTD with binary classification, respectively, outperforming baseline models. A study by24 employs three DL algorithms, CNN, LSTM, and CNN-LSTM, with different setups of HARD and LABR datasets. Their final result using CNN with fastText achieves a strong performance, surpassing both LSTM and CNN-LSTM. However, the result obtained for a HARD dataset with a binary balanced distribution, achieving an accuracy of 90.42%, remains below the benchmark performance. Furthermore, the author does not investigate the balanced version of the LABR dataset. The study25 proposed a selective reading approach for Arabic sentiment analysis. They used a policy network to select words that have a high impact on the sentiment polarity of a given text throughout the GRU. After that, the chosen tokens are fed into a classification module consisting of GRU and three CNN layers. The experiment is evaluated on three Arabic datasets: HARD, LABR, and ASTD. The final result shows that the proposed method outperforms previous work while only retaining 75% of tokens from the training sets.

Sentiment analysis with LLMs using PEFT

The introduction of the transformer-based model shows a significant increment in performance of many NLP tasks through its ability to capture fine-grained linguistic characteristics and complex contexts. This subsection covers recent sentiment analysis studies based on transformer architectures, highlighting those that incorporate PEFT methods, especially LoRA.

The researcher in26 assesses the efficiency of the multilingual XLM-RoBERTa model employing the LoRA technique for binary sentiment analysis and investigates the trade-off between performance and resource utilization. The study leveraged the IMDb data set for reviews in the English language and the SentiComments.SR corpus for Serbian language with 3490 total instances for each dataset. The result shows that for the English language, the accuracy is 3% lower than the full fine-tuning. For the Serbian dataset, the full fine-tuning achieved 85% accuracy in five epochs. When implementing LoRA with only 0.42% trainable parameters, the accuracy reaches 84% with ten epochs and showing a significant drop in both training time and memory allocation. Another study27 discusses the influence of LoRA tuning across different sizes of Bert-based transformer models for Indonesian emotion classification. Furthermore, the paper implements HPO using the Optuna framework and employs a grid-search approach with 10 trials for each model. Five hyperparameters were included: the number of training epochs, learning rate, train batch size, eval batch size, and Weight decay. The values of Lora rank, LoRA alpha, and LoRA dropout were fixed at 8, 32, and 0.1. The final result shows that XML-RoBERTa attains the highest performance with a macro-F1 of 80.12%, outperforming all models under both full fine-tuning and PEFT configurations. Credit risk assessment has been discussed in28 by leveraging Bert, Roberta, Llama 3.2, and ML models. The financial news dataset was collected through the NewsCatcher API with a significant class imbalance toward the positive class. The final result demonstrates a similar performance of Bert and Roberta, achieving an accuracy of 91% and 90%, respectively. LLaMA-3.2 attained a lower accuracy of 78%, highlighting its difficulties with sentiment classification, especially for neutral and negative classes, as all instances were misclassified as positive. However, XGBoost achieved an accuracy of 94% and logistic regression obtained 92%, outperforming the transformer-based models. The importance of SA in the decision-making process is emphasized in this study29. To improve the Llama2-7b-hf model’s performance, two approaches were implemented. Initially, a baseline evaluation was conducted, which resulted in an overall accuracy of 37.3% with difficulties in identifying negative and positive sentiments and a bias toward the neutral class. After applying quantization and an adaptive threshold, the accuracy increased to 84.4%. Furthermore, incorporating LoRA fine-tuning enhanced the model’s accuracy, reaching 89% demonstrating its effectiveness among all classes. Furthermore, this study30 explores the use of LlaMA-3.2-1B-IT and Gemma-2-2BIT for Turkish SA using LoRA. They employed four Turkish SA datasets that were relabeled using GPT-4o-mini to overcome the issue related to labeling using star ratings. The research evaluates both zero-shot and LoRA-tuned models. Fine-tuning with GPT-generated labels significantly improved performance, with F1 scores reaching 91.2% for in-domain and 91.84% for out-of-domain, outperforming commercial models by 6%. Authors in31 employ five LLM models known for their proficiency in handling the Chinese language to investigate their ability in SA for classical poetry from the Song Dynasty. The fine-tuning involves LoRA and QLoRA. The results indicate that the ChatGLM model, utilizing 4-bit and 8-bit quantization achieved the highest F1-scores. In contrast, Chinese-LaMA2 struggled to handle classical Chinese poetry. Additionally, the Qwen 1.5-7B model demonstrates efficiency with lower bit depth, highlighting the efficiency of the quantization method. Relatedly, this research32 evaluates the capability of three LLMs for Chinese financial sentiment analysis. The authors combine three financial sentiment datasets, resulting in 16,646 samples. The instruction-tuned Qwen-Fin7B utilizing LoRA with a rank of 8, an alpha of 16, and a learning rate of 5e-5, outperforms Qwen1.57B, ChatGLM36B, and Qwen1.57B. The researcher in33 addresses the challenges of fine-tuning with limited data availability. To mitigate this, they propose a framework that combines the generation of synthetic data using ICL, filtering, and LoRA-based fine-tuning utilizing Vicuna in both 7b and 13b parameters for classification and question answering tasks. The results obtained using the Vicuna-13 b model demonstrate the effectiveness of the proposed method34. highlight the benefit of using LoRA and QLoRA in terms of efficiency, memory usage, and performance for the sentiment analysis task using the llama-3 model with classification head adaptation on the Yelp dataset. Their methodology focused on investigating optimal hyperparameter values for LoRA and QLoRA through testing different rank and scaling factor values. Furthermore, the paper evaluates the impact of adapting all linear layers during training versus only the attention layer. Text classification is studied on35 through a detailed examination of how LLMs respond to different fine-tuning strategies. Seven LLM models, namely (i)BERT, (ii)RoBERTa, (iii)OPT, (iv)Falcon, (v)LLaMA2, (vi)Mistral, and (vii) Zephyr, were fine-tuned using various PEFT techniques. For the sentiment analysis task, the authors used the Twitter financial news and IMDB datasets. The finding shows that discriminative models outperform generative LLMs by 3% performance increment, which suggests that pre-training objective and model architecture may have a stronger influence on performance than model scale. Adapting LoRA to the fine-tune process yields improvements in F1 score from 82% to 88.58% for IMDB, whereas the Financial Sentiment dataset has dropped from 87.07% to 81.72%. Lastly, the authors investigate the effect of different LoRA dropout rates ranging from 0.0 to 1.0, which shows a negative impact on performance as the dropout increases. This study36 evaluates the transformer-based architecture for aspect extraction in Portuguese sentiment analysis using literary and TV datasets. The author developed two domain-specific BERTtv and BERTTreli. Furthermore, conduct a fine-tuning of BertTimbau as a general domain model using LoRA. Additionally, the study evaluated Cabrita, a tuned version of OpenLLaMA adapted for Portuguese using QlorA. The proposed Bert model with LoRA optimization significantly surpasses other models’ F1-score. However, the finding shows that while LLMs perform better than general-domain BERT, they still lag behind baseline and specific-domain BERT models.

In the context of the Arabic language, a recent study37 evaluates the ability of GPT-3.5 Turbo and GPT-4 on the Arabic emotion classification task using three settings: in-context learning, emotional stimulus prompt, and fine-tuning. The result demonstrated that fine-tuned GPT 3.5 achieved the best result across all settings and outperformed the SOTA model. Another study38 investigated the effectiveness of LLMs in Arabic aspect-based sentiment analysis. The authors compare a different prompt approach and fine-tuning to assess the ability of GPT3.5 and GPT4 on the downstream task. Two datasets were used for evaluation: the Human-annotated Arabic dataset of Book reviews (HAAD) and the Arabic news dataset. The result suggested that fine-tuned GPT was able to handle Arabic aspect-based sentiment analysis tasks more efficiently than BERT-based models for the HAAD dataset with a 17% improvement in F1-score. Study39 proposed an Arabic sentiment analysis multimodel framework using UniTextFusion on the Ar-Musa dataset. The study fine-tuned LLaMA-3.1-8B-Instruct and SILMA-9B-Instruct using three input types: text only, text combined with audio, and text combined with both audio and images. Each kind of input was converted into a textual representation. The fine-tuning leveraged LoRA with an alpha of 16, rank of 64, and dropout set to 0. For the textonly setting, the performance of base and fine-tuned models is raised from 41 to 65% weighted F1-score for LLaMA-3.1-8B-Instruct and from 52 to 67% for SILMA-9B-Instruct. The influence of prompt alignment with the input dialect for Arabic sentiment analysis was investigated in40. The study compares the effectiveness of DeepSeek, Qwen2.5, and LLaMA-3, which were fine-tuned using LoRA among Modern Standard Arabic (MSA), the Saudi dialect, and Darija. Qwen2.5 models achieve the highest performance, outperforming other models when using MSA prompt type across all dialects. This result indicating their robustness to mismatches. Alternatively, DeepSeek shows high sensitivity to prompt-input mismatch. Llama-3 exhibited stable performance in all configurations and was more resistant to English prompts, highlighting its cross-lingual flexibility.

Methodology

Figure 1 represents the overall methodology of our research, which follows a structured approach to explore the potential of LLMs fine-tuning for the Arabic sentiment analysis task. The first stages include dataset selection and building a preprocessing pipeline. After that, LLMs are selected, including both multilingual and Arabic-based models. As illustrated, two distinct experiments were adopted. The first approach involves training an LLM for a sequence classification task, where the base model is chosen for fine-tuning and testing to evaluate their performance. The second approach focuses on a fine-tuned instruction-tuned version of LLM that requires input to be accompanied with a prompt to ensure the model follows instructions and generates a response according to the given prompt. For both approaches, we conduct Bayesian HPO to find the optimal values of hyperparameters for fine-tuning using the LoRA technique. In this section, we outline the details of each step involved in the proposed methodology.

Fig. 1Fig. 1

Overview of the proposed methodology for Arabic sentiment analysis using Fine-Tuned large language models.

Dataset details

This study utilizes the publicly available ASTD (https://github.com/mahmoudnabil/ASTD), LABR (https://github.com/mohamedadaly/LABR) , and HARD (https://github.com/elnagara/HARD-Arabic-Dataset) datasets. This selection provides a wide range of dataset sizes, domains, and review lengths for LoRA fine-tuning of LLMs.Table 1 presents a detailed statistical overview of the selected datasets. We used the original version of each dataset published on GitHub. A 70/10/20 split was adopted for training, validation, and testing, respectively, for both LABR and HARD. For ASTD we maintained the original dataset split provided by the authors, consisting of 481 samples for training and 159 samples for each of validation and testing. The distribution of the datasets is presented in Table 2.

1.

Arabic sentiment tweets (ASTD)41: Arabic Sentiment Tweets Dataset contains 10k tweets written in modern standard Arabic and Egyptian dialect. The data set was manually annotated into four categories: objective, subjective negative, subjective positive, and subjective mixed. Furthermore, the authors provided a balanced and unbalanced version of the data, each with a binary and multi-classification configuration. For our paper, we perform a two-way sentiment classification. We include positive and negative tweets of a balanced version with a total of 1598 data points.

2.

Large Arabic book reviews (LABR)42: A popular benchmark for book reviews is the LABR dataset. Authors gathered more than 63,000 Arabic book reviews from the Goodreads website in March 2013. Each review was given a five-point rating (1–5). The numbers of negative, positive, and neutral reviews were 8224, 42,832, and 12,201, respectively. For this study, we used the balanced version of the dataset which containing 13k book reviews.

3.

Hotel Arabic reviews dataset (HARD)43: This dataset comprises hotel reviews that were manually annotated and collected from 1,858 hotels on a booking website. Initially, the authors collected 981,143 reviews and ranked them from 1 to 5 in both dialectal Arabic and modern standard Arabic. After data cleaning, the dataset was reduced to 373,773 reviews. It was available in both balanced and unbalanced configurations for both binary and multi-class classification. For this study, we used the balanced version with 105k reviews that were equally distributed between negative and positive categories.

Table 1 Statistical information of the ASTD, LABR, and HARD datasets.Table 2 Distribution of sentiment analysis data across training, validation, and testing sets.

Although the original datasets have multi-class annotations, we reformulate the task as binary sentiment classification to reduce class imbalance and ensure comparability with prior Arabic sentiment analysis studies. Considering that our work’s primary goal is to evaluate LoRA-based parameter-efficient fine-tuning strategies, a binary setting offers a controlled system to isolate the effect of different adaptation methods. Future work will extend the evaluation to a multi-class setting.

Data set pre-processing

The selected data sets underwent a pre-processing pipeline including data cleaning, normalization, and tokenization. These steps were developed to ensure data quality before the training38. The data cleaning was performed to eliminate non-essential elements and shift the focus to the content itself. URLs, user mentions, spaces, digits, and the hashtag symbol”#” were eliminated, while the hashtag text was kept to preserve the semantic meaning. Additionally, white spaces and invisible Unicode characters were removed. Normalization was applied to standardize the forms of Arabic characters and to maintain consistency across text data8. This involves normalization of Arabic letter variants, removing elongation and diacritics, and handling character repetition. Lastly, Tokenization was performed to convert the raw Arabic text into token sequences. We used the tokenizer associated with each model checkpoint in our experiments with right-side padding and truncation enabled. The maximum sequence length was set based on the text length of each dataset, with values of 128 tokens for ASTD, 512 tokens for LABR, and 256 tokens for HARD.

Prompt design

In this study, two instruction-tuned large language models are evaluated using carefully designed prompts that align with the primary language and instruction format for the model44. The prompt design aims to ensure fairness and consistency across models while aligning with their linguistic and architectural differences40. To ensure consistency among experiments we develop two primary prompt templates in both English and Arabic. The instruction structure remained identical across all experiments, with the only difference in the domain of the dataset being used, either as a tweet, book review, or hotel review. The LLaMA-3-Instruct model is prompted in English using a structured chat-style format with system, user, and assistant roles in a tags format. The system message specifies the sentiment classification task and instructing the model to respond with exactly one label, either “positive” or “negative”. The review or tweet text is then provided as input for classification. For the SILMA-9B-Instruct model, prompts are formulated in Arabic, aligned with model’s intended language setting. Similarly, we define the model as an expert sentiment classifier and restrict the output to a single sentiment label. This constrained prompt structure is designed to minimize generation variability and ensure that the model generates accurate and label-consistent responses. Table 3 illustrates the general structure of the prompt for all the datasets in both Arabic and English.

Table 3 Template of prompts used for english and arabic languages.Models and task

To conduct the experiments, we used LLaMA 3 and SILMA AI models. These models are built upon a Transformer architecture that employs a multi-head attention mechanism, which allows them to capture contextual relationships within sentences and generate coherent and accurate text12. LLaMA 3 is the third generation of the LLama family developed by MetaAI, with a number of parameters ranging from 8 to 70 billion, and has been pre-trained on 15 trillion tokens collected from publicly available online sources. The multilingual capability of the model with a vocabulary size of 128k allows for both understanding and generating text across various linguistic contexts. This leads to effective generalization performance and robustness to prompt variations45. They introduce extended context windows and grouped-query attention mechanisms, which enhance their overall performance. For this study, we used both base and instruction-tuned models with an 8 billion parameter size.

The sequence classification and instruction-tuned approach has a different paradigm for conducting the training process. In traditional supervised learning, the model is trained on a large amount of labeled data. For the pretrained language models, this is achieved by adding a linear layer for classification to the end of the model architecture, known as a classification head. This adapts the model to a specific task by utilizing the semantic representations generated by the model through training of the newly added classification head, while the underlying model weight is kept frozen46. In instruction fine-tuning, the model is a learner to follow a given instruction. The data set structure for instruction fine-tuning consists of pairs of manually created instructions by a human and the desired output. This approach aligns the next word prediction objective of large language models with users’ expectations of having LLMs that adhere to human instructions47. SILMA-9B-Instruct is an Arabic instruction language model built on the Gemma architecture from Google. This model has a wide range of applications, such as content research and education across various domains.Also, it supports both natural language generation and NLP tasks.

Experimental settings of fine tuning using LoRA

This section outlines the LoRA fine-tuning experimental framework, which was applied across all Bayesian hyperparameter optimization trials. The experiments are conducted using RunPods, utilizing an A100 GPU with Python version 3.11 and PyTorch version 2.4.0. All model checkpoints were loaded from the HuggingFace transformers library with the device map parameter set to ‘auto’. As illustrated in the methodology introduction, we conduct fine-tuning based on both the sequence classification task and the generation task. For sequence classification, LLaMA-3-8B was initialized using AutoModelForSequenceClassification with two output classes in the classification head. AutoModelForCausalLM was used to load LLaMA-3-8B-Instruct and SILMA-9B-Instruct-v1.0 as instruction-tuned models8. For the instruction-tuned models, the training loss was computed on the generated model response. Additionally, we use the TrainingArgs and the Trainer Library to run all experiments. Table 4 presents the training hyperparameters used for each dataset during the experiments. For all experiments, LoRA was applied to all linear projection layer including “q_proj”, “v_proj”, “k_proj”, “o_proj”, “gate_proj”, “up_proj”, “down_proj”. All models are trained for three epochs for ASTD and LABR datasets and one epoch for HARD dataset. Epoch counts were fixed on the basis of preliminary experiments, in which additional epochs beyond three for ASTD and LABR and beyond one for HARD produced no improvement in validation F1-score; epochs were therefore excluded from the search space to concentrate the optimization budget on the LoRA hyperparameters.

Table 4 Training hyperparameters for each dataset.Hyperparameters tuning

The training process for DL and ML is driven by a set of parameters called hyperparameters. Choosing the appropriate set of these hyperparameters is essential to leverage the potential of a developed model and enable adaptation to a given dataset. Manual tuning of these hyperparameters is considered a time-consuming process. Automated techniques were introduced to overcome the limitation of manual tuning, such as grid search and random search. Grid search involves evaluating the objective function at each point in a pre-defined grid. This approach can be time-consuming in cases where the objective function is costly to calculate. Random search is another method that evaluates the objective function at a random subset of points. This method can also be time-consuming and may not produce correct results if the objective function is noisy48. Bayesian HPO is an advanced method for tuning hyperparameters that incrementally constructs and updates a probabilistic model based on prior evaluation results. This approach saves time and resources as it reduces the need to evaluate regions that are unlikely to be optimal49.

For our experiment, we chose to test the effect of different values of the LoRA hyperparameters, including rank, dropout, and learning rate on the overall performance of LLMs for sentiment analysis tasks. The LoRA scaling parameter was not included in the optimization process and was kept fixed at 2 × r throughout all experiments. Bayesian HPO was performed using the Weights & Biases (W&B) platform. Firstly, we define the search space as illustrated in Table 5 and define the objective function to maximize the F1-score of the validation set. Due to computational constraints, we set the total number of optimization iterations to 20 trials. At each trial, the selected hyperparameter from the predefined search space is evaluated using LoRA fine-tuning. This loop will continue until we reach the stopping condition, which is in our case, the completion of all 20 trials. Finally, the configuration that achieved the highest validation F1-score is selected. The Optimization process is illustrated in Fig. 2.

Table 5 Hyperparameter search spaces for LoRA rank, LoRA dropout and learning rate.Fig. 2Fig. 2

Hyperparameter tuning using Bayesian optimization. The optimization loop is executed independently for each model, and the trial that achieved the highest validation F-1 score is selected as the optimal trial to be tested on the test set.

Model evaluation

We report the performance of different metrics listed in Eqs. (3–6). The weighted F1-score was chosen as the primary metric, and we use it for hyperparameter sweep optimization, best model selection, and final testing. The following equations present the definitions of the evaluation metrics used in this study. Accuracy comparing the percentage of accurately labeled data points out of all instances. Precision measures the proportion of true positive predictions over all positive Prediction. Recall measures the proportion of true positives to the sum of true positives and false negatives. F1-score is harmonic mean of Precision and Recall.

$$\text{A}\text{c}\text{c}\text{u}\text{r}\text{a}\text{c}\text{y} =\frac{\text{T}\text{P} + \text{T}\text{N}}{\text{T}\text{P} + \text{T}\text{N} + \text{F}\text{P} + \text{F}\text{N}}$$

(3)

$$\text{P}\text{r}\text{e}\text{c}\text{i}\text{s}\text{i}\text{o}\text{n}=\frac{\text{T}\text{P} }{\text{T}\text{P} + \text{F}\text{P}} $$

(4)

$$\text{R}\text{e}\text{c}\text{a}\text{l}\text{l}=\frac{\text{T}\text{P} }{\text{T}\text{P} + \text{F}\text{N}} $$

(5)

$$\text{F}1-\text{s}\text{c}\text{o}\text{r}\text{e}=2 \times \frac{\text{P}\text{r}\text{e}\text{c}\text{i}\text{s}\text{i}\text{o}\text{n} \times \text{R}\text{e}\text{c}\text{a}\text{l}\text{l} }{\text{P}\text{r}\text{e}\text{c}\text{i}\text{s}\text{i}\text{o}\text{n}+ \text{R}\text{e}\text{c}\text{a}\text{l}\text{l} } $$

(6)