Fine-Tuning Llama2 with LoRA

Fine-Tuning Llama2 with LoRA

  • 1. What is LoRA?
  • 2. How does LoRA work?
  • 3. Applying LoRA to Llama2 models
  • 4. LoRA finetuning recipe in torchtune
  • 5. Trading off memory and model performance with LoRA
  • Model Arguments
  • References

https://docs.pytorch.org/torchtune/main/tutorials/lora_finetune.html

This guide will teach you about LoRA, a parameter-efficient finetuning technique, and show you how you can use torchtune to finetune a Llama2 model with LoRA.

LoRA: Low-Rank Adaptation of Large Language Models
https://arxiv.org/abs/2106.09685

1. What is LoRA?

LoRA is an adapter-based method for parameter-efficient finetuning that adds trainable low-rank decomposition matrices to different layers of a neural network, then freezes the network’s remaining parameters. LoRA is most commonly applied to transformer models, in which case it is common to add the low-rank matrices to some of the linear projections in each transformer layer’s self-attention.

  • Note
    If you’re unfamiliar, check out these references for the definition of rank https://en.wikipedia.org/wiki/Rank_(linear_algebra) and discussion of low-rank approximations https://en.wikipedia.org/wiki/Low-rank_approximation.

By finetuning with LoRA (as opposed to finetuning all model parameters), you can expect to see memory savings due to a substantial reduction in the number of parameters with gradients. When using an optimizer with momentum, like AdamW https://docs.pytorch.org/docs/stable/generated/torch.optim.AdamW.html,
you can expect to see further memory savings from the optimizer state.

  • Note
    LoRA memory savings come primarily from gradient and optimizer states, so if your model’s peak memory comes in its forward() method, then LoRA may not reduce peak memory.

2. How does LoRA work?

LoRA replaces weight update matrices with a low-rank approximation. In general, weight updates for an arbitrary nn.Linear(in_dim,out_dim) layer could have rank as high as min(in_dim,out_dim). LoRA (and other related papers such as Aghajanyan et al.) hypothesize that the intrinsic dimension https://en.wikipedia.org/wiki/Intrinsic_dimension of these updates during LLM fine-tuning can in fact be much lower. To take advantage of this property, LoRA finetuning will freeze the original model, then add a trainable weight update from a low-rank projection. More explicitly, LoRA trains two matrices A and B. A projects the inputs down to a much smaller rank (often four or eight in practice), and B projects back up to the dimension output by the original linear layer.

hypothesize /haɪˈpɒθəsaɪz/
v. 假设;假定

Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning
https://arxiv.org/abs/2012.13255

The image below gives a simplified representation of a single weight update step from a full finetune (on the left) compared to a weight update step with LoRA (on the right). The LoRA matrices A and B serve as an approximation to the full rank weight update in blue.

在这里插入图片描述

Although LoRA introduces a few extra parameters in the model forward(), only the A and B matrices are trainable. This means that with a rank r LoRA decomposition, the number of gradients we need to store reduces from in_dim * out_dim to r * (in_dim+out_dim). (Remember that in general r is much smaller than in_dim and out_dim.)

For example, in the 7B Llama2’s self-attention, in_dim=out_dim=4096 for the Q, K, and V projections. This means a LoRA decomposition of rank r=8 will reduce the number of trainable parameters for a given projection from 4096 ∗ 4096 ≈ 15 M 4096 * 4096 \approx 15M 4096409615M to 8 ∗ 8192 ≈ 65 K 8 * 8192 \approx 65K 8819265K, a reduction of over 99%.

Let’s take a look at a minimal implementation of LoRA in native PyTorch.

import torch
from torch import nnclass LoRALinear(nn.Module):def __init__(self,in_dim: int,out_dim: int,rank: int,alpha: float,dropout: float):# These are the weights from the original pretrained modelself.linear = nn.Linear(in_dim, out_dim, bias=False)# These are the new LoRA params. In general rank << in_dim, out_dimself.lora_a = nn.Linear(in_dim, rank, bias=False)self.lora_b = nn.Linear(rank, out_dim, bias=False)# Rank and alpha are commonly-tuned hyperparametersself.rank = rankself.alpha = alpha# Most implementations also include some dropoutself.dropout = nn.Dropout(p=dropout)# The original params are frozen, and only LoRA params are trainable.self.linear.weight.requires_grad = Falseself.lora_a.weight.requires_grad = Trueself.lora_b.weight.requires_grad = Truedef forward(self, x: torch.Tensor) -> torch.Tensor:# This would be the output of the original modelfrozen_out = self.linear(x)# lora_a projects inputs down to the much smaller self.rank,# then lora_b projects back up to the output dimensionlora_out = self.lora_b(self.lora_a(self.dropout(x)))# Finally, scale by the alpha parameter (normalized by rank)# and add to the original model's outputsreturn frozen_out + (self.alpha / self.rank) * lora_out

There are some other details around initialization which we omit here, but if you’d like to know more you can see our implementation in LoRALinear https://docs.pytorch.org/torchtune/main/generated/torchtune.modules.peft.LoRALinear.html. Now that we understand what LoRA is doing, let’s look at how we can apply it to our favorite models.

3. Applying LoRA to Llama2 models

With torchtune, we can easily apply LoRA to Llama2 with a variety of different configurations. Let’s take a look at how to construct Llama2 models in torchtune with and without LoRA.

from torchtune.models.llama2 import llama2_7b, lora_llama2_7b# Build Llama2 without any LoRA layers
base_model = llama2_7b()# The default settings for lora_llama2_7b will match those for llama2_7b
# We just need to define which layers we want LoRA applied to.
# Within each self-attention, we can choose from ["q_proj", "k_proj", "v_proj", and "output_proj"].
# We can also set apply_lora_to_mlp=True or apply_lora_to_output=True to apply LoRA to other linear
# layers outside of the self-attention.
lora_model = lora_llama2_7b(lora_attn_modules=["q_proj", "v_proj"])
  • Note
    Calling lora_llama_2_7b https://docs.pytorch.org/torchtune/main/generated/torchtune.models.llama2.lora_llama2_7b.html alone will not handle the definition of which parameters are trainable.

Let’s inspect each of these models a bit more closely.

# Print the first layer's self-attention in the usual Llama2 model
>>> print(base_model.layers[0].attn)
MultiHeadAttention((q_proj): Linear(in_features=4096, out_features=4096, bias=False)(k_proj): Linear(in_features=4096, out_features=4096, bias=False)(v_proj): Linear(in_features=4096, out_features=4096, bias=False)(output_proj): Linear(in_features=4096, out_features=4096, bias=False)(pos_embeddings): RotaryPositionalEmbeddings()
)# Print the same for Llama2 with LoRA weights
>>> print(lora_model.layers[0].attn)
MultiHeadAttention((q_proj): LoRALinear((dropout): Dropout(p=0.0, inplace=False)(lora_a): Linear(in_features=4096, out_features=8, bias=False)(lora_b): Linear(in_features=8, out_features=4096, bias=False))(k_proj): Linear(in_features=4096, out_features=4096, bias=False)(v_proj): LoRALinear((dropout): Dropout(p=0.0, inplace=False)(lora_a): Linear(in_features=4096, out_features=8, bias=False)(lora_b): Linear(in_features=8, out_features=4096, bias=False))(output_proj): Linear(in_features=4096, out_features=4096, bias=False)(pos_embeddings): RotaryPositionalEmbeddings()
)

Notice that our LoRA model’s layer contains additional weights in the Q and V projections, as expected. Additionally, inspecting the type of lora_model and base_model, would show that they are both instances of the same TransformerDecoder https://docs.pytorch.org/torchtune/main/generated/torchtune.modules.TransformerDecoder.html.

Why does this matter? torchtune makes it easy to load checkpoints for LoRA directly from our Llama2 model without any wrappers or custom checkpoint conversion logic.

# Assuming that base_model already has the pretrained Llama2 weights,
# this will directly load them into your LoRA model without any conversion necessary.
lora_model.load_state_dict(base_model.state_dict(), strict=False)
  • Note
    Whenever loading weights with strict=False, you should verify that any missing or extra keys in the loaded state_dict are as expected. torchtune’s LoRA recipes do this by default via validate_missing_and_unexpected_for_lora() https://docs.pytorch.org/torchtune/main/generated/torchtune.modules.peft.validate_missing_and_unexpected_for_lora.html.

Once we’ve loaded the base model weights, we also want to set only LoRA parameters to trainable.

from torchtune.modules.peft.peft_utils import get_adapter_params, set_trainable_params# Fetch all params from the model that are associated with LoRA.
lora_params = get_adapter_params(lora_model)# Set requires_grad=True on lora_params, and requires_grad=False on all others.
set_trainable_params(lora_model, lora_params)# Print the total number of parameters
total_params = sum([p.numel() for p in lora_model.parameters()])
trainable_params = sum([p.numel() for p in lora_model.parameters() if p.requires_grad])
print(f"""{total_params} total params,{trainable_params}" trainable params,{(100.0 * trainable_params / total_params):.2f}% of all params are trainable."""
)6742609920 total params,
4194304 trainable params,
0.06% of all params are trainable.
  • Note
    If you are directly using the LoRA recipe, you need only pass the relevant checkpoint path. Loading model weights and setting trainable parameters will be taken care of in the recipe.
recipe /ˈresəpi/
n. 配方;食谱;方法;秘诀;烹饪法;诀窍

4. LoRA finetuning recipe in torchtune

Finally, we can put it all together and finetune a model using torchtune’s LoRA recipe. Make sure that you have first downloaded the Llama2 weights and tokenizer by following these instructions. You can then run the following command to perform a LoRA finetune of Llama2-7B with two GPUs (each having VRAM of at least 16GB):

tune run --nnodes 1 --nproc_per_node 2 lora_finetune_distributed --config llama2/7B_lora
  • Note
    Make sure to point to the location of your Llama2 weights and tokenizer. This can be done either by adding checkpointer.checkpoint_files=[my_model_checkpoint_path] tokenizer_checkpoint=my_tokenizer_checkpoint_path or by directly modifying the 7B_lora.yaml file. See our “All About Configs” https://docs.pytorch.org/torchtune/main/deep_dives/configs.html recipe for more details on how you can easily clone and modify torchtune configs.

  • Note
    You can modify the value of nproc_per_node depending on (a) the number of GPUs you have available, and (b) the memory constraints of your hardware.

The preceding command will run a LoRA finetune with torchtune’s factory settings, but we may want to experiment a bit. Let’s take a closer look at some of the lora_finetune_distributed config.

# Model Arguments
model:_component_: lora_llama2_7blora_attn_modules: ['q_proj', 'v_proj']lora_rank: 8lora_alpha: 16
...

We see that the default is to apply LoRA to Q and V projections with a rank of 8. Some experiments with LoRA have found that it can be beneficial to apply LoRA to all linear layers in the self-attention, and to increase the rank to 16 or 32. Note that this is likely to increase our max memory, but as long as we keep rank<<embed_dim, the impact should be relatively minor.

Let’s run this experiment. We can also increase alpha (in general it is good practice to scale alpha and rank together).

tune run --nnodes 1 --nproc_per_node 2 lora_finetune_distributed --config llama2/7B_lora \
lora_attn_modules=['q_proj','k_proj','v_proj','output_proj'] \
lora_rank=32 lora_alpha=64 output_dir=./lora_experiment_1

A comparison of the (smoothed) loss curves between this run and our baseline over the first 500 steps can be seen below.

在这里插入图片描述

  • Note
    The above figure was generated with W&B. You can use torchtune’s WandBLogger https://docs.pytorch.org/torchtune/main/generated/torchtune.training.metric_logging.WandBLogger.html to generate similar loss curves, but you will need to install W&B and setup an account separately. For more details on using W&B in torchtune, see our “Logging to Weights & Biases” https://docs.pytorch.org/torchtune/main/deep_dives/wandb_logging.html recipe.

5. Trading off memory and model performance with LoRA

In the preceding example, we ran LoRA on two devices. But given LoRA’s low memory footprint, we can run fine-tuning
on a single device using most commodity GPUs which support bfloat16 <https://en.wikipedia.org/wiki/Bfloat16_floating-point_format#bfloat16_floating-point_format>_
floating-point format. This can be done via the command:

… code-block:: bash

tune run lora_finetune_single_device --config llama2/7B_lora_single_device

On a single device, we may need to be more cognizant of our peak memory. Let’s run a few experiments
to see our peak memory during a finetune. We will experiment along two axes:
first, which model layers have LoRA applied, and second, the rank of each LoRA layer. (We will scale
alpha in parallel to LoRA rank, as discussed above.)

To compare the results of our experiments, we can evaluate our models on truthfulqa_mc2 <https://github.com/sylinrl/TruthfulQA>, a task from
the TruthfulQA <https://arxiv.org/abs/2109.07958>
benchmark for language models. For more details on how to run this and other evaluation tasks
with torchtune’s EleutherAI evaluation harness integration, see our :ref:End-to-End Workflow Tutorial <eval_harness_label>.

Previously, we only enabled LoRA for the linear layers in each self-attention module, but in fact there are other linear
layers we can apply LoRA to: MLP layers and our model’s final output projection. Note that for Llama-2-7B the final output
projection maps to the vocabulary dimension (32000 instead of 4096 as in the other linear layers), so enabling LoRA for this layer will increase
our peak memory a bit more than the other layers. We can make the following changes to our config:

… code-block:: yaml

Model Arguments

model:
component: lora_llama2_7b
lora_attn_modules: [‘q_proj’, ‘k_proj’, ‘v_proj’, ‘output_proj’]
apply_lora_to_mlp: True
apply_lora_to_output: True

… note::
All the finetuning runs below use the llama2/7B_lora_single_device <https://github.com/pytorch/torchtune/blob/main/recipes/configs/llama2/7B_lora_single_device.yaml>_
config, which has a default batch size of 2. Modifying the batch size (or other hyperparameters, e.g. the optimizer) will impact both peak memory
and final evaluation results.

… list-table::
:widths: 25 25 25 25 25
:header-rows: 1

    • LoRA Layers
    • Rank
    • Alpha
    • Peak Memory
    • Accuracy (truthfulqa_mc2)
    • Q and V only
    • 8
    • 16
    • 15.57 GB
    • 0.475
    • all layers
    • 8
    • 16
    • 15.87 GB
    • 0.508
    • Q and V only
    • 64
    • 128
    • 15.86 GB
    • 0.504
    • all layers
    • 64
    • 128
    • 17.04 GB
    • 0.514

We can see that our baseline settings give the lowest peak memory, but our evaluation performance is relatively lower.
By enabling LoRA for all linear layers and increasing the rank to 64, we see almost a 4% absolute improvement
in our accuracy on this task, but our peak memory also increases by about 1.4GB. These are just a couple simple
experiments; we encourage you to run your own finetunes to find the right tradeoff for your particular setup.

Additionally, if you want to decrease your model’s peak memory even further (and still potentially achieve similar
model quality results), you can check out our :ref:QLoRA tutorial<qlora_finetune_label>.

References

[1] Yongqiang Cheng, https://yongqiang.blog.csdn.net/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/80462.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

python打卡day29

类的装饰器 知识点回顾 类的装饰器装饰器思想的进一步理解&#xff1a;外部修改、动态类方法的定义&#xff1a;内部定义和外部定义 回顾一下&#xff0c;函数的装饰器是 &#xff1a;接收一个函数&#xff0c;返回一个修改后的函数。类也有修饰器&#xff0c;类装饰器本质上确…

十一、STM32入门学习之FREERTOS移植

目录 一、FreeRTOS1、源码下载&#xff1a;2、解压源码 二、移植步骤一&#xff1a;在需要移植的项目中新建myFreeRTOS的文件夹&#xff0c;用于存放FREERTOS的相关源码步骤二&#xff1a;keil中包含相关文件夹和文件引用路径步骤三&#xff1a;修改FreeRTOSConfig.h文件的相关…

2025 年十大网络安全预测

随着我们逐步迈向 2026 年&#xff0c;网络安全领域正处于一个关键的转折点&#xff0c;技术创新与数字威胁以前所未有的复杂态势交织在一起。 地缘政治环境进一步加剧了这些网络安全挑战&#xff0c;国际犯罪组织利用先进的技术能力来追求战略目标。 人工智能在这一不断演变…

Mac 环境下 JDK 版本切换全指南

概要 在 macOS 上安装了多个 JDK 后&#xff0c;可以通过系统自带的 /usr/libexec/java_home 工具来查询并切换不同版本的 Java。只需在终端中执行 /usr/libexec/java_home -V 列出所有已安装的 JDK&#xff0c;然后将你想使用的版本路径赋值给环境变量 JAVA_HOME&#xff0c;…

中级网络工程师知识点6

1.堆叠方式可以共享使用交换机背板带宽&#xff1b;级联方式可以使用双绞线将交换机连接在一起 2.光功率计是专门测量光功率大小的仪器&#xff0c;在对光缆进行检测时&#xff0c;通过在光缆的发送端和接收端分别测量光功率&#xff0c;进而计算出光衰情况。 3.光时域反射计…

动态规划——乌龟棋

题目描述 解题思路 首先这是一个很明显的线性dp的题目&#xff0c;很容易发现规律 数据输入 我们用 h[ N ] 数组存储每一个格子的分数 用 cnt [ ]&#xff0c;数组表示每一中卡片的数目 1&#xff0c;状态表示 因为这里一个有4种跳跃方式可以选择 f[ i ][ a ][ b ][ c ][ d…

C#自定义控件-实现了一个支持平移、缩放、双击重置的图像显示控件

1. 控件概述 这是一个继承自 Control 的自定义控件&#xff0c;主要用于图像的显示和交互操作&#xff0c;具有以下核心功能&#xff1a; 图像显示与缩放&#xff08;支持鼠标滚轮缩放&#xff09;图像平移&#xff08;支持鼠标拖拽&#xff09;视图重置&#xff08;双击重置…

C++ map multimap 容器:赋值、排序、大小与删除操作

概述 map和multimap是C STL中的关联容器&#xff0c;它们存储的是键值对(key-value pairs)&#xff0c;并且会根据键(key)自动排序。两者的主要区别在于&#xff1a; map不允许重复的键multimap允许重复的键 本文将详细解析示例代码中涉及的map操作&#xff0c;包括赋值、排…

AI Agent开发第70课-彻底消除RAG知识库幻觉(4)-解决知识库问答时语料“总重复”问题

开篇 “解决知识库幻觉”系列还在继续,这是因为:如果只是个人玩玩,像自媒体那些说的什么2小时搭一个知识库+deepseek不要太香一类的RAG或者是基于知识库的应用肯定是没法用在企业级落地上的。 我们真的经历过或者正在经历的人都是知道的,怎么可能2小时就搭建完成一个知识…

【DAY22】 复习日

内容来自浙大疏锦行python打卡训练营 浙大疏锦行 仔细回顾一下之前21天的内容 作业&#xff1a; 自行学习参考如何使用kaggle平台&#xff0c;写下使用注意点&#xff0c;并对下述比赛提交代码 kaggle泰坦里克号人员生还预测

【Docker】Docker Compose方式搭建分布式协调服务(Zookeeper)集群

开发分布式应用时,往往需要高度可靠的分布式协调,Apache ZooKeeper 致力于开发和维护开源服务器&#xff0c;以实现高度可靠的分布式协调。具体内容见zookeeper官网。现代应用往往使用云原生技术进行搭建,如何用Docker搭建Zookeeper集群,这里介绍使用Docker Compose方式搭建分布…

若依框架Consul微服务版本

1、最近使用若依前后端分离框架改造为Consul微服务版本 在这里分享出来供大家参考 # Consul微服务配置参数已经放置/bin/Consul微服务配置目录 仓库地址&#xff1a; gitee&#xff1a;https://gitee.com/zlxls/Ruoyi-Consul-Cloud.git gitcode&#xff1a;https://gitcode.c…

BOM知识点

BOM&#xff08;Browser Object Model&#xff09;即浏览器对象模型&#xff0c;是用于访问和操作浏览器窗口的编程接口。以下是一些BOM的知识点总结&#xff1a; 核心对象 • window&#xff1a;BOM的核心对象&#xff0c;代表浏览器窗口。它也是全局对象&#xff0c;所有全…

什么是迁移学习(Transfer Learning)?

什么是迁移学习&#xff08;Transfer Learning&#xff09;&#xff1f; 一句话概括 迁移学习研究如何把一个源领域&#xff08;source domain&#xff09;/源任务&#xff08;source task&#xff09;中获得的知识迁移到目标领域&#xff08;target domain&#xff09;/目标任…

[创业之路-362]:企业战略管理案例分析-3-战略制定-华为使命、愿景、价值观的演变过程

一、华为使命、愿景、价值观的演变过程 1、创业初期&#xff08;1987 - 1994 年&#xff09;&#xff1a;生存导向&#xff0c;文化萌芽 使命愿景雏形&#xff1a;1994年华为提出“10年之后&#xff0c;世界通信行业三分天下&#xff0c;华为将占一份”的宏伟梦想&#xff0c…

Python黑魔法与底层原理揭秘:突破语言边界的深度探索

Python黑魔法与底层原理揭秘&#xff1a;突破语言边界的深度探索 开篇&#xff1a;超越表面的Python Python常被称为"胶水语言"&#xff0c;但其真正的威力在于对底层的高度可控性。本文将揭示那些鲜为人知的Python黑魔法&#xff0c;带你深入CPython实现层面&…

Es的text和keyword类型以及如何修改类型

昨天同事触发定时任务发现es相关服务报了一个序列化问题&#xff0c; 今天早上捕获异常将异常堆栈全部打出来看&#xff0c;才发现是聚合的字段不是keyword类型的问题。 到kibbna命令行执行也是一样的错误 使用 /_mapping查看索引的字段类型&#xff0c;才发现userUniqueid是te…

大语言模型 07 - 从0开始训练GPT 0.25B参数量 - MiniMind 实机训练 预训练 监督微调

写在前面 GPT&#xff08;Generative Pre-trained Transformer&#xff09;是目前最广泛应用的大语言模型架构之一&#xff0c;其强大的自然语言理解与生成能力背后&#xff0c;是一个庞大而精细的训练流程。本文将从宏观到微观&#xff0c;系统讲解GPT的训练过程&#xff0c;…

【Android】从Choreographer到UI渲染(二)

【Android】从Choreographer到UI渲染&#xff08;二&#xff09; Google 在 2012 年推出的 Project Butter&#xff08;黄油计划&#xff09;是 Android 系统发展史上的重要里程碑&#xff0c;旨在解决长期存在的 UI 卡顿、响应延迟等问题&#xff0c;提升用户体验。 在 Androi…

mvc-ioc实现

IOC 1&#xff09;耦合/依赖 依赖&#xff0c;是谁离不开谁 就比如上诉的Controller层必须依赖于Service层&#xff0c;Service层依赖于Dao 在软件系统中&#xff0c;层与层之间存在依赖。我们称之为耦合 我们系统架构或者设计的一个原则是&#xff…