Home

Awesome

<p align="center" width="100%"> <img src="imgs/LongAlpaca.png" alt="Stanford-Alpaca" style="width: 100%; min-width: 300px; display: block; margin: auto;"> </p>

LongLoRA and LongAlpaca for Long-context LLMs

Huggingface Models Data Paper

Code License Data License Weight License

TABLE OF CONTENTS

  1. News
  2. Highlights
  3. How to contribute
  4. Requirements
  5. Installation and quick guide
  6. LongAlpaca Data
  7. Models
  8. Training
  9. Evaluation
  10. Demo
  11. Streaming Inference
  12. Data Generation via Pdf2Text
  13. Examples
  14. Citation
  15. Acknowledgement
  16. License

News

LongLoRA: Efficient Fine-tuning of Long-Context Large Language Models [Paper] <br /> Yukang Chen, Shengju Qian, Haotian Tang, Xin Lai, Zhijian Liu, Song Han, Jiaya Jia<br />

Highlights

  1. In LongLoRA approach, The proposed shifted short attention is easy to implement, compatible with Flash-Attention, and is not required during inference.
  2. We released all our models, including models from 7B to 70B, context length from 8k to 100k, including LLaMA2-LongLoRA-7B-100k, LLaMA2-LongLoRA-13B-64k, and LLaMA2-LongLoRA-70B-32k.
  3. We built up a long-context instruction-following dataset, LongAlpaca-12k. We released the corresponding LongAlpaca-7B, LongAlpaca-13B and LongAlpaca-70B models. To our best knowledge, this is the first open-sourced long-context 70B model.

How to Contribute

Usage Requirements

To download and use the pre-trained weights you will need:

  1. Hugging Face (HF) account with valid email. Note, the email used for HF must alse be used for the license agreement.
  2. Accept the Meta license and acceptable use policy

Installation and Quick Guide

To install and run the application:

  1. Fork this repo on github
  2. Clone the repository on your local machine, using git clone and pasting the url of this project.
  3. Run the following code:
pip install -r requirements.txt
pip install flash-attn --no-build-isolation
  1. Use either a Released model or Fine tune a model to fit your preferences.
  2. Test your model by chat.
  3. Deploy your own demo.

LongAlpaca Data

LongAlpaca-12k contains 9k long QA data that we collected and 3k short QA sampled from the original Alpaca data. This is to avoid the case that the model might degrade at short instruction following. The data we collect contains various types and amounts as the following figure.

<p align="center" width="100%"> <img src="imgs/data-distribution-in-longalpaca12k.png" alt="Stanford-Alpaca" style="width: 60%; min-width: 300px; display: block; margin: auto;"> </p>
DataShort QALong QATotalDownload
LongAlpaca-12k3k9k12kLink

Following the original Alpaca format, our Long QA data uses the following prompts for fine-tuning:

We did not use the input format in the Alpaca format for simplicity.

Models

Models with supervised fine-tuning

ModelSizeContextTrainLink
LongAlpaca-7B7B32768Full FTModel
LongAlpaca-13B13B32768Full FTModel
LongAlpaca-70B70B32768LoRA+Model (LoRA-weight)

Models with context extension via fully fine-tuning

ModelSizeContextTrainLink
Llama-2-7b-longlora-8k-ft7B8192Full FTModel
Llama-2-7b-longlora-16k-ft7B16384Full FTModel
Llama-2-7b-longlora-32k-ft7B32768Full FTModel
Llama-2-7b-longlora-100k-ft7B100000Full FTModel
Llama-2-13b-longlora-8k-ft13B8192Full FTModel
Llama-2-13b-longlora-16k-ft13B16384Full FTModel
Llama-2-13b-longlora-32k-ft13B32768Full FTModel

Models with context extension via improved LoRA fine-tuning

ModelSizeContextTrainLink
Llama-2-7b-longlora-8k7B8192LoRA+LoRA-weight
Llama-2-7b-longlora-16k7B16384LoRA+LoRA-weight
Llama-2-7b-longlora-32k7B32768LoRA+LoRA-weight
Llama-2-13b-longlora-8k13B8192LoRA+LoRA-weight
Llama-2-13b-longlora-16k13B16384LoRA+LoRA-weight
Llama-2-13b-longlora-32k13B32768LoRA+LoRA-weight
Llama-2-13b-longlora-64k13B65536LoRA+LoRA-weight
Llama-2-70b-longlora-32k70B32768LoRA+LoRA-weight
Llama-2-70b-chat-longlora-32k70B32768LoRA+LoRA-weight

Training

Pre-trained weights

We use LLaMA2 models as the pre-trained weights and fine-tune them to long context window sizes. Download based on your choices.

Pre-trained weights
Llama-2-7b-hf
Llama-2-13b-hf
Llama-2-70b-hf
Llama-2-7b-chat-hf
Llama-2-13b-chat-hf
Llama-2-70b-chat-hf

This project also supports GPTNeoX models as the base model architecture. Some candidate pre-trained weights may include GPT-NeoX-20B, Polyglot-ko-12.8B and other variants.

Fine-tuning

torchrun --nproc_per_node=8 fine-tune.py  \
        --model_name_or_path path_to/Llama-2-7b-hf \
        --bf16 True \
        --output_dir path_to_saving_checkpoints       \
        --cache_dir path_to_cache \
        --model_max_length 8192 \
        --use_flash_attn True \
        --low_rank_training False \
        --num_train_epochs 1  \
        --per_device_train_batch_size 1     \
        --per_device_eval_batch_size 2     \
        --gradient_accumulation_steps 8     \
        --evaluation_strategy "no"     \
        --save_strategy "steps"     \
        --save_steps 1000     \
        --save_total_limit 2     \
        --learning_rate 2e-5     \
        --weight_decay 0.0     \
        --warmup_steps 20     \
        --lr_scheduler_type "constant_with_warmup"     \
        --logging_steps 1     \
        --deepspeed "ds_configs/stage2.json" \
        --tf32 True \
        --max_steps 1000
cd path_to_saving_checkpoints && python zero_to_fp32.py . pytorch_model.bin

Note that the path_to_saving_checkpoints might be the global_step directory, which depends on the deepspeed versions.

Supervised Fine-tuning

torchrun --nproc_per_node=8 supervised-fine-tune.py  \
        --model_name_or_path path_to_Llama2_chat_models \
        --bf16 True \
        --output_dir path_to_saving_checkpoints       \
        --model_max_length 16384 \
        --use_flash_attn True \
        --data_path LongAlpaca-16k-length.json \
        --low_rank_training True \
        --num_train_epochs 5  \
        --per_device_train_batch_size 1     \
        --per_device_eval_batch_size 2     \
        --gradient_accumulation_steps 8     \
        --evaluation_strategy "no"     \
        --save_strategy "steps"     \
        --save_steps 98     \
        --save_total_limit 2     \
        --learning_rate 2e-5     \
        --weight_decay 0.0     \
        --warmup_steps 20     \
        --lr_scheduler_type "constant_with_warmup"     \
        --logging_steps 1     \
        --deepspeed "ds_configs/stage2.json" \
        --tf32 True

Get trainable weights in low-rank training

In low-rank training, we set embedding and normalization layers as trainable. Please use the following line to extract the trainable weights trainable_params.bin from pytorch_model.bin

python3 get_trainable_weights.py --checkpoint_path path_to_saving_checkpoints --trainable_params "embed,norm"

Merge LoRA Weight

Merge the LoRA weights of pytorch_model.bin and trainable parameters trainable_params.bin, save the resulting model into your desired path in the Hugging Face format:

python3 merge_lora_weights_and_save_hf_model.py \
        --base_model path_to/Llama-2-7b-hf \
        --peft_model path_to_saving_checkpoints \
        --context_size 8192 \
        --save_path path_to_saving_merged_model

For example,

python3 merge_lora_weights_and_save_hf_model.py \
        --base_model /dataset/pretrained-models/Llama-2-7b-hf \
        --peft_model /dataset/yukangchen/hf_models/lora-models/Llama-2-7b-longlora-8k \
        --context_size 8192 \
        --save_path /dataset/yukangchen/models/Llama-2-7b-longlora-8k-merged

Evaluation

Perplexity Validation

To evaluate a model that is trained in the low-rank setting, please set both base_model and peft_model. base_model is the pre-trained weight. peft_model is the path to the saved checkpoint, which should contain trainable_params.bin, adapter_model.bin and adapter_config.json. For example,

python3 eval.py --seq_len 8192 --context_size 8192 --batch_size 1 --base_model path_to/Llama-2-7b-hf --peft_model path_to_saving_checkpoints --data_path pg19/test.bin

Or evaluate with multiple GPUs as follows.

torchrun --nproc_per_node=auto eval_distributed.py --seq_len 8192 --context_size 8192 --batch_size 1 --base_model path_to/Llama-2-7b-hf --peft_model path_to_saving_checkpoints --data_path pg19/test.bin

To evaluate a model that is fully fine-tuned, you only need to set base_model as the path to the saved checkpoint, which should contain pytorch_model.bin and config.json. peft_model should be ignored.

python3 eval.py --seq_len 8192 --context_size 8192 --batch_size 1 --base_model path_to_saving_checkpoints --data_path pg19/test.bin

Or evaluate with multiple GPUs as follows.

torchrun --nproc_per_node=auto eval_distributed.py --seq_len 8192 --context_size 8192 --batch_size 1 --base_model path_to_saving_checkpoints --data_path pg19/test.bin
DatasetSplitLink
PG19validationpg19/validation.bin
PG19testpg19/test.bin
Proof-piletestproof-pile/test_sampled_data.bin

Passkey Retrieval

We provide a manner to test the passkey retrieval accuracy. For example,

python3 passkey_retrivial.py \
        --context_size 32768 \
        --base_model path_to/Llama-2-7b-longlora-32k \
        --max_tokens 32768 \
        --interval 1000

Demo

Local Inference

To chat with LongAlpaca models,

python3 inference.py  \
        --base_model path_to_model \
        --question $question \
        --context_size $context_length \
        --max_gen_len $max_gen_len \
        --flash_attn True \
        --material $material_content

To ask a question related to a book:

python3 inference.py  \
        --base_model /data/models/LongAlpaca-13B \
        --question "Why doesn't Professor Snape seem to like Harry?" \
        --context_size 32768 \
        --max_gen_len 512 \
        --flash_attn True \
        --material "materials/Harry Potter and the Philosophers Stone_section2.txt"

To ask a question related to a paper:

python3 inference.py  \
        --base_model /data/models/LongAlpaca-13B \
        --question "What are the main contributions and novelties of this work?" \
        --context_size 32768 \
        --max_gen_len 512 \
        --flash_attn True \
        --material "materials/paper1.txt"

Online Demo

To deploy your own demo run

python3 demo.py  \
	--base_model path_to_model \
	--context_size $context_size \
	--max_gen_len $max_gen_len \
	--flash_attn True

Example

python3 demo.py  \
	--base_model /data/models/LongAlpaca-13B \
	--context_size 32768 \
	--max_gen_len 512 \
	--flash_attn True

Streaming Inference

We support the inference of LongAlpaca models with StreamingLLM. This increases the context-length of the multi-round dialogue in StreamingLLM. Here is an example,

python run_streaming_llama_longalpaca.py \
	----enable_streaming \
	--test_filepath outputs_stream.json \
	--use_flash_attn True \
	--recent_size 32768

Data Generation via Pdf2text

During our dataset collection, we convert paper and books from pdf to text. The conversion quality has a large influence on the final model quality. We think that this step is non-trivial. We release the tool for the pdf2txt conversion, in the folder pdf2txt. It is built upon pdf2image, easyocr, ditod and detectron2. Please refer to the README.md in pdf2txt for more details.

Examples

<p align="center"> <img src="imgs/paper-improvements.png" width="100%"> </p> <p align="center"> <img src="imgs/paper-review.png" width="100%"> </p> <p align="center"> <img src="imgs/paper-style-compare-cvpr-iclr.png" width="100%"> </p> <p align="center"> <img src="imgs/demo-compare-journeytothewest.png" width="100%"> </p> <p align="center"> <img src="imgs/demo-compare-harrypotter.png" width="100%"> </p> <p align="center"> <img src="imgs/demo-compare-threebody.png" width="100%"> </p> <p align="center"> <img src="imgs/economy-comparison.png" width="100%"> </p> <p align="center"> <img src="imgs/economy-prediction.png" width="100%"> </p>

Citation

If you find this project useful in your research, please consider citing:

@inproceedings{longlora,
  author       = {Yukang Chen and Shengju Qian and Haotian Tang and Xin Lai and Zhijian Liu and Song Han and Jiaya Jia},
  title        = {LongLoRA: Efficient Fine-tuning of Long-Context Large Language Models},
  booktitle    = {The International Conference on Learning Representations (ICLR)},
  year         = {2024},
}
@misc{long-alpaca,
  author = {Yukang Chen and Shaozuo Yu and Shengju Qian and Haotian Tang and Xin Lai and Zhijian Liu and Song Han and Jiaya Jia},
  title = {Long Alpaca: Long-context Instruction-following models},
  year = {2023},
  publisher = {GitHub},
  journal = {GitHub repository},
  howpublished = {\url{https://github.com/dvlab-research/LongLoRA}},
}

Acknowledgement

License