<?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 Ahmed Salhin on Medium]]></title>
        <description><![CDATA[Stories by Ahmed Salhin on Medium]]></description>
        <link>https://medium.com/@ahmedsalhin?source=rss-e79972c92570------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ANbtCJbaSMaVrkNYDwRLmw.jpeg</url>
            <title>Stories by Ahmed Salhin on Medium</title>
            <link>https://medium.com/@ahmedsalhin?source=rss-e79972c92570------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 19:38:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahmedsalhin/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[The Boring Work Nobody Talks About]]></title>
            <link>https://medium.com/@ahmedsalhin/the-boring-work-nobody-talks-about-aaeef2fa6271?source=rss-e79972c92570------2</link>
            <guid isPermaLink="false">https://medium.com/p/aaeef2fa6271</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[leadership]]></category>
            <dc:creator><![CDATA[Ahmed Salhin]]></dc:creator>
            <pubDate>Thu, 09 Apr 2026 09:12:35 GMT</pubDate>
            <atom:updated>2026-04-09T09:12:35.356Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sqYFsBRO0NuMZGHx" /><figcaption>Photo by <a href="https://unsplash.com/@serenarepice?utm_source=medium&amp;utm_medium=referral">Serena Repice Lentini</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There is an underrated value in doing the boring work nobody talks about.</p><p>Daniel Chambliss studied Olympic swimmers for years and found that excellence was usually not dramatic. It was mundane. Small things, done properly, over and over again.</p><p>The same idea shows up in tech teams. Data integrity, reliability, monitoring, maintenance, cleanup, edge cases. None of it looks exciting. But a lot of product quality and user trust sits on top of that invisible work.</p><p>At the same time, teams cannot live on maintenance alone.</p><p>They need to ship features, test ideas, create momentum, and learn from the market.</p><p>That is the real tension.</p><p>Not flashy work versus boring work.</p><p>Trust versus momentum.</p><p>Neglect the boring work, and the product becomes fragile. Neglect new work, and the team slows down in a different way.</p><p>The hardest part is when both are needed at once.</p><p>That is where judgement matters: knowing when to invest in the foundations, when to keep shipping, and how much weight to give each without pretending one side is always right.</p><p>Most of the tension here is not about values. It is about timing, prioritisation, and trade-offs.</p><p>Under constraint, the answer is usually not choosing one side once and for all. It is protecting some capacity for the invisible work before short-term urgency crowds it out.</p><p>Balance rarely comes from good intentions alone. It usually comes from making sure the important work does not have to win a fresh argument every single time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaeef2fa6271" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Losing Accuracy after LLM Quantization!]]></title>
            <link>https://medium.com/sage-ai/stop-losing-accuracy-after-llm-quantization-a06fa4883aeb?source=rss-e79972c92570------2</link>
            <guid isPermaLink="false">https://medium.com/p/a06fa4883aeb</guid>
            <category><![CDATA[quantization]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[model-quantization]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ahmed Salhin]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 15:21:02 GMT</pubDate>
            <atom:updated>2024-12-03T15:21:02.445Z</atom:updated>
            <content:encoded><![CDATA[<h4>How a Dequantize-First Approach Saves Your QLoRA Models after Merging</h4><p>Co-authors: <a href="https://medium.com/@yuchengtsai84">Yu-Cheng Tsai</a>, <a href="https://medium.com/@srijith.rajamohan">Srijith Rajamohan</a>, <a href="https://medium.com/@joshfrazier2113">Josh Frazier</a>, <a href="https://www.linkedin.com/in/todd-cook-5219495/">Todd Cook</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nNVm2GNTIuoCEBxvVune-g.png" /></figure><h3>TL;DR</h3><p>Fine-tuning large language models with <strong>Quantized LoRA (QLoRA)</strong> allows efficient updates to original model weights but may initially reduce accuracy when merging LoRA weights with quantized base weights. The solution is to <strong>first dequantize these layers</strong>, ensuring that merging preserves the model’s fine-tuned performance. This approach maintains accuracy after merging LoRA weights, while keeping the model lightweight for resource-efficient inference.</p><h3>The Story</h3><p>When fine-tuning a <strong>Large Language Model (LLM)</strong>, the goal is to adjust the weights to better capture patterns in your data. However, full fine-tuning of a model with a vast number of parameters can be challenging due to high computational costs, significant memory requirements, and the risk of overfitting — especially with limited data.</p><p>So, you’re thinking about fine-tuning an LLM on your own data. Maybe you want it to master specific patterns in your domain, or perhaps you have a downstream task in mind where you need the model to outperform off-the-shelf alternatives.</p><p>You’ve chosen the model, prepared the data, and fired up your GPU machine, all set to start coding and training. But there’s a catch: your resources aren’t unlimited, and time is ticking.</p><p>You need an efficient way to fine-tune without compromising too much on performance.</p><p>That’s when you stumble upon <strong>LoRA</strong> (Low-Rank Adaptation). With LoRA, you can avoid training the entire model’s weights, focusing instead on a more resource-friendly approach to fine-tuning.</p><p>You give it a shot, but soon you encounter the dreaded <strong>Out of Memory (OOM)</strong> error. You start looking for an alternative, and that’s when you find <strong>QLoRA ,</strong> an approach that follows LoRA’s efficiency but also quantizes model weights, allowing them to fit comfortably on a single machine while fine-tuning.</p><p>Problem solved!</p><p>Or so you thought.</p><p>After training with QLoRA, you run your evaluation and see great results. You save the model; merging the LoRA weights with the original ones to consolidate the learned adaptations into a single, unified model. This merging step is crucial, it ensures that the final model is ready for deployment or storage without relying on the extra LoRA modules. When you reload it and run another evaluation, the results are shocking. Accuracy has deteriorated, no matter whether you load it at higher or lower precision.</p><p>If this sounds familiar, or if you’re exploring a similar path, read on. This article will guide you through the exact steps needed to maintain the accuracy you saw during fine-tuning with QLoRA, all while achieving a much lighter memory footprint than the original model.</p><h3>Brief introduction to fine-tuning with LoRA</h3><p><strong>Low-Rank Adaptation (LoRA)</strong>, <a href="https://arxiv.org/pdf/2106.09685">introduced in 2021</a> proposed an efficient alternative to full fine-tuning. Instead of updating all model weights during fine-tuning, LoRA modifies only a small subset of parameters while preserving model performance.</p><p>The core concept involves freezing the pre-trained model’s original weights and injecting trainable low-rank decomposition matrices into the selected layers. Only these new matrices are trained, reducing both memory and computational load.</p><p>For example, consider the mistral-7b-instruct-v0.1 model, which is our focus in this article (though these methods apply to other models as well). When you load this model from HuggingFace and examine its architecture (Figure 1), you’ll notice multiple linear layers (in yellow).</p><figure><img alt="Figure 1 : Mistral-7B-Instruct-v0.1 structure prior to fine-tuning" src="https://cdn-images-1.medium.com/max/1024/1*Lx5IKzUOVt9CS7s0ao-u3A.png" /><figcaption>Figure 1 : Mistral-7B-Instruct-v0.1 structure prior to fine-tuning</figcaption></figure><p>Each linear layer represents a matrix W of shape ℝᵐ * ⁿ, where 𝓂 is the input features to the layer and 𝓃 is the output feature. LoRA decomposes this matrix into two smaller matrices, A and B, whose dimensions are determined by the rank 𝓇, a hyperparameter chosen by the user. This rank 𝓇 is much smaller than 𝓂 or 𝓃, allowing the dimensions of new matrices to be just a fraction of the original size, and therefore significantly reducing the resources required for training.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FxmQMo3u5wGs11YzDpdLj9s&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FxmQMo3u5wGs11YzDpdLj9s" width="416" height="380" frameborder="0" scrolling="no"><a href="https://medium.com/media/3209106b9c26f6aab4a13b97b9e5fffc/href">https://medium.com/media/3209106b9c26f6aab4a13b97b9e5fffc/href</a></iframe><p>For illustration and simplicity, let’s apply LoRA to a single linear layer, q_proj using <a href="https://github.com/huggingface/peft">PEFT</a>. As shown in Figure 1 (in blue and green colours), you’ll see that q_proj now includes additional components:</p><ul><li>lora_dropout</li><li>lora_a, and</li><li>lora_b</li></ul><p>lora_b</p><p>The original q_proj layer, has in_features=4096and out_features=4096, giving it a shape of (4096, 4096).</p><figure><img alt="Figure 2: Mistral-7B-Instruct-v0.1 structure after adding LoRA layers using PEFT" src="https://cdn-images-1.medium.com/max/1024/1*iDqAKo5VDMdZvZS5Nb6dKw.png" /><figcaption>Figure 2: Mistral-7B-Instruct-v0.1 structure after adding LoRA layers using PEFT</figcaption></figure><p>With a LoRA operation of rank 16, the dimensions of lora_a and lora_b are adapted as follows:</p><ul><li>lora_a has in_features = 4096 and out_features = 16.</li><li>lora_b has in_features = 16 and out_features = 4096.</li></ul><p>When lora_a is multiplied by lora_b, the resulting tensor dimension is (4096, 4096), matching the original q_proj layer’s shape. This match is intentional to ensure compatibility with the original model architecture. While LoRA does not explicitly use Singular Value Decomposition (SVD), it is inspired by the principles of low-rank approximation, where high-dimensional tensors can be approximated by the product of smaller, low-rank tensors.</p><p>Why employ this approach?</p><p>In short, it significantly reduces the number of trainable parameters, focusing training updates on lora_a, lora_b, and lora_dropout while keeping the original model layers frozen. Once the LoRA operation completes, the combined product of lora_a, lora_b, and lora_dropout is added back to q_proj as a low-rank update. Since this update shares the same (4096, 4096) dimension as the original matrix W, it integrates seamlessly.</p><p>You can refer to our earlier post and the merge and unload section of this post to understand this better.</p><p><a href="https://medium.com/sage-ai/a-practical-guide-fine-tuning-large-language-models-with-huggingface-3d4b8298b55f">A Practical Guide: Fine-Tuning Large Language Models with HuggingFace</a></p><p>This technique is an efficient way to reduce training requirements, saving computation resources. However, as large language models continue to grow, even this approach may not be enough to avoid GPU memory exhaustion. To further mitigate this issue, a quantization approaches were proposed, compressing model parameters to manage memory more effectively.</p><h3>Introduction to Quantization in LLM</h3><h4>Introduction to quantization</h4><p>Quantization reduces the precision of base model weights while striving not to lose too much accuracy. Typically, models are stored in <strong>FP32</strong> (32-bit floating-point format). With quantization, one can save the models in FP16, BF16, INT8, NF4 .., etc. Each of these formats offer a trade-off between precision and memory efficiency, with lower-bit formats generally consuming less memory but potentially sacrificing some model accuracy.</p><h4>Types of quantization</h4><p><strong>Post-Training Quantization (PTQ)</strong></p><p>PTQ is applied after a model has been fully trained. It involves converting the model’s weights and activations to lower precision formats without the need to retraining the model while its weights are quantized. This method is straightforward to implement but may result in some performance degradation:</p><p><strong>Quantization-Aware Training (QAT)</strong></p><p>QAT incorporates quantization effects during the training process. <strong>QLoRA</strong> is in this category. This approach allows the model to adapt to the reduced precision, often resulting in better performance compared to PTQ.</p><p>Here is a table summarizing the differences between the two:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*aJ39WQ6fWH_YlMI5TVNi-Q.png" /></figure><p><em>Why quantization?</em></p><p>Quantization offers two key benefits: smaller model size and reduced memory usage.</p><p><strong><em>Smaller Model Size: </em></strong>Quantized models take up less space, making them easier to store, transfer, and deploy across devices.</p><p><strong><em>Reduced Memory Consumption: </em></strong>Lower precision formats reduce memory needs during both training and inference, enabling models to run on devices with limited memory.</p><p>It’s important to note that quantization may also lead to longer inference times despite reduced memory usage. For a deeper look into this trade-off, you can refer to benchmark results like those provided by <a href="https://github.com/Lightning-AI/litgpt/blob/main/tutorials/quantize.md">LitGPT</a>, which show the effects of quantization on both memory usage and inference speed. We also observed the longer inference speed with quantized models.</p><p><strong>Quantization Techniques</strong></p><p>HuggingFace supports a wide range of quantization techniques on various hardware platforms, including CPU, CUDA GPU, RoCm GPU, Metal (Apple Silicon). They provide a compatibility table (Figure 3) to make selection of techniques possible.</p><figure><img alt="Figure 3: Quantization methods overview. Source: Hugging Face Transformers Documentation — Quantization Overview, accessed on 13 November 2024." src="https://cdn-images-1.medium.com/max/1024/1*vk_NSJDDssjO4GldoLxnLg.png" /><figcaption>Figure 3: Quantization methods overview. Source: Hugging Face <a href="https://huggingface.co/docs/transformers/v4.46.2/quantization/overview">Transformers Documentation — Quantization Overview</a>, accessed on 13 November 2024.</figcaption></figure><p>For deeper details, you can refer to this <a href="https://medium.com/@lmpo/understanding-model-quantization-for-llms-1573490d44ad">article</a></p><h4>QLoRA: Balancing Efficiency and Accuracy</h4><p>Quantizing LoRA fine-tuning (QLoRA) offers a way to fine-tune large language models by combining LoRA’s efficiency in training a subset of parameters with the quantization of base weights, which saves memory during fine-tuning.</p><p>Lets get back to how our model structure would look like when fine-tuning with QLoRA (Figure 4):</p><figure><img alt="Figure 4 : Mistral-7B-Instruct-v0.1 structure after fine tuning with QLoRA prior to merging." src="https://cdn-images-1.medium.com/max/1024/1*uwJ7d8203EmCVTxrEhNUqw.png" /><figcaption>Figure 4 : Mistral-7B-Instruct-v0.1 structure after fine tuning with QLoRA prior to merging</figcaption></figure><p>Focusing on the blue lines, each layer contains a base_layer quantized at 4 bits (indicated by the Linear4bit module), as well as lora_A and lora_B layers that remain in high precision (indicated by the Linear modules in green). This structure allows efficient training while maintaining precision where it matters for LoRA updates.</p><p>In many cases, you might expect a drop in model performance during fine-tuning due to the lower precision of weights in the forward pass. However, after fine-tuning, inference results should ideally be consistent, whether or not the LoRA weights are merged back into the base weights. In the non-merged model, inputs pass through both the base and LoRA layers, while in the merged model (after removing the LoRA layers in a process called “unloading”), inputs pass through a single layer with combined weights, theoretically yielding identical outputs. Unfortunately, this isn’t always the case. In the following sections, we’ll explore why incorrectly merge the LoRA weights can sometimes lead to unexpected accuracy drops and how to address this issue.</p><h3>Merge and unload</h3><p>If we use this model directly for inference, the input tokens would be embedded and passed through multiple layers of the transformer, including both the quantized base layers and the LoRA layers. The final layer would produce output embeddings for each token, which would then be processed to generate the predicted tokens. This process, followed by decoding, yields the final text output.</p><p>However, for streamlined inference, we want to “merge and unload” the LoRA layers. In this step, we merge the LoRA layers (lora_A and lora_B) into the base layer via a linear transformation and then remove (or “unload”) the LoRA layers, as they’re no longer needed for inference.</p><p>The merging process follows the formula:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FahF3M81L4eFmgH3t5ibrBd&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FahF3M81L4eFmgH3t5ibrBd" width="200" height="136" frameborder="0" scrolling="no"><a href="https://medium.com/media/134b0874a3c6c6dc400cced25f232720/href">https://medium.com/media/134b0874a3c6c6dc400cced25f232720/href</a></iframe><p>where:</p><ul><li><em>W</em> is the original, frozen at high precision, weight matrix.</li><li><em>ΔW</em> is the LoRA adjustments matrix the model learned during fine tuning represented as the product of two low-rank matrices, <em>Α</em> and <em>Β</em>.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2F6JgUrTmLVpwMZ4iSjkuy1A&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F6JgUrTmLVpwMZ4iSjkuy1A" width="200" height="136" frameborder="0" scrolling="no"><a href="https://medium.com/media/faba1d2eb77bbfd71f02496bb0155ead/href">https://medium.com/media/faba1d2eb77bbfd71f02496bb0155ead/href</a></iframe><p>The merging process is translated into:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2FhCMTxeDZjkaVC6MtdS1qcu&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FhCMTxeDZjkaVC6MtdS1qcu" width="200" height="137" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4816281921797d5d8c21de54f10832e/href">https://medium.com/media/e4816281921797d5d8c21de54f10832e/href</a></iframe><p>Here, <em>W′</em> becomes the updated weight matrix that combines both the original weights and the LoRA adjustments which will replace the original base_layer weights <em>W</em>.</p><p>During inference, the model will use this merged weight matrix <em>W′</em> in the forward pass. After merging, we can now safely discard the LoRA layers in what is called the “unload” step.</p><p>Here’s a code example illustrating how a basic, but an <strong>“inaccurate”</strong> merge-and-unload function might look:</p><pre>import torch<br>import logging<br><br>logging.basicConfig(level=logging.INFO)<br>logger = logging.getLogger(__name__)<br><br>def calculate_lora_weights(<br>    rank: int, lora_alpha: float, lora_A: torch.Tensor, lora_B: torch.Tensor<br>) -&gt; torch.Tensor:<br>    &quot;&quot;&quot;<br>    Computes the LoRA (Low-Rank Adaptation) weights by scaling the matrix product <br>    of LoRA A and B matrices.<br><br>    Args:<br>        rank (int): The rank (r) used in LoRA.<br>        lora_alpha (float): Scaling factor for LoRA.<br>        lora_A (torch.Tensor): LoRA A matrix.<br>        lora_B (torch.Tensor): LoRA B matrix.<br><br>    Returns:<br>        torch.Tensor: The scaled LoRA weights.<br>    &quot;&quot;&quot;<br>    scaling_factor = lora_alpha / rank<br>    logger.debug(f&quot;Calculating LoRA weights with scaling factor: {scaling_factor}&quot;)<br>    return (lora_B @ lora_A) * scaling_factor<br><br><br>def merge_lora_weights(<br>    base_layer: torch.nn.Module,<br>    finetuned_layer: torch.nn.Module,<br>    rank: int,<br>    lora_alpha: float,<br>) -&gt; torch.nn.Module:<br>    &quot;&quot;&quot;<br>    Merges the base pretrained weights with LoRA weights into the finetuned layer.<br><br>    Args:<br>        base_layer (torch.nn.Module): The base pretrained layer.<br>        finetuned_layer (torch.nn.Module): The LoRA finetuned layer.<br>        rank (int): The rank (r) used in LoRA.<br>        lora_alpha (float): Scaling factor for LoRA.<br><br>    Returns:<br>        torch.nn.Module: The finetuned layer with LoRA weights merged.<br>    &quot;&quot;&quot;<br>    logger.info(&quot;Merging LoRA weights into the finetuned layer.&quot;)<br><br>    # Extracting input/output features and weights<br>    input_features = finetuned_layer.lora_A.default.in_features<br>    output_features = finetuned_layer.lora_B.default.out_features<br>    logger.debug(f&quot;Input features: {input_features}, Output features: {output_features}&quot;)<br><br>    lora_A_weight = finetuned_layer.lora_A.default.weight<br>    lora_B_weight = finetuned_layer.lora_B.default.weight<br>    logger.debug(f&quot;LoRA A shape: {lora_A_weight.shape}, LoRA B shape: {lora_B_weight.shape}&quot;)<br><br>    # Calculate the LoRA weight matrix<br>    lora_weights = calculate_lora_weights(rank, lora_alpha, lora_A_weight, lora_B_weight)<br><br>    # Merge LoRA weights with base weights<br>    pretrained_dtype = finetuned_layer.base_layer.weight.data.dtype<br>    with torch.no_grad():<br>        logger.info(&quot;Adding LoRA weights to the pretrained base layer.&quot;)<br>        base_weight = finetuned_layer.weight<br>        finetuned_layer.weight.data += lora_weights.to(<br>            device=base_weight.data.device, dtype=pretrained_dtype<br>        )<br><br>    logger.info(&quot;LoRA weights successfully merged.&quot;)<br>    return finetuned_layer<br><br><br>def unload_model(model: torch.nn.Module) -&gt; torch.nn.Module:<br>    &quot;&quot;&quot;<br>    Unloads the model to free resources or return a reduced state.<br><br>    Args:<br>        model (torch.nn.Module): The input model to be unloaded.<br><br>    Returns:<br>        torch.nn.Module: The unloaded model.<br>    &quot;&quot;&quot;<br>    logger.info(&quot;Unloading the model.&quot;)<br>    return model.unload()</pre><h3>The incorrect way to merge Base model weights with LoRA layers</h3><p>The previous code demonstrates a common but incorrect approach to merging LoRA layers, which results in a discrepancy in model quality between pre-merge and post-merge states.</p><p>In theory, merging LoRA layers with the base model should not impact inference quality, as it is fundamentally a linear transformation. However, many developers rely on off-the-shelf merge_and_unload functions, such as <a href="https://huggingface.co/docs/peft/main/en/package_reference/lora#peft.LoraModel.merge_and_unload">Hugging Face&#39;s implementation</a>. While these functions follow the same merging logic—adding the <em>A</em> <em>* B</em> LoRA adjustments back into the base_layer weights—using them directly on a quantized model can lead to degraded quality in the fine-tuned model compared to inference with the unmerged layers.</p><h4>The Problem with Basic Merging on Quantized Models</h4><p>What’s happening here is that we’re merging high-precision LoRA adjustments into a 4-bit quantized base layer. To illustrate why this approach is problematic, let’s walk through a simple example.</p><p>First, let’s generate a random float32 number, which we’ll call 𝒮:</p><pre>import numpy as np<br>s = np.float32(np.random.uniform(-1, 1))<br>print(&quot;S:&quot;, s)</pre><p>Suppose 𝒮 equals -0.22289008.</p><p>Next, let’s quantize 𝒮 to 4-bit precision, like what we need to do in model quantization.</p><p>We will follow a Uniform Quantization where the range of an input sequence is divided into number of equally spaced zones. That’s a straight forward normalization and scaling of the 𝒮 using the following formula.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fmath.embed.fun%2Fx7LSXhZ8GNHSSg178oNfLo&amp;type=text%2Fhtml&amp;schema=embed&amp;display_name=Embed+Fun&amp;src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fx7LSXhZ8GNHSSg178oNfLo" width="310" height="158" frameborder="0" scrolling="no"><a href="https://medium.com/media/19f50582d60a021511d2708edc2467e4/href">https://medium.com/media/19f50582d60a021511d2708edc2467e4/href</a></iframe><ul><li>𝓎ₙ is the quantized sequence</li><li>𝓍ₙ is the input sequence</li><li><em>L</em> is the levels of quantization calculated as 2ᵇ where <em>b</em> is the number of bits used for quantization.</li></ul><p>Assuming our quantization range is -1 to 1, with 4-bit quantization (16 levels ( ²⁴)), we will have:</p><pre>quantization_levels = 16<br>min_val, max_val = -1.0, 1.0<br>quantized_s = np.round((s - min_val) / (max_val - min_val) * (quantization_levels - 1))<br>print(&quot;Quantized S:&quot;, quantized_s)</pre><p>After quantization, Quantized 𝒮 is 6.0, which represents the quantized version of a scaler value of the base model’s weight.</p><p>Now, let’s assume we have a second float32 value, <em>G</em>, resulting from fine-tuning with LoRA:</p><pre>g = np.float32(np.random.uniform(-1, 1))<br>print(&quot;G:&quot;, g)</pre><p>Suppose <em>G</em> equals 0.8382505.</p><p>Using a basic merge approach, we would add <em>G</em> (in its high-precision format) directly to the quantized 𝒮 (6.0), resulting in a merged weight of 6.8382505. This result, however, fails to capture the true weight adjustment accurately because it combines values of very different precisions.</p><h3>Correct Merging: Dequantization-First Approach</h3><p>To handle this correctly, we should first dequantize (the reverse process of quantization) 𝒮 back to its original float32 precision before merging as follow:</p><pre>dequantized_s = (quantized_s / (quantization_levels - 1)) * (max_val - min_val) + min_val<br>print(&quot;Dequantized S:&quot;, dequantized_s)</pre><p>For this randomly generated numbers, the dequantized 𝒮 would be approximately -0.1999996.</p><p>Now, when we merge 𝒮 and <em>G</em>, we get 0.6382509, a significant difference from the basic merge result of 6.8382505</p><p>Let’s explore how this dequantization-first approach applies to a model with a frozen, 4-bit quantized base layer and high precision, float32, LoRA layers, as shown in Figure 5 below.</p><figure><img alt="Figure 5 : Mistral-7B-Instruct-v0.1 structure after fine tuning with QLoRA prior to merging" src="https://cdn-images-1.medium.com/max/1024/1*KzGKeBP8lHiKr6fGbtXbFw.png" /><figcaption>Figure 5 : Mistral-7B-Instruct-v0.1 structure after fine tuning with QLoRA prior to merging</figcaption></figure><p>In this model, we need to iterate over its layers and, when we come across a quantized to 4-bit layer, dequantize it back to float32. For our model, the specific layer requiring this dequantization is highlighted in the yellow box in the figure.</p><p><strong>Steps in the Dequantization-First Approach:</strong></p><ol><li><strong>Identify Quantized Layers</strong>: Loop through each layer and check if it’s a quantized layer, as indicated by the bnb.nn.Linear4bit instance.</li><li><strong>Dequantize Weights</strong>: For each quantized layer, retrieve its quantization information from quant_state and use bnb.functional.dequantize_4bit to convert the 4-bit weights to a higher precision.</li><li><strong>Create a New Layer with Dequantized Weights</strong>: Initialize a new torch.nn.Linear layer with the same input and output sizes as the original 4-bit layer, then assign the dequantized weights to this new layer.</li><li><strong>Replace the Old Layer</strong>: Use _get_submodules from peft.utils to locate the parent module of the target layer, then replace the old quantized layer with the new high-precision module.</li></ol><pre>import bitsandbytes as bnb<br>from peft.utils import _get_submodules<br>import torch<br>import copy<br>import logging<br>from typing import Union<br><br>logging.basicConfig(level=logging.INFO)<br>logger = logging.getLogger(__name__)<br><br>def dequantize_model(<br>    model: torch.nn.Module, <br>    dtype: torch.dtype = torch.float32, <br>    device: str = &quot;cuda&quot;<br>) -&gt; torch.nn.Module:<br>    &quot;&quot;&quot;<br>    Converts all Linear4bit layers in the given model to standard PyTorch Linear layers <br>    with dequantized weights.<br>    <br>    Args:<br>        model (torch.nn.Module): The input model containing quantized layers.<br>        dtype (torch.dtype): The target data type for the dequantized weights (default: torch.float32).<br>        device (str): The target device for the new layers (default: &quot;cuda&quot;).<br>    <br>    Returns:<br>        torch.nn.Module: The model with Linear4bit layers replaced by standard Linear layers.<br>    &quot;&quot;&quot;<br>    logger.info(&quot;Starting dequantization process for the model.&quot;)<br>    layer_count = 0  # To count how many layers are dequantized<br><br>    with torch.no_grad():<br>        for module_name, module_instance, in model.named_modules():<br>            if isinstance(module_instance, bnb.nn.Linear4bit):<br>                logger.info(f&quot;Dequantizing layer: {module_name}&quot;)<br>                <br>                # Deep copy the quantization state to preserve original module properties<br>                quantization_state: dict = copy.deepcopy(module_instance.weight.quant_state)<br>                logger.debug(f&quot;Quantization state for layer {module_name}: {quantization_state}&quot;)<br><br>                # Dequantize the 4-bit weights and convert them to the desired dtype<br>                dequantized_weights: torch.Tensor = bnb.functional.dequantize_4bit(<br>                    module_instance.weight.data, <br>                    quant_state=quantization_state, <br>                    quant_type=&quot;nf4&quot;<br>                ).to(dtype)<br>                logger.debug(f&quot;Dequantized weights shape for layer {module_name}: {dequantized_weights.shape}&quot;)<br><br>                # Create a new Linear layer with the dequantized weights<br>                new_linear_layer: torch.nn.Linear = torch.nn.Linear(<br>                    in_features=module_instance.in_features, <br>                    out_features=module_instance.out_features, <br>                    bias=False, <br>                    dtype=dtype<br>                )<br>                new_linear_layer.weight = torch.nn.Parameter(dequantized_weights)<br>                new_linear_layer.to(device=device, dtype=dtype)<br><br>                # Replace the original module with the new one in the model<br>                parent_module: torch.nn.Module<br>                target_module: Union[torch.nn.Module, None]<br>                target_name: str<br>                parent_module, target_module, target_name = _get_submodules(model, module_name)<br>                setattr(parent_module, target_name, new_linear_layer)<br>                logger.info(f&quot;Replaced {module_name} with dequantized Linear layer.&quot;)<br><br>                layer_count += 1<br><br>    logger.info(f&quot;Dequantization process completed. Total layers dequantized: {layer_count}&quot;)<br>    return model</pre><p>After running this function, the base model will be fully dequantized, allowing it to be merged with the high-precision LoRA layers accurately.</p><p>Inspecting the model structure post merging and unloading, we would see LoRA layers disappearing with base layers appear in an unquatized as shown in Figure 6.</p><figure><img alt="Figure 6 : Mistral-7B-Instruct-v0.1 structure after fine tuning with QLoRA post merge and unload" src="https://cdn-images-1.medium.com/max/1024/1*MYf3_Dn2aw18bc-OkMqMlQ.png" /><figcaption>Figure 6: Mistral-7B-Instruct-v0.1 structure after fine tuning with QLoRA post merge and unload</figcaption></figure><p>Once merged, the model can be saved and reloaded at either high or low precision, preserving the quality achieved during fine-tuning.</p><h3>Summary</h3><p>Quantized LoRA (QLoRA) enables efficient fine-tuning of large models on limited resources by combining quantized base weights with LoRA adjustments. Directly merging LoRA adjustments into quantized layers can reduce accuracy due to precision mismatches. The solution is a <strong>dequantize-first approach</strong>, dequantizing base weights first, then merge LoRA updates, preserving accuracy without sacrificing memory efficiency. This method maintains fine-tuned performance and makes QLoRA ideal for resource-constrained environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a06fa4883aeb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sage-ai/stop-losing-accuracy-after-llm-quantization-a06fa4883aeb">Stop Losing Accuracy after LLM Quantization!</a> was originally published in <a href="https://medium.com/sage-ai">Sage Ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Run a Flask App in a Docker Container]]></title>
            <link>https://medium.com/@ahmedsalhin/run-a-flask-app-in-a-docker-container-d483dba9390b?source=rss-e79972c92570------2</link>
            <guid isPermaLink="false">https://medium.com/p/d483dba9390b</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Ahmed Salhin]]></dc:creator>
            <pubDate>Mon, 30 Jul 2018 11:28:05 GMT</pubDate>
            <atom:updated>2018-07-30T13:29:02.396Z</atom:updated>
            <content:encoded><![CDATA[<p>I like tutorials that first gets you to the output you want and then shows you the details. This is a straightforward tutorial on how to build a <a href="http://flask.pocoo.org/docs/1.0/">Flask</a> app and containerise it. I will then dive deeper into the details, a bit later than now.</p><p>Let’s get straight into this:</p><p>You either want to build a flask app, containerise an app or both. Anyway, here is how you can do that in very simple steps:</p><h3><strong>Build a Flask App</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ou6FFJJD3zhcIUU8wBZqIw.png" /></figure><p>Let’s start by building a classic ‘Hello World!” app on your local machine first and then containerise it later in the next step.</p><p>First install Flask:</p><pre>pip install Flask</pre><p>In a python script, lets call it “flasky.py”, add the following:</p><pre>from flask import Flask<br>app = Flask(__name__)<br>@app.route(&quot;/&quot;)<br>def hello():<br>    return &quot;Hello World!&quot;<br>if __name__ == &quot;__main__&quot;:<br>    app.run(host=&quot;0.0.0.0&quot;, port=int(&quot;4000&quot;), debug=True)</pre><p>Then run python flasky.py in your terminal</p><p>Here it will return the “Hello World!” string once you access the port 4000 in your local host.</p><p>Now let’s see how to host this app in a <a href="https://www.docker.com/">Docker</a> container</p><h3><strong>Dockerising a Flask App</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eiU8lzUwh35_xqAIDR-bYQ.png" /></figure><p>Remember, to run the “Hello World!” app you needed to install flask in your local machine first. You will need to do the same in the container before running the app.</p><p>To do so, let’s create a “requirements.txt” file that we can upload to the container in the next step. Just add the word flask to the “requirements.txt” file and save it in the same directory as the “flasky.py”.</p><p>You then need to pull an image from <a href="https://hub.docker.com/_/alpine/">Docker Hub</a> with linux and python installed, install the requirements, upload the app file and run it. Let’s do all that in three simple steps:</p><p>1- Create a file and call it “Dockerfile” and add the following to it:</p><pre>FROM python:alpine3.7<br>COPY . /flaskapp<br>WORKDIR /flaskapp<br>RUN pip install -r requirements.txt<br>EXPOSE 4000<br>CMD python ./flasky.py</pre><p><em>Here is what each line does:</em></p><p>FROM python:alpine3.7 → p<em>ulls an </em><a href="https://hub.docker.com/_/alpine/"><em>Alpine 3.7</em></a><em> image from Docker Hub</em></p><p>COPY . /flaskapp → <em>Copy files from your “local” to the container</em></p><p>WORKDIR /flaskapp → Change working directory</p><p>RUN pip install -r requirements.txt → Install requiremnts</p><p>Expose 4000 → Expose the port</p><p>CMD python ./flask.py → Run the flask app</p><p>2- Now you created the Dockerfile with the instructions to run the flask app, you now need to build the image from that file:</p><pre>docker build --tag my-flask-app .</pre><p>3- What is left is to run that image as a container with the following</p><pre>docker run --name flask-app -p 4000:4000 my-flask-app</pre><p>That’s all for now :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d483dba9390b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>