Archive of AI

Source Snapshot / 2021-06-17-microsoft-lora-peft-2

microsoft/LoRA

Linked event: 2021-06-17 · Microsoft Research Proposes and Open-Sources LoRA, Establishing the Standard for Low-Cost Large Model Fine-Tuning

Publisher
GitHub
Archived
2026-11-23
Capture Method
Direct page capture
HTTP / SHA-256
200 / e8b11d37b83f0639
Original URL
Open source ↗
Wayback Backup
Not archived
This page preserves a plain-text static snapshot against link rot. When citing figures, tables, or full legal terms, verify against the original URL and Wayback Machine archive.

[来源关键摘录] Code for loralib, an implementation of LoRA: Low-Rank Adaptation of Large Language Models.

[正文前段节选] Skip to content

Navigation Menu

Appearance settings

You signed in with another tab or window. Reload to refresh your session.

You signed out in another tab or window. Reload to refresh your session.

You switched accounts on another tab or window. Reload to refresh your session.

Dismiss alert

{{ message }}

Repository navigation

NotificationsYou must be signed in to change notification settings

Fork935 (935)

Star13.9k (13.9k)You must be signed in to star a repository

Code for loralib, an implementation of "LoRA: Low-Rank Adaptation of Large Language Models"

arxiv.org/abs/2106.09685

adaptationdebertadeep-learninggpt-2gpt-3language-modelloralow-rankpytorchroberta

Code of conduct

Security policy

Custom properties

Report repository

BranchesTags

Open more actions menu

Latest commit

Folders and files

Last commit message

Last commit date

View all files

Repository files navigation

LoRA: Low-Rank Adaptation of Large Language Models

This repo contains the source code of the Python package loralib and several examples of how to integrate it with PyTorch models, such as those in Hugging Face.

We only support PyTorch for now.

See our paper for a detailed description of LoRA.

Edward J. Hu*, Yelong Shen*, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen

Paper: https://arxiv.org/abs/2106.09685

Video explainer: https://www.youtube.com/watch?v=DhRoTONcyZE

Update 2/2023: LoRA is now supported by the State-of-the-art Parameter-Efficient Fine-Tuning (PEFT) library by Hugging Face.

LoRA reduces the number of trainable parameters by learning pairs of rank-decompostion matrices while freezing the original weights.

This vastly reduces the storage requirement for large language models adapted to specific tasks and enables efficient task-switching during deployment all without introducing inference latency.

LoRA also outperforms several other adaptation methods including adapter, prefix-tuning, and fine-tuning.

We obtain result comparable or superior to full finetuning on the GLUE benchmark using RoBERTa (Liu et al., 2019) base and large and DeBERTa (He et al., 2020) XXL 1.5B, while only training and storing a fraction of the parameters. Click the numbers below to download the RoBERTa and DeBERTa LoRA checkpoints.

RoBERTa base Fine-tune

RoBERTa base LoRA

DeBERTa XXL Fine-tune

DeBERTa XXL LoRA

# of Trainable Params.

MNLI (m-Acc/mm-Acc)

87.5±.3/86.9±.3

91.9±.1/91.9±.2

CoLA (Matthew's Corr)

STSB (Pearson/Spearman Corr)

91.5±.2/91.3±.2

93.0±.2/92.9±.3

Note: You still need the original pre-trained checkpoint from Hugging Face to use the LoRA checkpoints.

Fine-tuning numbers are taken from Liu et al. (2019) and He et al. (2020). We include confidence intervals on results from our experiments. Please follow the instructions in examples/NLU/ to reproduce our results.

On GPT-2, LoRA compares favorably to both full finetuning and other efficient tuning methods, such as adapter (Houlsby et al., 2019) and prefix tuning (Li and Liang, 2021). We evaluated on E2E NLG Challenge, DART, and WebNLG:

# of Trainable Params

WebNLG (BLEU-U/S/A)

GPT-2 M (Fine-Tune)

30.4/63.2/47.6

GPT-2 M (Adapter)

45.1/54.5/50.2

GPT-2 M (Prefix)

44.1/63.1/54.4

GPT-2 M (LoRA)

46.7±.4/62.1±.2/55.3±.2

GPT-2 L (Fine-Tune)

41.7/64.6/54.2

GPT-2 L (Adapter)

49.8±.0/61.1±.0/56.0±.0

GPT-2 L (Prefix)

47.0/64.2/56.4

GPT-2 L (LoRA)

48.4±.3/64.0±.3/57.0±.1

Non-LoRA baselines, except for adapter on GPT-2 large, are taken from Li and Liang (2021). We include confidence intervals on results from our experiments.

Download the GPT-2 LoRA checkpoints:

GPT-2 Medium E2E (1.5 MB)

GPT-2 Medium DART (1.5 MB)

GPT-2 Medium WebNLG (1.5 MB)

GPT-2 Large E2E (2.3 MB)

GPT-2 Large DART (2.3 MB)

GPT-2 Large WebNLG (2.3 MB)

Please follow the instructions in examples/NLG/ to reproduce our result.

Repository Overview

(The initial release of this repo has been archived in the branch "snapshot-9-15-2021")

There are several directories in this repo:

loralib/ contains the source code for the package loralib, which needs to be installed to run the examples we provide;

examples/NLG/ contains an example implementation of LoRA in GPT-2 using our package, which can be used to reproduce the result in our paper;

examples/NLU/ contains an example implementation of LoRA in RoBERTa and DeBERTa using our package, which produces competitive results on the GLUE benchmark;

See how we use loralib in GPT-2, RoBERTa, and DeBERTa v2

Installing loralib is simply

pip install loralib

# Alternatively

# pip install git+https://github.com/microsoft/LoRA

You can choose to adapt some layers by replacing them with counterparts implemented in loralib. We only support nn.Linear, nn.Embedding, and nn.Conv2d for now. We also support a MergedLinear for cases where a single nn.Linear represents more than one layers, such as in some implementations of the attention qkv projection (see Additional Notes for more).

# ===== Before =====

# layer = nn.Linear(in_features, out_features)

# ===== After ======

import loralib as lora

# Add a pair of low-rank adaptation matrices with rank r=16

layer = lora.Linear(in_features, out_features, r=16)

Before the training loop begins, mark only LoRA parameters as trainable.

model = BigModel()

# This sets requires_grad to False for all parameters without the string "lora_" in their names

lora.mark_only_lora_as_trainable(model)

# Training loop

for batch in dataloader:

When saving a checkpoint, generate a state_dict that only contains LoRA parameters.

# torch.save(model.state_dict(), checkpoint_path)

# ===== After =====

torch.save(lora.lora_state_dict(model), checkpoint_path)

When loading a checkpoint using load_state_dict, be sure to set strict=False.

# Load the pretrained checkpoint first

model.load_state_dict(torch.load('ckpt_pretrained.pt'), strict=False)

# Then load the LoRA checkpoint

model.load_state_dict(torch.load('ckpt_lora.pt'), strict=False)

Now training can proceed as usual.

Additional Notes

While we focus on a simple yet effect setup, namely adapting only the q and v projection in a Transformer, in our examples, LoRA can be apply to any subsets of pre-trained weights. We encourage you to explore different configurations, such as adapting the embedding layer by replacing nn.Embedding with lora.Embedding and/or adapting the MLP layers. It's very likely that the optimal configuration varies for different model architectures and tasks.

Some Transformer implementation uses a single nn.Linear for the projection matrices for query, key, and value. If one wishes to constrain the rank of the updates to the individual matrices, one has to either break it up into three separate matrices or use lora.MergedLinear. Make sure to modify the checkpoint accordingly if you choose to break up the layer.

# qkv_proj = nn.Linear(d_model, 3*d_model)

# Break it up (remember to modify the pretrained checkpoint accordingly)

q_proj = lora.Linear(d_model, d_model, r=8)

k_proj = nn.Linear(d_model, d_model)

v_proj = lora.Linear(d_model, d_model, r=8)

# Alternatively, use lora.MergedLinear (recommended)

qkv_proj = lora.MergedLinear(d_model, 3*d_model, r=8, enable_lora=[True, False, True])

Training bias vectors in tandem with LoRA might be a cost-efficient way to squeeze out extra task performance (if you tune the learning rate carefully). While we did not study its effect thoroughly in our paper, we make it easy to try in lora. You can mark some biases as trainable by passing "all" or "lora_only" to bias= when calling mark_only_lora_as_trainable. Remember to pass the corresponding bias= argument to lora_state_dict when saving a checkpoint.

# lora.mark_only_lora_as_trainable(model) # Not training any bias vectors

# Training all bias vectors associated with modules we apply LoRA to

lora.mark_only_lora_as_trainable(model, bias='lora_only')

[...内容已截断,完整版请查看原文或 Wayback 快照]