• Stars
    star
    2,563
  • Rank 17,891 (Top 0.4 %)
  • Language
    Python
  • License
    Apache License 2.0
  • Created about 1 year ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Code and documents of LongLoRA and LongAlpaca (ICLR 2024 Oral)

Stanford-Alpaca

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]
Yukang Chen, Shengju Qian, Haotian Tang, Xin Lai, Zhijian Liu, Song Han, Jiaya Jia

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

  • Make sure to have git installed.
  • Create your own fork of the project.
  • Clone the repository on your local machine, using git clone and pasting the url of this project.
  • Read both the Requirements and Installation and Quick Guide sections below.
  • Commit and push your changes.
  • Make a pull request when finished modifying the project.

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.

Stanford-Alpaca

Data Short QA Long QA Total Download
LongAlpaca-12k 3k 9k 12k Link

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

  • instruction: str, describes the task the model should perform. For example, to answer a question after reading a book section or paper. We vary the contents and questions to make instructions diverse.
  • output: str, the answer to the instruction.

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

Models

Models with supervised fine-tuning

Model Size Context Train Link
LongAlpaca-7B 7B 32768 Full FT Model
LongAlpaca-13B 13B 32768 Full FT Model
LongAlpaca-70B 70B 32768 LoRA+ Model (LoRA-weight)

Models with context extension via fully fine-tuning

Model Size Context Train Link
Llama-2-7b-longlora-8k-ft 7B 8192 Full FT Model
Llama-2-7b-longlora-16k-ft 7B 16384 Full FT Model
Llama-2-7b-longlora-32k-ft 7B 32768 Full FT Model
Llama-2-7b-longlora-100k-ft 7B 100000 Full FT Model
Llama-2-13b-longlora-8k-ft 13B 8192 Full FT Model
Llama-2-13b-longlora-16k-ft 13B 16384 Full FT Model
Llama-2-13b-longlora-32k-ft 13B 32768 Full FT Model

Models with context extension via improved LoRA fine-tuning

Model Size Context Train Link
Llama-2-7b-longlora-8k 7B 8192 LoRA+ LoRA-weight
Llama-2-7b-longlora-16k 7B 16384 LoRA+ LoRA-weight
Llama-2-7b-longlora-32k 7B 32768 LoRA+ LoRA-weight
Llama-2-13b-longlora-8k 13B 8192 LoRA+ LoRA-weight
Llama-2-13b-longlora-16k 13B 16384 LoRA+ LoRA-weight
Llama-2-13b-longlora-32k 13B 32768 LoRA+ LoRA-weight
Llama-2-13b-longlora-64k 13B 65536 LoRA+ LoRA-weight
Llama-2-70b-longlora-32k 70B 32768 LoRA+ LoRA-weight
Llama-2-70b-chat-longlora-32k 70B 32768 LoRA+ 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
  • Please remember to change path_to/Llama-2-7b-hf, path_to_saving_checkpoints, path_to_cache to your own directory.
  • Note that you can change model_max_length to other values.
  • You could change ds_configs/stage2.json to ds_configs/stage3.json if you want.
  • Please set use_flash_attn as False if you use V100 machines or do not install flash attention.
  • You can set low_rank_training as False if you want to use fully fine-tuning. It will cost more GPU memory and slower, but the performance will be a bit better.
  • When training is finished, to get the full model weight:
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
  • There is no need to make supervised fine-tuning upon the fine-tuned context extended models. It is all right to directly use base model as Llama2-chat models, as the amount of long instruction following data is enough for SFT.
  • Our long instruction following data can be found in LongAlpaca-12k.json.
  • Note that supervised-fine-tune.py can be replaced by supervised-fine-tune-qlora.py if you want to try 4-bit quantized fine-tuning for further GPU memory reduction. This follows QLoRA.
  • If you meet issue for saving pytorch_model.bin after the qlora sft, please refer to this issue.

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
  • Note that --seq_len is to set the sequence length for evaluation. --context_size is to set the context length of the model during fine-tuning. --seq_len should not be larger than --context_size.

  • We have already tokenized the validation and test splits of PG19 and proof-pile dataset into pg19/validation.bin, pg19/test.bin, and proof-pile/test_sampled_data.bin, with the tokenizer of LLaMA. proof-pile/test_sampled_data.bin contains 128 documents that are randomly sampled from the total proof-pile test split. For each document, it has at least 32768 tokens. We also release the sampled ids in proof-pile/test_sampled_ids.bin. You can download them from the links below.

Dataset Split Link
PG19 validation pg19/validation.bin
PG19 test pg19/test.bin
Proof-pile test proof-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
  • Note that the context_size is the context length during fine-tuning.
  • max_tokens is maximum length for the document in passkey retrieval evaluation.
  • interval is the interval during the document length increasing. It is a rough number because the document increases by sentences.

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"
  • Note that inference.py can be replaced by inference-qlora.py if you want to try 4-bit quantized fine-tuning for further GPU memory reduction. This follows QLoRA.

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
  • Note that flash_attn=True will make the generation slow but save much GPU memory.

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
  • Note that please use a smaller recent_size if you meet OOM issues, for example 8192.
  • test_filepath is the json file that contains prompts for inference. We provide an example file outputs_stream.json, which is a subset of LongAlpaca-12k. You can replace it to your own questions.

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

Citation

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

@article{longlora,
  title={LongLoRA: Efficient Fine-tuning of Long-Context Large Language Models},
  author={Yukang Chen and Shengju Qian and Haotian Tang and Xin Lai and Zhijian Liu and Song Han and Jiaya Jia},
  journal={arXiv:2309.12307},
  year={2023}
}
@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

  • LongLoRA is licensed under the Apache License 2.0. This means that it requires the preservation of copyright and license notices.
  • Data and weights are under CC-BY-NC 4.0 License. They are licensed for research use only, and allowed only non-commercial. Models trained using the dataset should not be used outside of research purposes.

More Repositories

1

MGM

Official repo for "Mini-Gemini: Mining the Potential of Multi-modality Vision Language Models"
Python
3,111
star
2

LISA

Project Page for "LISA: Reasoning Segmentation via Large Language Model"
Python
1,680
star
3

VoxelNeXt

VoxelNeXt: Fully Sparse VoxelNet for 3D Object Detection and Tracking (CVPR 2023)
Python
692
star
4

LLaMA-VID

LLaMA-VID: An Image is Worth 2 Tokens in Large Language Models (ECCV 2024)
Python
656
star
5

DeepUPE

Underexposed Photo Enhancement Using Deep Illumination Estimation
Python
566
star
6

3D-Box-Segment-Anything

We extend Segment Anything to 3D perception by combining it with VoxelNeXt.
Jupyter Notebook
524
star
7

LLMGA

This project is the official implementation of 'LLMGA: Multimodal Large Language Model based Generation Assistant', ECCV2024
Python
424
star
8

ControlNeXt

Controllable video and image Generation, SVD, Animate Anyone, ControlNet, LoRA
Python
417
star
9

PanopticFCN

Fully Convolutional Networks for Panoptic Segmentation (CVPR2021 Oral)
Python
391
star
10

PointGroup

PointGroup: Dual-Set Point Grouping for 3D Instance Segmentation
Python
376
star
11

3DSSD

3DSSD: Point-based 3D Single Stage Object Detector (CVPR 2020)
Python
375
star
12

Video-P2P

Video-P2P: Video Editing with Cross-attention Control
Python
365
star
13

FocalsConv

Focal Sparse Convolutional Networks for 3D Object Detection (CVPR 2022, Oral)
Python
364
star
14

Stratified-Transformer

Stratified Transformer for 3D Point Cloud Segmentation (CVPR 2022)
Python
362
star
15

DSGN

DSGN: Deep Stereo Geometry Network for 3D Object Detection (CVPR 2020)
Python
324
star
16

PFENet

PFENet: Prior Guided Feature Enrichment Network for Few-shot Segmentation (TPAMI).
Python
307
star
17

SphereFormer

The official implementation for "Spherical Transformer for LiDAR-based 3D Recognition" (CVPR 2023).
Python
300
star
18

GridMask

Python
281
star
19

ReviewKD

Distilling Knowledge via Knowledge Review, CVPR 2021
Python
249
star
20

Parametric-Contrastive-Learning

Parametric Contrastive Learning (ICCV2021) & GPaCo (TPAMI 2023)
Python
237
star
21

Step-DPO

Implementation for "Step-DPO: Step-wise Preference Optimization for Long-chain Reasoning of LLMs"
Python
232
star
22

Simple-SR

Include MuCAN, LAPAR, etc.
Python
224
star
23

UVTR

Unifying Voxel-based Representation with Transformer for 3D Object Detection (NeurIPS 2022)
Python
224
star
24

Facelet_Bank

Facelet-Bank for Fast Portrait Manipulation (pytorch)
Python
208
star
25

SA-AutoAug

Scale-aware Automatic Augmentation for Object Detection (CVPR 2021)
Python
196
star
26

LargeKernel3D

LargeKernel3D: Scaling up Kernels in 3D Sparse CNNs (CVPR 2023)
Python
189
star
27

SNR-Aware-Low-Light-Enhance

This is the official implementation for the paper "SNR-aware low-light image enhancement" in CVPR2022
Python
160
star
28

MASA-SR

MASA-SR: Matching Acceleration and Spatial Adaptation for Reference-Based Image Super-Resolution (CVPR2021)
Python
158
star
29

ECCV22-P3AFormer-Tracking-Objects-as-Pixel-wise-Distributions

The official code for our ECCV22 oral paper: tracking objects as pixel-wise distributions.
Python
158
star
30

Context-Aware-Consistency

Semi-supervised Semantic Segmentation with Directional Context-aware Consistency (CVPR 2021)
Python
155
star
31

SparseTransformer

A fast and memory-efficient libarary for sparse transformer with varying token numbers (e.g., 3D point cloud).
Python
153
star
32

spconv-plus

Python
152
star
33

EfficientNeRF

The official code for "Efficient Neural Radiance Fields" in CVPR2022.
Python
152
star
34

MiSLAS

Improving Calibration for Long-Tailed Recognition (CVPR2021)
Python
144
star
35

RIVAL

[NeurIPS 2023 Spotlight] Real-World Image Variation by Aligning Diffusion Inversion Chain
Python
143
star
36

MOOD

Official PyTorch implementation of MOOD series: (1) MOODv1: Rethinking Out-of-distributionDetection: Masked Image Modeling Is All You Need. (2) MOODv2: Masked Image Modeling for Out-of-Distribution Detection.
Python
133
star
37

outpainting_srn

Wide-Context Semantic Image Extrapolation, CVPR2019
Python
131
star
38

MSAD

Multi-Scale Aligned Distillation for Low-Resolution Detection (CVPR2021)
Python
127
star
39

DeepVision3D

DeepVision3D is an open source toolbox for point-cloud understanding.
Python
119
star
40

Ref-NPR

[CVPR 2023] Ref-NPR: Reference-Based Non-PhotoRealistic Radiance Fields
Python
119
star
41

VFIformer

Video Frame Interpolation with Transformer (CVPR2022)
Python
112
star
42

Prompt-Highlighter

[CVPR 2024] Prompt Highlighter: Interactive Control for Multi-Modal LLMs
Python
112
star
43

VFF

Voxel Field Fusion for 3D Object Detection (CVPR2022)
Python
95
star
44

SMR

Self-Supervised 3D Mesh Reconstruction from Single Images (CVPR2021)
Python
91
star
45

SCGAN

The implementation of 'Image synthesis via semantic composition', ICCV2021.
Python
81
star
46

Imbalanced-Learning

Imbalanced learning tool for imbalanced recognition and segmentation
Python
79
star
47

JigsawClustering

This is the code for CVPR 2021 oral paper: Jigsaw Clustering for Unsupervised Visual Representation Learning
Python
78
star
48

AttenNorm

Attentive Normalization for Conditional Image Generation
Python
71
star
49

GFS-Seg

The official implementation of Generalized Few-shot Semantic Segmentation (CVPR 2022)
Python
63
star
50

Mask-Attention-Free-Transformer

Official Implementation for "Mask-Attention-Free Transformer for 3D Instance Segmentation"
Python
59
star
51

MoTCoder

This is the official code repository of MoTCoder: Elevating Large Language Models with Modular of Thought for Challenging Programming Tasks.
Python
58
star
52

SDSD

Seeing Dynamic Scene in the Dark: High-Quality Video Dataset with Mechatronic Alignment (ICCV2021)
Python
48
star
53

GroupContrast

[CVPR 2024] GroupContrast: Semantic-aware Self-supervised Representation Learning for 3D Understanding
42
star
54

ProposeReduce

Video Instance Segmentation with a Propose-Reduce Paradigm (ICCV 2021)
Python
41
star
55

Robust-Semantic-Segmentation

Dynamic Divide-and-Conquer Adversarial Training for Robust Semantic Segmentation (ICCV2021)
Python
40
star
56

Mr-Ben

This is the repo for our paper "Mr-Ben: A Comprehensive Meta-Reasoning Benchmark for Large Language Models"
Python
38
star
57

BAL

BAL: Balancing Diversity and Novelty for Active Learning - Official Pytorch Implementation
Python
38
star
58

TriVol

The official code of TriVol in CVPR-2023
Python
37
star
59

MR-GSM8K

Challenge LLMs to Reason About Reasoning: A Benchmark to Unveil Cognitive Depth in LLMs
Python
37
star
60

DecoupleNet

Official implementation for our ECCV 2022 paper "DecoupleNet: Decoupled Network for Domain Adaptive Semantic Segmentation"
Python
36
star
61

Dsig

Deep Structured Instance Graph for Distilling Object Detectors (ICCV 2021)
Python
35
star
62

LBGAT

Learnable Boundary Guided Adversarial Training (ICCV2021)
Python
33
star
63

Q-LLM

This is the official repo of "QuickLLaMA: Query-aware Inference Acceleration for Large Language Models"
Python
31
star
64

AGSS-VOS

AGSS-VOS: Attention Guided Single-Shot Video Object Segmentation
Python
20
star
65

MAT

MAT: Mask-Aware Transformer for Large Hole Image Inpainting
Python
16
star
66

MSN

Memory Selection Network for Video Propagation (ECCV 2020)
Python
6
star
67

APD

Python
5
star
68

Point2Pix

The official code of Point2pix in CVPR-2023
2
star
69

TagCLIP

Python
2
star