<?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 Sourab Mangrulkar on Medium]]></title>
        <description><![CDATA[Stories by Sourab Mangrulkar on Medium]]></description>
        <link>https://medium.com/@sourabmangrulkar?source=rss-16813f635c05------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VGVI8Z0LeaasuzWTtqfk9g.jpeg</url>
            <title>Stories by Sourab Mangrulkar on Medium</title>
            <link>https://medium.com/@sourabmangrulkar?source=rss-16813f635c05------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:59:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sourabmangrulkar/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[Falcon 180B Finetuning using  PEFT and DeepSpeed]]></title>
            <link>https://medium.com/@sourabmangrulkar/falcon-180b-finetuning-using-peft-and-deepspeed-b92643091d99?source=rss-16813f635c05------2</link>
            <guid isPermaLink="false">https://medium.com/p/b92643091d99</guid>
            <dc:creator><![CDATA[Sourab Mangrulkar]]></dc:creator>
            <pubDate>Mon, 02 Oct 2023 11:34:46 GMT</pubDate>
            <atom:updated>2024-03-04T12:28:17.389Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IbeH2W4UfU1cxOccXFMqtw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rAzITggI7GWr9vNwvfZW-g.png" /><figcaption>Chatbot using the Falcon 180B Chat &amp; Instruct Fine-tuned model using 🤗 PEFT and DeepSpeed.</figcaption></figure><p>In this blog post, we will look at how you can fine-tune humongous models like Falcon 180B using Hugging Face’s PEFT, DeepSpeed ZeRO-3, Flash Attention and Gradient Checkpointing using just 16 A100 80GB GPUs, a fraction of the 1024 GPUs typically used for such tasks. What makes this even more compelling is that the resulting model not only consumes significantly fewer resources but also outperforms the official Falcon-180B and FalconChat-180B models on the OpenLLM Leaderboard by a remarkable <strong>3%</strong>. So, not only does this save on computational power, but it also delivers superior results. And the cherry on top? The cost of training this model comes in at just $864 (36 hrs * $24/hr), a mere fraction of what it would take to fine-tune the chat version of Falcon-180B. Let’s dive in and discover how to achieve this impressive feat!</p><h3>Introduction</h3><h4>DeepSpeed Zero Redundancy Optimizer (ZeRO)</h4><p>It is a paradigm in which the optimizer states, gradients and parameters are sharded across devices. It results in huge memory savings allowing to scale training to large LLMs and higher batch sizes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/0*aD7R3_j_2QzZbf_B.png" /><figcaption>(Source: <a href="https://www.microsoft.com/en-us/research/blog/zero-deepspeed-new-system-optimizations-enable-training-models-with-over-100-billion-parameters/">link</a>) DeepSpeed ZeRO</figcaption></figure><p>Stage 1 : Shards optimizer states across data parallel workers/GPUs</p><p>Stage 2 : Shards optimizer states + gradients across data parallel workers/GPUs</p><p>Stage 3: Shards optimizer states + gradients + model parameters across data parallel workers/GPUs</p><p>Optimizer Offload: Offloads the gradients + optimizer states to CPU/Disk building on top of ZERO Stage 2</p><p>Param Offload: Offloads the model parameters to CPU/Disk building on top of ZERO Stage 3</p><h4><strong>Parameter Efficient Fine-Tuning (PEFT) and Low Rank Adaptation (LoRA)</strong></h4><p>As models get larger and larger, full fine-tuning becomes infeasible to train on consumer hardware. In addition, storing and deploying fine-tuned models independently for each downstream task becomes very expensive, because fine-tuned models are the same size as the original pretrained model.</p><p>Parameter-Efficient Fine-Tuning (PEFT) is a technique that allows us to fine-tune a large pretrained model on a specific downstream task while requiring significantly fewer parameters than full fine-tuning. The goal is to achieve comparable or even better performance than full fine-tuning, while requiring less computation and memory resources.</p><p>PEFT approaches only fine-tune a small number of (extra) model parameters while freezing most parameters of the pretrained LLMs, thereby greatly decreasing the computational and storage costs. This also overcomes the issues of catastrophic forgetting, a behaviour observed during the full finetuning of LLMs. PEFT approaches have also shown to be better than fine-tuning in the low-data regimes and generalize better to out-of-domain scenarios. It can be applied to various modalities, e.g., image classification and stable diffusion dreambooth.</p><p>It also helps in portability wherein users can tune models using PEFT methods to get tiny checkpoints worth a few MBs compared to the large checkpoints of full fine-tuning, e.g., bigscience/mt0-xxl takes up 40GB of storage and full fine-tuning will lead to 40GB checkpoints for each downstream dataset whereas using PEFT methods it would be just a few MBs for each downstream dataset all the while achieving comparable performance to full fine-tuning. The small trained weights from PEFT approaches are added on top of the pretrained LLM. So, the same LLM can be used for multiple tasks by adding small weights without having to replace the entire model.</p><p><a href="https://github.com/huggingface/peft"><strong>🤗 PEFT</strong></a> library provides the latest Parameter-Efficient Fine-tuning techniques seamlessly integrated with 🤗 Transformers and 🤗 Accelerate. This enables the use of the most popular and performant models from Transformers coupled with the simplicity and scalability of Accelerate.</p><p>For further information, please go through the below blogpost.</p><p><a href="https://huggingface.co/blog/peft">Parameter-Efficient Fine-Tuning using 🤗 PEFT</a></p><p>LoRA is a PEFT method which employs memory efficient reparametrization trick by adapting small additional trainable parameters on target modules (usually query, value layers on transformer attention blocks). Thereby, drastically reduces the number of trainable parameters. One of the nice features of LoRA is that there is no latency addition during inference as the additional trainable parameters are added back to the original weights. This method achieves comparable performance to full fine-tuning which makes its usage widespread across the community.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x87l4UskPlUGgQVoDlAYAg.png" /><figcaption>LoRA implementation. Figure 1 from LoRA paper (Hu. et al.)</figcaption></figure><h4><strong>Flash Attention</strong></h4><p>Flash Attention and enabling gradient checkpointing are required for faster training and reducing VRAM usage to enable fine-tuning and save compute costs. The codebase currently uses monkey patching and the implementation is at <a href="https://github.com/pacman100/DHS-LLM-Workshop/blob/main/chat_assistant/training/falcon_flash_attn_monkey_patch.py">DHS-LLM-Workshop/chat_assistant/training/falcon_flash_attn_monkey_patch.py</a></p><p><a href="https://arxiv.org/pdf/2205.14135.pdf">FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness</a> introduces a way to compute exact attention while being faster and memory-efficient by leveraging the knowledge of the memory hierarchy of the underlying hardware/GPUs — The higher the bandwidth/speed of the memory, the smaller its capacity as it becomes more expensive.</p><p>If we follow the blog <a href="https://horace.io/brrr_intro.html">Making Deep Learning Go Brrrr From First Principles</a>, we can figure out that Attention module on current hardware is memory-bound/bandwidth-bound. The reason being that Attention mostly consists of elementwise operations as shown below on the left hand side. We can observe that masking, softmax and dropout operations take up the bulk of the time instead of matrix multiplications which consists of the bulk of FLOPs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*Oe0TS2lC4X1UIQYutesa3A.png" /><figcaption>(Source: <a href="https://arxiv.org/pdf/2205.14135.pdf">link</a>)</figcaption></figure><p>This is precisely the problem that Flash Attention addresses. The idea is to remove redundant HBM reads/writes. It does so by keeping everything in SRAM, perform all the intermediate steps and only then write the final result back to HBM, also known as Kernel Fusion. Below is an illustration of how this overcomes the memory-bound bottleneck.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*-eqzu4TW93nhUhFAv-Js7g.png" /><figcaption>(Source: <a href="https://gordicaleksa.medium.com/eli5-flash-attention-5c44017022ad">link</a>)</figcaption></figure><p>Tiling is used during forward and backward passes to chunk the NxN softmax/scores computation into blocks to overcome the limitation of SRAM memory size. To enable tiling, online softmax algorithm is used. Recomputation is used during backward pass in order to avoid storing the entire NxN softmax/score matrix during forward pass. This greatly reduces the memory consumption.</p><p>For a simplified and in depth understanding of Flash Attention, please refer the blog posts <a href="https://gordicaleksa.medium.com/eli5-flash-attention-5c44017022ad">ELI5: FlashAttention</a> and <a href="https://horace.io/brrr_intro.html">Making Deep Learning Go Brrrr From First Principles</a> along with the original paper <a href="https://arxiv.org/pdf/2205.14135.pdf">FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness</a>.</p><h3>Hardware and Environment</h3><p>Number of nodes: 2.<br>Number of GPUs per node: 8<br>GPU type: A100<br>GPU memory: 80GB<br>intra-node connection: NVLink<br>RAM per node: 1TB<br>CPU cores per node: 96<br>inter-node connection: Elastic Fabric Adapter</p><h3>Dataset</h3><p>This dataset is focused on improving LLM logical reasoning skills and conversation skills. It is comprised of the following datasets and it can be found on the hub at <a href="https://huggingface.co/datasets/smangrul/chat-instruct-mixer">smangrul/chat-instruct-mixer</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bUiEAopR0OykAdWKXhE3Iw.png" /><figcaption>Chat-Instruct-Mixer Dataset Constituents</figcaption></figure><h3>Fine-Tuning</h3><p>Below is the command showcasing how to use Accelerate launcher to run the training. Notice that we are overriding main_process_ip , main_process_port , machine_rank , num_processes and num_machines values of the fsdp_config.yaml. Here, another important point to note is that the storage is stored between all the nodes. The training code can be found at <a href="https://github.com/pacman100/DHS-LLM-Workshop/blob/main/chat_assistant/sft/training/train.py">DHS-LLM-Workshop/chat_assistant/sft/training/train.py</a></p><pre><br>accelerate launch \<br>    --config_file configs/deepspeed_config.yaml \<br>    --main_process_ip $MASTER_ADDR \<br>    --main_process_port $MASTER_PORT \<br>    --machine_rank \$SLURM_PROCID \<br>    --num_processes 16 \<br>    --num_machines 2 \<br>    train.py \<br>    --model_name &quot;tiiuae/falcon-180B&quot; \<br>    --dataset_name &quot;smangrul/chat-instruct-mixer&quot; \<br>    --max_seq_len 2048 \<br>    --bf16 True \<br>    --max_steps 5000 \<br>    --logging_steps 25 \<br>    --eval_steps 1000 \<br>    --save_steps 100 \<br>    --packing True \<br>    --output_dir &quot;./experiments/falcon-180B-chat-asst-ds-lora-v3&quot; \<br>    --per_device_train_batch_size 1 \<br>    --gradient_accumulation_steps 1 \<br>    --dataset_text_field &quot;content&quot; \<br>    --lr_scheduler_type &quot;cosine&quot; \<br>    --weight_decay 0.01 \<br>    --warmup_ratio 0.03 \<br>    --use_flash_attn True \<br>    --use_gradient_checkpointing True \<br>    --use_peft_lora True \<br>    --lora_r 16 \<br>    --lora_alpha 32 \<br>    --lora_dropout 0.1 \<br>    --lora_target_modules &quot;query_key_value,dense,dense_h_to_4h,dense_4h_to_h&quot;</pre><p>The DeepSpeed config is available at <a href="https://github.com/pacman100/DHS-LLM-Workshop/blob/main/chat_assistant/training/configs/deepspeed_config.yaml">DHS-LLM-Workshop/chat_assistant/training/configs/deepspeed_config.yaml</a> and also given below:</p><pre>compute_environment: LOCAL_MACHINE                                                                                             <br>debug: false<br>deepspeed_config:<br>  deepspeed_multinode_launcher: standard<br>  gradient_accumulation_steps: 1<br>  offload_optimizer_device: none<br>  offload_param_device: none<br>  zero3_init_flag: true<br>  zero3_save_16bit_model: true<br>  zero_stage: 3<br>distributed_type: DEEPSPEED<br>downcast_bf16: &#39;no&#39;<br>machine_rank: 0<br>main_training_function: main<br>mixed_precision: bf16<br>num_machines: 1<br>num_processes: 8<br>rdzv_backend: static<br>same_network: true<br>tpu_env: []<br>tpu_use_cluster: false<br>tpu_use_sudo: false<br>use_cpu: false</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j5QHeRZsiC5T2R-g5qgWHg.png" /><figcaption>Finetuning plots displaying the eval loss, train loss and learning rate schedule respectively.</figcaption></figure><p>Above are the plots displaying the eval loss, train loss and learning rate schedule respectively. We can observe the training progressed as expected.</p><p>Notice that the training time is above 30 hours. As per logs, it took 36 hours in total. Therefore, the <strong>cost of training this model comes in at just $864 (36 hrs * $24/hr)</strong>, a mere fraction of what it would take to fine-tune the chat version of Falcon-180B. The price is based on the <a href="https://lambdalabs.com/service/gpu-cloud/pricing">Lambda GPU Cloud | VM Pricing and Specs (lambdalabs.com)</a>.</p><p>The trained model checkpointing can be found here: <a href="https://huggingface.co/smangrul/falcon-180B-chat-asst-ds-lora">smangrul/falcon-180B-chat-asst-ds-lora</a></p><h3>Evaluation</h3><p>We evaluate the model as per the <a href="https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard">Open LLM Leaderboard — a Hugging Face Space by HuggingFaceH4</a> and below are the results. We can observe that our fine-tuned model outperforms the official Falcon-180B and FalconChat-180B models by a remarkable <strong>3% (relative gains)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tEapMCzJH6vh6_3teX44ww.png" /><figcaption>Open LLM Leaderboard metrics of various Falcon 180B variants. PEFT+DeepSpeed finetuned model achieves the best performance with ~3% improvement over the previous best.</figcaption></figure><h4>Qualitative Evaluation</h4><p>Let’s take a look at a few examples to gauge the model’s capabilities qualitatively:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IOKRroyMz-iVW1Y7d3hFZg.png" /><figcaption>Helping with Marketing Copy</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Bc1XHbsaiKItpchXBJulA.png" /><figcaption>Talking to a persona</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jxSY-cfGbX3FkoipVxSvNQ.png" /><figcaption>Coding</figcaption></figure><h3>Conclusion</h3><p>We successfully fine-tuned Falcon-180B model using LoRA and DeepSpeed in a multi-node multi-gpu setting. We went over a brief overview of DeepSpeed, PEFT methods and Flash Attention. This was followed by the description of the dataset to be used for fine-tuning, finetuning codebase and the script launching command with the related hyperparameters. We looked at the cost and performance of the resulting model which can be found here:<strong> </strong><a href="https://huggingface.co/smangrul/falcon-180B-chat-asst-ds-lora">smangrul/falcon-180B-chat-asst-ds-lora</a>. The fine-tuned model outperformed the original models on the Open LLM leaderboard by <strong>3% </strong>while being extremely computationally efficient and it only cost $<strong>864. Therefore, fine-tuning LLMs using PEFT and DeepSpeed is a good alternative to Full Fine-tuning in a computationally resource-constrained scenario.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b92643091d99" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>