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. Solo apoyamos a Pytorch por ahora. Vea nuestro artículo para obtener una descripción detallada de Lora.
Lora: adaptación de bajo rango de modelos de idiomas grandes
Edward J. Hu*, Yelong Shen*, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen
Documento: https://arxiv.org/abs/2106.09685
Explicador de video: https://www.youtube.com/watch?v=dhrotoncyze
ACTUALIZACIÓN 2/2023: Lora ahora es compatible con la biblioteca de ajuste fino (PEFT) de vanguardia (PEFT).
Lora reduce el número de parámetros entrenables aprendiendo pares de matrices de rango de decomposión mientras congela los pesos originales. 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 también supera a varios otros métodos de adaptación que incluyen adaptador, ajuste de prefijo y ajuste fino.
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 . Haga clic en los números a continuación para descargar los puntos de control de Roberta y Deberta Lora.
Base Roberta Afinar | Base Roberta Lora | Deberta xxl Afinar | Deberta xxl Lora | ||
---|---|---|---|---|---|
# de parámetros entrenables. | 125m | 0.8m | 1.5b | 4.7m | |
MNLI (M-ACC/MM-ACC) | 87.6 | 87.5 ± .3/86.9 ± .3 | 91.7/ 91.9 | 91.9 ± .1/ 91.9 ± .2 | |
SST2 (ACC) | 94.8 | 95.1 ± .2 | 97.2 | 96.9 ± .2 | |
MRPC (ACC) | 90.2 | 89.7 ± .7 | 92.0 | 92.6 ± .6 | |
Cola (Matthew's Corr) | 63.6 | 63.4 ± 1.2 | 72.0 | 72.4 ± 1.1 | |
Qnli (ACC) | 92.8 | 93.3 ± .3 | 96.0 | 96.0 ± .1 | |
QQP (ACC) | 91.9 | 90.8 ± .1 | 92.7 | 92.9 ± .1 | |
RTE (ACC) | 78.7 | 86.6 ± .7 | 93.9 | 94.9 ± .4 | |
STSB (Pearson/Spearman Corr) | 91.2 | 91.5 ± .2/ 91.3 ± .2 | 92.9 /92.6 | 93.0 ± .2/ 92.9 ± .3 | |
Promedio | 86.40 | 87.24 | 91.06 | 91.32 |
Nota: Todavía necesita el punto de control previamente capacitado original de abrazar la cara para usar los puntos de control de Lora.
Los números de ajuste fino se toman de Liu et al. (2019) y He et al. (2020). Incluimos intervalos de confianza en los resultados de nuestros experimentos. Siga las instrucciones en examples/NLU/
para reproducir nuestros resultados.
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). Evaluamos en E2E NLG Challenge, Dart y Webnlg:
Método | # de parámetros entrenables | E2e (bleu) | Dart (Bleu) | Webnlg (bleu-u/s/a) | |
---|---|---|---|---|---|
GPT-2 M (Tune fino) | 354.92m | 68.2 | 46.0 | 30.4 / 63.2 /47.6 | |
GPT-2 M (adaptador) | 0.37m | 66.3 | 42.4 | 45.1/54.5/50.2 | |
GPT-2 M (prefijo) | 0.35m | 69.7 | 45.7 | 44.1/63.1/54.4 | |
GPT-2 M (Lora) | 0.35m | 70.4 ± .1 | 47.1 ± .2 | 46.7 ± .4/ 62.1 ± .2/ 55.3 ± .2 | |
GPT-2 L (Tune fino) | 774.03m | 68.5 | 46.5 | 41.7 / 64.6 /54.2 | |
GPT-2 L (adaptador) | 0.88m | 69.1 ± .1 | 45.7 ± .1 | 49.8 ± .0/61.1 ± .0/56.0 ± .0 | |
GPT-2 L (prefijo) | 0,77 m | 70.3 | 46.5 | 47.0/64.2/56.4 | |
GPT-2 L (Lora) | 0,77 m | 70.4 ± .1 | 47.5 ± .1 | 48.4 ± .3/ 64.0 ± .3/ 57.0 ± .1 |
Las líneas de base no lora, excepto el adaptador en GPT-2 grande, se toman de Li y Liang (2021). Incluimos intervalos de confianza en los resultados de nuestros experimentos.
Descargue los puntos de control GPT-2 Lora:
Siga las instrucciones en examples/NLG/
para reproducir nuestro resultado.
(El lanzamiento inicial de este repositorio se ha archivado en la rama "Snapshot-15-15-2021")
Hay varios directorios en este repositorio:
loralib
, que debe instalarse para ejecutar los ejemplos que proporcionamos;loralib
en GPT-2, Roberta y Deberta V2 loralib
es simplemente pip install loralib
# Alternatively
# pip install git+https://github.com/microsoft/LoRA
loralib
. Solo apoyamos nn.Linear
, nn.Embedding
y nn.Conv2d
por ahora. 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 )
import loralib as lora
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 :
...
state_dict
que solo contiene parámetros Lora. # ===== Before =====
# torch.save(model.state_dict(), checkpoint_path)
# ===== After =====
torch . save ( lora . lora_state_dict ( model ), checkpoint_path )
load_state_dict
, asegúrese de establecer 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 )
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. Es muy probable que la configuración óptima varíe para diferentes arquitecturas y tareas de modelos.
Alguna implementación del transformador utiliza un solo nn.Linear
para las matrices de proyección para consulta, clave y valor. 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
. Asegúrese de modificar el punto de control en consecuencia si elige romper la capa.
# ===== Before =====
# qkv_proj = nn.Linear(d_model, 3*d_model)
# ===== After =====
# 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 ])
lora
. Puede marcar algunos sesgos como entrenables pasando "todo" o "lora_only" a bias=
al llamar mark_only_lora_as_trainable
. Recuerde pasar el bias=
argumento a lora_state_dict
al guardar un punto de control. # ===== Before =====
# lora.mark_only_lora_as_trainable(model) # Not training any bias vectors
# ===== After =====
# Training all bias vectors associated with modules we apply LoRA to
lora . mark_only_lora_as_trainable ( model , bias = 'lora_only' )
# Alternatively, we can train *all* bias vectors in the model, including LayerNorm biases
lora . mark_only_lora_as_trainable ( model , bias = 'all' )
# When saving a checkpoint, use the same bias= ('all' or 'lora_only')
torch . save ( lora . lora_state_dict ( model , bias = 'all' ), checkpoint_path )
model.eval()
will trigger the merging of LoRA parameters with the corresponding pretrained ones, which eliminates additional latency for subsequent forward passes. Llamar model.train()
nuevamente deshacerá la fusión. Esto se puede deshabilitar pasando merge_weights=False
a Lora Capas. Póngase en contacto con nosotros o publique un problema si tiene alguna pregunta.
Para preguntas relacionadas con el paquete loralib
:
El ejemplo de GPT-2:
El ejemplo de Roberta/Deberta:
We thank in alphabetical order Jianfeng Gao, Jade Huang, Jiayuan Huang, Lisa Xiang Li, Xiaodong Liu, Yabin Liu, Benjamin Van Durme, Luis Vargas, Haoran Wei, Peter Welinder, and Greg Yang for providing valuable feedback.
@inproceedings {
hu2022lora,
title = { Lo{RA}: Low-Rank Adaptation of Large Language Models } ,
author = { Edward J Hu and Yelong Shen and Phillip Wallis and Zeyuan Allen-Zhu and Yuanzhi Li and Shean Wang and Lu Wang and Weizhu Chen } ,
booktitle = { International Conference on Learning Representations } ,
year = { 2022 } ,
url = { https://openreview.net/forum?id=nZeVKeeFYf9 }
}
Este proyecto da la bienvenida a las contribuciones y sugerencias. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. Para más detalles, visite https://cla.opensource.microsoft.com.
When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (eg, status check, comment). Simplemente siga las instrucciones proporcionadas por el bot. Solo necesitará hacer esto una vez en todos los reposos usando nuestro CLA.
Este proyecto ha adoptado el Código de Conducta Open Open Microsoft. Para obtener más información, consulte el Código de Conducta Preguntas frecuentes o comuníquese con [email protected] con cualquier pregunta o comentario adicional.