<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yogesh Mane on Medium]]></title>
        <description><![CDATA[Stories by Yogesh Mane on Medium]]></description>
        <link>https://medium.com/@y.mane?source=rss-ce554a9e76de------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*96LlWpa41jilm8Px</url>
            <title>Stories by Yogesh Mane on Medium</title>
            <link>https://medium.com/@y.mane?source=rss-ce554a9e76de------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:44:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@y.mane/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Fine-Tuning Large Language Models with QLoRA]]></title>
            <link>https://medium.com/globant/fine-tuning-large-language-models-with-qlora-adacfb23747e?source=rss-ce554a9e76de------2</link>
            <guid isPermaLink="false">https://medium.com/p/adacfb23747e</guid>
            <category><![CDATA[wandb]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[llm-finetuning]]></category>
            <category><![CDATA[qlora]]></category>
            <dc:creator><![CDATA[Yogesh Mane]]></dc:creator>
            <pubDate>Wed, 11 Dec 2024 12:15:11 GMT</pubDate>
            <atom:updated>2024-12-11T12:15:11.230Z</atom:updated>
            <content:encoded><![CDATA[<h4>Harnessing the Power of W&amp;B for Enhanced Visualization and Insights</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/0*cNv4sO2gz-sO5Qiv.jpg" /><figcaption><a href="https://images.app.goo.gl/giFuC6DfxK9gB3hM9">https://images.app.goo.gl/giFuC6DfxK9gB3hM9</a></figcaption></figure><p>Fine-tuning language models involves adapting pre-trained models to specific tasks or domains by training them further on task-specific datasets. This technique leverages the extensive knowledge acquired during the pre-training phase, enabling the model to perform specialized tasks more effectively. In this guide, we explore the process of fine-tuning language models using QLoRA — a method that combines Low-Rank Adaptation (LoRA) with quantization for efficient training. We also delve into the benefits of using Weight and Biases (Wandb) (W&amp;B) for tracking and visualizing the fine-tuning process. By understanding these concepts, you’ll gain the ability to fine-tune large models efficiently, monitor their performance, and make informed decisions to optimize their outputs.</p><h3><strong>Why Visualise Model Progress?</strong></h3><p>During the fine-tuning process, it is crucial to monitor the model’s progress to gain insights into its behavior and performance. By visualizing the model’s results and the interim results, we can do the following things.</p><ul><li>Track Loss and Metrics: Monitor the loss and other metrics to assess the model’s convergence and performance.</li><li>Analyse Hyperparameters: Observe the impact of hyperparameters on the model’s performance and make informed decisions in hyperparameter tuning.</li><li>Debug and Diagnose: Identify potential issues or anomalies in the model’s output and diagnose the root causes.</li><li>Interpret and Explain: Gain a better understanding of the model’s decision-making process and interpret its predictions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OBF42ip1dUQOEoITu8-jKA.png" /><figcaption>This is image related to power ,system usage by llm model while fine tuning</figcaption></figure><h3><strong>Benefits of Using W&amp;B</strong></h3><p>Using W&amp;B provides several benefits for fine-tuning language models:</p><ul><li><strong>Experiment Tracking</strong>: W&amp;B allows tracking of all experiments, making it easy to compare different runs and configurations.</li><li><strong>Visualization: </strong>Real-time visualization of metrics and loss helps in understanding the training process and diagnosing issues.</li><li><strong>Hyperparameter Optimization</strong>: W&amp;B facilitates hyperparameter tuning by providing tools to search and compare different hyperparameter settings.</li><li><strong>Collaboration</strong>: Teams can collaborate more effectively by sharing experiment results and visualizations.</li><li><strong>Model Versioning</strong>: W&amp;B supports model versioning, allowing you to keep track of different versions of your model and revert to previous versions if needed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sTUfc8dxdCoE4YY34D-u4Q.png" /><figcaption>By using Wandb we can easily visualise various metric and version of model training</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oBKCOKt7V2GNXh1SKjzCzw.png" /><figcaption>We can add various parameters while fine tuning of model and track them</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h_tKrf8Rv2CVJhU_zpKieg.png" /><figcaption>This image shows model fine tuned by various users with various stats</figcaption></figure><h3>Different Approaches for Fine-tuning</h3><p>Below are the most commonly used approaches to fine-tune LLM models.</p><ul><li><strong>Approach 1</strong>: Layer-wise Fine-Tuning — In this method, the pre-trained model’s early layers can be frozen while only the later layers are fine-tuned. Alternatively, the entire model can be fine-tuned.</li><li><strong>Approach 2</strong>: Parameter Selective Fine-tuning — This technique involves identifying and updating only a subset of parameters that are considered relevant to the task at hand.</li><li><strong>Approach 3</strong>: Adapter-based Fine-tuning — An alternative technique is to incorporate lightweight “adapter” modules alongside the pre-trained model. These adapters contain task-specific adjustments, enabling more precise fine-tuning.</li></ul><h3>Setting up Weight and Biases (W&amp;B)</h3><p>Weight and Biases (W&amp;B) is a powerful platform that helps track, visualize, and analyze machine learning experiments. It offers a range of features for experiment tracking, model visualization, and result analysis. To get started with W&amp;B, follow these steps:</p><ul><li>Sign Up: Create a free account on the Wandb (W&amp;B) website if you haven’t already.</li><li>Install the Library: Install the W&amp;B Python library.</li><li>Import the Library: Import the Wandb module in your Python script.</li><li>Initialise W&amp;B: Add the following code snippet at the beginning of your script to initialize W&amp;B.</li></ul><pre>pip install transformers datasets wandb peft scikit-learn bitsandbytes accelerate transformers[torch</pre><p>Now, we have configured W&amp;B. While fine-tuning the model, we are using QLoRA. Let&#39;s understand this in a very simple manner.</p><h4><strong>Fine-tuning the Language Model using QLoRA</strong></h4><p>LORA (Low-Rank Adaptation) is designed to efficiently fine-tune large-scale models by focusing on a small subset of the model’s weights that have the most significant impact on the task at hand. Unlike traditional fine-tuning, where a larger number of weights might be updated, LORA takes a different approach by Tracking modifications to weights instead of updating them directly. Decomposing large matrices of weight changes into smaller matrices that hold the “trainable parameters.”</p><p>This method offers several benefits:</p><ul><li>A major reduction in the number of trainable parameters resulting in faster and more efficient fine-tuning.</li><li>For Smaller Hardware: LoRA’s lower parameter count enables the fine-tuning of substantial models on less powerful hardware, like modest GPUs or CPUs</li><li>Preservation of the original pre-trained weights, which allows for the creation of multiple lightweight models tailored to different tasks.</li><li>Compatibility with other parameter-efficient techniques, enabling further optimisation.</li><li>Performance that is often comparable to fully fine-tuned models.</li><li>No additional inference latency since adapter weights can be merged with the base model.</li></ul><p><strong>QLoRa takes LORA a step further by quantizing the trainable parameters, representing them with fewer bits. This reduces the model size even more, potentially enabling deployment on devices with limited memory and computational resources.</strong></p><p>Example:</p><ul><li>Model Size: A model with 1 million weights in 32-bit floats requires 4 MB of memory.</li><li>16-bit Precision: Reduces memory usage to 2 MB.</li><li>8-bit Quantisation: Further reduces memory to 1 MB.</li></ul><p>Example:</p><p>Now, here is the same chart showing the LoRA trainable parameters as a percentage of the overall total model parameters. The table below shows the details of rank and parameter size.</p><pre>| Rank |   7B   |   13B  |   70B  |   180B  |<br>|------|--------|--------|--------|---------|<br>|  1   | 0.002% | 0.002% | 0.001% | 0.000%  |<br>|  2   | 0.005% | 0.004% | 0.002% | 0.001%  |<br>|  4   | 0.010% | 0.007% | 0.003% | 0.002%  |<br>|  8   | 0.019% | 0.014% | 0.006% | 0.004%  |<br>| 16   | 0.038% | 0.028% | 0.012% | 0.008%  |</pre><p>From above, we see as increase the rank, trainable parameter number increases.</p><p>Now, let’s dive into the fine-tuning process using the Hugging Face Transformers library and QLoRA for efficient fine-tuning.</p><pre>import torch<br>from datasets import Dataset<br>import wandb<br>from transformers import T5ForConditionalGeneration, T5Tokenizer, Trainer, TrainingArguments, TrainerCallback, AutoTokenizer, DataCollatorForSeq2Seq<br>from peft import LoftQConfig, LoraConfig, get_peft_model<br>from datasets import Dataset</pre><p><strong>Initialise W&amp;B</strong></p><pre>wandb.init(project=&quot;language_model_finetuning&quot;, entity=&quot;your_username&quot;)<br>#Custom callback for logging<br>class LoggingCallback(TrainerCallback):<br>def on_log(self, args, state, control, logs=None, **kwargs):<br>if logs is not None:<br>  wandb.log(logs)</pre><p><strong>Initialise Weights &amp; Biases</strong></p><pre>wandb.init(project=&quot;t5-finetuning-peft&quot;)</pre><p><strong>Sample data</strong></p><p>You can replace this sample data with your own data.</p><pre>train_data = [<br>{&quot;article&quot;: &quot;Fine-tuning language models can significantly improve their performance on specialized tasks. By training the model on task-specific data, it can learn the nuances of the task and provide better results.&quot;, &quot;summary&quot;: &quot;Fine-tuning improves model performance on specialized tasks.&quot;},<br>{&quot;article&quot;: &quot;Quantized methods like QLoRA are becoming popular for efficient fine-tuning of large language models. These methods reduce the computational resources required for training while maintaining accuracy.&quot;, &quot;summary&quot;: &quot;QLoRA enables efficient fine-tuning of large models.&quot;},<br>{&quot;article&quot;: &quot;Weight and Biases (W&amp;B) is a powerful tool for tracking and visualizing machine learning experiments. It helps data scientists monitor the training process and gain insights into model performance.&quot;, &quot;summary&quot;: &quot;W&amp;B aids in tracking and visualizing ML experiments.&quot;},<br>{&quot;article&quot;: &quot;Using pre-trained models as a starting point for fine-tuning can save time and resources. Pre-trained models have already learned a vast amount of information from large datasets.&quot;, &quot;summary&quot;: &quot;Pre-trained models save time and resources.&quot;},<br>{&quot;article&quot;: &quot;During fine-tuning, it is essential to monitor the model&#39;s loss and metrics to ensure it is learning correctly. Visualization tools can help in understanding the training process.&quot;, &quot;summary&quot;: &quot;Monitoring loss and metrics is crucial during fine-tuning.&quot;},<br>{&quot;article&quot;: &quot;Data augmentation techniques can help improve the robustness of machine learning models. By artificially increasing the diversity of the training data, models can generalize better to new, unseen data.&quot;, &quot;summary&quot;: &quot;Data augmentation improves model robustness.&quot;},<br>{&quot;article&quot;: &quot;Transfer learning involves using a pre-trained model on a new, but related task. This approach can accelerate the training process and improve model performance.&quot;, &quot;summary&quot;: &quot;Transfer learning accelerates training and improves performance.&quot;},<br>{&quot;article&quot;: &quot;Hyperparameter tuning is a critical step in optimizing model performance. Techniques like grid search and random search are commonly used to find the best hyperparameter values.&quot;, &quot;summary&quot;: &quot;Hyperparameter tuning optimizes model performance.&quot;},<br>{&quot;article&quot;: &quot;Regularization methods like dropout and weight decay help prevent overfitting in neural networks. These techniques ensure that the model generalizes well to new data.&quot;, &quot;summary&quot;: &quot;Regularization prevents overfitting in neural networks.&quot;},<br>{&quot;article&quot;: &quot;Cross-validation is a robust method for assessing the performance of machine learning models. It provides a more accurate estimate of model performance than a single train-test split.&quot;, &quot;summary&quot;: &quot;Cross-validation provides accurate performance estimates.&quot;}<br>]</pre><pre>test_data = [<br>{&quot;article&quot;: &quot;Active learning can reduce the amount of labeled data needed for training. By selectively choosing the most informative samples, models can learn more efficiently.&quot;, &quot;summary&quot;: &quot;Active learning reduces the need for labeled data.&quot;},<br>{&quot;article&quot;: &quot;Ensemble methods combine the predictions of multiple models to improve accuracy. Techniques like bagging and boosting are popular ensemble methods.&quot;, &quot;summary&quot;: &quot;Ensemble methods improve prediction accuracy.&quot;},<br>{&quot;article&quot;: &quot;Gradient descent is a fundamental optimization algorithm used to train machine learning models. Variants like stochastic gradient descent (SGD) offer improvements in convergence speed.&quot;, &quot;summary&quot;: &quot;Gradient descent and its variants optimize model training.&quot;}]</pre><pre>evaluation_data = [<br>{&quot;article&quot;: &quot;Feature engineering is the process of using domain knowledge to create features that make machine learning algorithms work better. It is a crucial step in building effective models.&quot;, &quot;summary&quot;: &quot;Feature engineering enhances model effectiveness.&quot;},<br>{&quot;article&quot;: &quot;Batch normalization is a technique used to improve the training of deep neural networks. It normalizes the input of each layer, allowing for faster and more stable training.&quot;, &quot;summary&quot;: &quot;Batch normalization stabilizes and speeds up training.&quot;},<br>{&quot;article&quot;: &quot;Model interpretability is important for understanding how machine learning models make decisions. Techniques like SHAP and LIME provide insights into model predictions.&quot;, &quot;summary&quot;: &quot;Model interpretability techniques provide insights into predictions.&quot;}]</pre><pre>train_dataset = Dataset.from_list(train_data)<br>test_dataset = Dataset.from_list(test_data)<br>eval_dataset = Dataset.from_list(evaluation_data)</pre><p>We will use the T5 model. T5 is an encoder-decoder model pre-trained on a multi-task mixture of unsupervised and supervised tasks, where each task is converted into a text-to-text format.</p><p><strong>Load the T5 tokenizer and model</strong></p><p>The t5-small tokenizer model has 60 million trainable parameters and 987MB of storage size.</p><pre>model_name = &#39;t5-small&#39;<br>tokenizer = T5Tokenizer.from_pretrained(model_name)<br>base_model = T5ForConditionalGeneration.from_pretrained(model_name)</pre><p><strong>Apply PEFT using LoRA</strong></p><pre>loftq_config = LoftQConfig(loftq_bits=4) # set 4bit quantization<br>lora_config = LoraConfig(<br>r=6, # Rank of the adaptation matrices<br>lora_alpha=16   #When the weight changes are added back into the original model weights, they are multiplied by a scaling factor that&#39;s #calculated as alpha divided by rank.<br>loftq_config=loftq_config,<br>target_modules=[&quot;k&quot;,&quot;q&quot;, &quot;v&quot;], # Target modules for LoRA adaptation<br>lora_dropout=0.1, # Dropout rate<br>bias=&quot;none&quot; # Whether to adapt bias terms<br>)<br>peft_model = get_peft_model(base_model, lora_config)<br>peft_model.print_trainable_parameters()</pre><p>We can clearly see here that after using PEFT configuration, trainable parameters were reduced from 60 million to nearly 3 lakhs.</p><p><strong>Preprocessing the datasets</strong></p><pre>def preprocess_function(examples):<br>  inputs = tokenizer(examples[&quot;article&quot;], padding=&quot;max_length&quot;, truncation=True, max_length=512)<br>  targets = tokenizer(examples[&quot;summary&quot;], padding=&quot;max_length&quot;, truncation=True, max_length=128)<br>  inputs[&quot;labels&quot;] = targets[&quot;input_ids&quot;]<br>  return inputs<br>train_dataset = train_dataset.map(preprocess_function, batched=True)<br>test_dataset = test_dataset.map(preprocess_function, batched=True)<br>eval_dataset = eval_dataset.map(preprocess_function, batched=True)</pre><p><strong>Define the </strong><strong>compute_metrics function</strong></p><pre>def compute_metrics(pred: EvalPrediction):<br>    metric = load_metric(&quot;rouge&quot;)<br>    labels_ids = pred.label_ids<br>    pred_ids = pred.predictions<br>    #Decode the predicted and true labels<br>    decoded_preds = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)<br>    decoded_labels = tokenizer.batch_decode(labels_ids, skip_special_tokens=True)<br>    # Rouge expects a newline after each sentence<br>    decoded_preds = [&quot;\n&quot;.join(pred.strip().split()) for pred in decoded_preds]<br>    decoded_labels = [&quot;\n&quot;.join(label.strip().split()) for label in decoded_labels]<br>    result = metric.compute(predictions=decoded_preds, references=decoded_labels)<br>  return {&quot;rouge1&quot;: result[&quot;rouge1&quot;].mid.fmeasure}</pre><p><strong>Define training arguments</strong></p><pre>training_args = TrainingArguments(do_eval=True,<br>output_dir=&quot;./results&quot;,<br>eval_strategy=&quot;steps&quot;, # Change to &quot;steps&quot; for more frequent logging<br>eval_steps=10, # Evaluate every 10 steps<br>logging_dir=&#39;./logs&#39;, # Directory for storing logs<br>logging_steps=20, # Log every 5 steps<br>learning_rate=2e-5,<br>per_device_train_batch_size=20,<br>per_device_eval_batch_size=20,<br>num_train_epochs=30,<br>weight_decay=0.01,<br>report_to=&quot;wandb&quot;,<br>)<br></pre><p><strong>Initialise the Trainer</strong></p><pre>trainer = Trainer(<br>model=peft_model,<br>args=training_args,<br>train_dataset=train_dataset,<br>eval_dataset=eval_dataset,<br>tokenizer=tokenizer,<br>compute_metrics=compute_metrics,<br>callbacks=[LoggingCallback()] # Add the custom logging callback<br>)<br>trainer.train()<br>eval_results = trainer.evaluate()</pre><p><strong>Save the model</strong></p><pre>trainer.save_model(&quot;./t5-finetuned&quot;)</pre><p>Now that we have a trained model, we need to merge the trained model with the base model. We can do that by calling merge_and_unload(). This method will merge the LoRA layers with the base model.</p><p><strong>Load LoRA adapter and merge</strong></p><pre>merged_model = peft_model.merge_and_unload()</pre><p><strong>Save the merged model</strong></p><pre>merged_model.save_pretrained(&quot;./t5-finetuned&quot;)</pre><p><strong>Finish the W&amp;B run</strong></p><pre>wandb.finish()</pre><p>Once this finishes, you will receive some links and logs provided by Weights &amp; Biases (Wandb). Upon clicking on these, you will see the results below, which include graphical visual representations. You can also add logs, tables, and many more elements as per your requirements.</p><p>We are getting such a great visualization in Wandb :</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*OBF42ip1dUQOEoITu8-jKA.png" /><figcaption>System resource usage</figcaption></figure><h4><strong>Issues While Fine-tuning LLMs</strong></h4><p>Fine-tuning large language models (LLMs) can present several challenges, such as resource intensiveness, overfitting, hyperparameter sensitivity, training instability:</p><p>W&amp;B provides a comprehensive dashboard to visualize the training process. Some of the key visualisations and benefits include such as track the loss over time to ensure the model is converging. Monitor metrics like accuracy, precision, recall, and F1-score. Analyze the effect of different hyperparameters on the model’s performance. Keep track of different versions of your model and compare their performance.</p><h3><strong>Conclusion</strong></h3><p>By utilizing QLoRA, we can reduce the model size and the number of trainable parameters. We can easily train and use a size LLM model and achieve better performance. Utilizing W&amp;B, we can gain valuable insights into the fine-tuning process and make informed decisions to improve the performance of our language models. The powerful visualization tools provided by W&amp;B allow us to monitor the model’s progress, track hyperparameters, and analyze the effects of different configurations. Incorporating W&amp;B into our fine-tuning workflow can significantly enhance our understanding and control over the training process.</p><h3><strong>Sources</strong></h3><ul><li><a href="https://docs.wandb.ai/">W&amp;B Docs | Weights &amp; Biases Documentation</a></li><li><a href="https://huggingface.co/transformers/">🤗 Transformers</a></li><li><a href="https://github.com/yogesh065/finetunnig-llm-on-local-machine-/blob/main/llm_finetune.ipynb">finetunnig-llm-on-local-machine-/llm_finetune.ipynb at main · yogesh065/finetunnig-llm-on-local-machine-</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adacfb23747e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/globant/fine-tuning-large-language-models-with-qlora-adacfb23747e">Fine-Tuning Large Language Models with QLoRA</a> was originally published in <a href="https://medium.com/globant">Globant</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>