Home

Awesome

<p align="center" width="100%"><img src="assets/longllama.png" alt="LongLLaMA" style="width: 50%; display: block; margin: auto;"></p>

LongLLaMA: Focused Transformer Training for Context Scaling

<div align="center"> <table> <tr> <th style="font-size: 120%"> >_ 🎓 <a href="https://huggingface.co/syzymon/long_llama_code_7b_instruct">LongLLaMA-Code 7B Instruct</a> 📑🗨 </th> </tr> <tr> <td align="center"> <a href="https://colab.research.google.com/github/CStanKonrad/long_llama/blob/main/long_llama_code_instruct_colab.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg"></a> &nbsp <a href="instruction_fine_tuning/LongLLamaCode7BInstruct.md">Learn more</a> </td> </tr> </table> </div> <div align="center"> <table> <tr> <td align="center"> <span style="font-size:200%">⇧</span> </td> </tr> </table> </div> <div align="center"> <table> <tr> <td align="center"> <span style="font-size:150%">{</span> </td> <td align="center"> <span style="font-size:110%"> <b> <a href="https://huggingface.co/syzymon/long_llama_code_7b" tyle="margin-bottom:30px">LongLLaMA-Code 7B</a> </b> </span> </td> <td align="center"> <span style="font-size:150%">}</span> </td> </tr> </table> <hr> </div> <div align="center"> <table> <tr> <th> <a href="https://huggingface.co/syzymon/long_llama_3b_instruct">LongLLaMA-Instruct-3Bv1.1</a> </th> <th> <a href="https://huggingface.co/syzymon/long_llama_3b_v1_1">LongLLaMA-3Bv1.1</a></th> </tr> <tr> <td align="center"> <a href="https://colab.research.google.com/github/CStanKonrad/long_llama/blob/main/long_llama_instruct_colab.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg"></a> </td> <td align="center"> <a href="https://colab.research.google.com/github/CStanKonrad/long_llama/blob/main/long_llama_colab.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg"></a> </td> </tr> </table> </div> <div align="center">

TLDR | Overview | Usage | LongLLaMA performance | Authors | Citation | License | Acknowledgments

FoT continued pretraining | Instruction tuning

</div>

TLDR

This repository contains the research preview of LongLLaMA, a large language model capable of handling long contexts of 256k tokens or even more.

LongLLaMA is built upon the foundation of OpenLLaMA and fine-tuned using the Focused Transformer (FoT) method. LongLLaMA Code is built upon the foundation of Code Llama. We release a smaller 3B base variant (not instruction tuned) of the LongLLaMA model on a permissive license (Apache 2.0) and inference code supporting longer contexts on Hugging Face. Our model weights can serve as the drop-in replacement of LLaMA in existing implementations (for short context up to 2048 tokens). Additionally, we provide evaluation results and comparisons against the original OpenLLaMA models.
In addition to this, we release code for instruction tuning (PyTorch) and FoT continued pretraining (JAX).

Overview

Base models

Focused Transformer: Contrastive Training for Context Scaling (FoT) presents a simple method for endowing language models with the ability to handle context consisting possibly of millions of tokens while training on significantly shorter input. FoT permits a subset of attention layers to access a memory cache of (key, value) pairs to extend the context length. The distinctive aspect of FoT is its training procedure, drawing from contrastive learning. Specifically, we deliberately expose the memory attention layers to both relevant and irrelevant keys (like negative samples from unrelated documents). This strategy incentivizes the model to differentiate keys connected with semantically diverse values, thereby enhancing their structure. This, in turn, makes it possible to extrapolate the effective context length much beyond what is seen in training.

LongLLaMA is an OpenLLaMA model finetuned with the FoT method, with three layers used for context extension. Crucially, LongLLaMA is able to extrapolate much beyond the context length seen in training: $8k$. E.g., in the passkey retrieval task, it can handle inputs of length $256k$.
LongLLaMA Code is a Code Llama model finetuned with the FoT method.

<div align="center">
LongLLaMA-3BLongLLaMA-3Bv1.1LongLLaMA-Code 7B
Source modelOpenLLaMA-3BOpenLLaMA-3Bv2CodeLLaMA-7b-hf
Source model tokens1T1 T2T + 0.5 T
Fine-tuning tokens10B5B35B
Memory layers6, 12, 186, 12, 188, 16, 24
</div>

FoT continued pretraining

In the fot_continued_pretraining subfolder, we provide the code that can be used to tune LLaMA models with FoT.
This code is written in JAX & Flax and based on EasyLM.

Instruction/Chat tuning

In the instruction_fine_tuning subfolder, we provide the code that was used to create LongLLaMA-Instruct-3Bv1.1, an instruction-tuned version of LongLLaMA-3Bv1.1. We used OpenOrca (instructions) and zetavg/ShareGPT-Processed (chat) datasets for tuning.
This code utilizes PyTorch and Hugging Face trainer.

Inference code

In the src subfolder we provide inference code for FoT models.
The code is written in PyTorch and based on Hugging Face implementation of LLaMA.
The code should support standard Hugging Face API. For more details see the Usage section.

Usage

See also:

Requirements

pip install --upgrade pip
pip install transformers==4.33.2 sentencepiece accelerate

Loading model

import torch
from transformers import LlamaTokenizer, AutoModelForCausalLM

tokenizer = LlamaTokenizer.from_pretrained("syzymon/long_llama_3b_v1_1")
model = AutoModelForCausalLM.from_pretrained("syzymon/long_llama_3b_v1_1", 
                                            torch_dtype=torch.float32, 
                                            trust_remote_code=True)

Input handling and generation

LongLLaMA uses the Hugging Face interface, the long input given to the model will be split into context windows and loaded into the memory cache.

prompt = "My name is Julien and I like to"
input_ids = tokenizer(prompt, return_tensors="pt").input_ids
outputs = model(input_ids=input_ids)

During the model call, one can provide the parameter last_context_length (default $1024$), which specifies the number of tokens left in the last context window. Tuning this parameter can improve generation as the first layers do not have access to memory. See details in How LongLLaMA handles long inputs.

generation_output = model.generate(
    input_ids=input_ids,
    max_new_tokens=256,
    num_beams=1,
    last_context_length=1792,
    do_sample=True,
    temperature=1.0,
)
print(tokenizer.decode(generation_output[0]))

Additional configuration

LongLLaMA has several other parameters:

import torch
from transformers import LlamaTokenizer, AutoModelForCausalLM

tokenizer = LlamaTokenizer.from_pretrained("syzymon/long_llama_3b_v1_1")
model = AutoModelForCausalLM.from_pretrained(
    "syzymon/long_llama_3b_v1_1", torch_dtype=torch.float32, 
    mem_layers=[], 
    mem_dtype='bfloat16',
    trust_remote_code=True,
    mem_attention_grouping=(4, 2048),
)

Drop-in use with LLaMA code

LongLLaMA checkpoints can also be used as a drop-in replacement for LLaMA checkpoints in Hugging Face implementation of LLaMA, but in this case, they will be limited to the original context length of $2048$.

from transformers import LlamaTokenizer, LlamaForCausalLM
import torch

tokenizer = LlamaTokenizer.from_pretrained("syzymon/long_llama_3b_v1_1")
model = LlamaForCausalLM.from_pretrained("syzymon/long_llama_3b_v1_1", torch_dtype=torch.float32)

How LongLLaMA handles long inputs

Inputs over $lctx=2048$ ($lctx=4096$ for LongLLaMA Code) tokens are automatically split into windows $w_1, \ldots, w_m$. The first $m-2$ windows contain $lctx$ tokens each, $w_{m-1}$ has no more than $lctx$ tokens, and $w_m$ contains the number of tokens specified by last_context_length. The model processes the windows one by one extending the memory cache after each. If use_cache is True, then the last window will not be loaded to the memory cache but to the local (generation) cache.

The memory cache stores $(key, value)$ pairs for each head of the specified memory layers mem_layers. In addition to this, it stores attention masks.

If use_cache=True (which is the case in generation), LongLLaMA will use two caches: the memory cache for the specified layers and the local (generation) cache for all layers. When the local cache exceeds $lctx$ elements, its content is moved to the memory cache for the memory layers.

For simplicity, context extension is realized with a memory cache and full attention in this repo. Replacing this simple mechanism with a KNN search over an external database is possible with systems like Faiss. This potentially would enable further context length scaling. We leave this as a future work.

LongLLaMA performance

We present some illustrative examples of LongLLaMA results. Refer to our paper Focused Transformer: Contrastive Training for Context Scaling for more details.

We manage to achieve good performance on the passkey retrieval task from Landmark Attention: Random-Access Infinite Context Length for Transformers. The code for generating the prompt and running the model is located in examples/passkey.py.

<p align="center" width="100%"> <img src="assets/plot_passkey.png" alt="LongLLaMA" style="width: 70%; min-width: 300px; display: block; margin: auto;"> </p>

Our LongLLaMA 3B model also shows improvements when using long context on two downstream tasks, TREC question classification and WebQS question answering.

<div align="center">
Context/DatasetTRECWebQS
$2K$67.021.2
$4K$71.621.4
$6K$72.922.2
$8K$73.322.4
</div>

LongLLaMA retains performance on tasks that do not require long context.

In particular, LongLLaMA-Code 7B improves reasoning (GSM8K) and knowledge (MMLU) due to code fine-tuning:

<p align="center" width="100%"> <img src="assets/full_results.png" alt="LongLLaMA" style="width: 70%; min-width: 300px; display: block; margin: auto;"> </p>

We provide a comparison with OpenLLaMA on lm-evaluation-harness in the zero-shot setting.

<div align="center">
Task/MetricOpenLLaMA-3BLongLLaMA-3B
anli_r1/acc0.330.32
anli_r2/acc0.320.33
anli_r3/acc0.350.35
arc_challenge/acc0.340.34
arc_challenge/acc_norm0.370.37
arc_easy/acc0.690.68
arc_easy/acc_norm0.650.63
boolq/acc0.680.68
hellaswag/acc0.490.48
hellaswag/acc_norm0.670.65
openbookqa/acc0.270.28
openbookqa/acc_norm0.400.38
piqa/acc0.750.73
piqa/acc_norm0.760.75
record/em0.880.87
record/f10.890.87
rte/acc0.580.60
truthfulqa_mc/mc10.220.24
truthfulqa_mc/mc20.350.38
wic/acc0.480.50
winogrande/acc0.620.60
Avg score0.530.53
</div>

Starting with v1.1 models we have decided to use EleutherAI implementation of lm-evaluation-harness with a slight modification, that adds <bos> token at beginning of input sequence. The results are provided in the table below.

<div align="center">
descriptionLongLLaMA-3BOpenLLaMA-3Bv2LongLLaMA-3Bv1.1LongLLaMA-Instruct-3Bv1.1
anli_r1/acc0.320.330.310.33
anli_r2/acc0.330.350.330.35
anli_r3/acc0.350.380.350.38
arc_challenge/acc0.340.330.320.36
arc_challenge/acc_norm0.370.360.360.37
arc_easy/acc0.670.680.680.7
arc_easy/acc_norm0.630.630.630.63
boolq/acc0.680.670.660.77
hellaswag/acc0.480.530.520.52
hellaswag/acc_norm0.650.70.690.68
openbookqa/acc0.280.280.280.28
openbookqa/acc_norm0.380.390.370.41
piqa/acc0.730.770.770.78
piqa/acc_norm0.750.780.770.77
record/em0.870.870.860.85
record/f10.880.880.870.86
rte/acc0.60.530.620.7
truthfulqa_mc/mc10.240.220.210.25
truthfulqa_mc/mc20.380.350.350.4
wic/acc0.50.50.50.54
winogrande/acc0.60.660.630.65
Avg score0.530.530.530.55
</div>

We also provide the results on human-eval. We cut the generated text after either

<div align="center">
OpenLLaMA-3Bv2LongLLaMA-3Bv1.1LongLLaMA-Instruct-3Bv1.1
pass@10.090.120.12
</div>

Authors

Citation

To cite this work please use

@misc{tworkowski2023focused,
      title={Focused Transformer: Contrastive Training for Context Scaling}, 
      author={Szymon Tworkowski and Konrad Staniszewski and Mikołaj Pacek and Yuhuai Wu and Henryk Michalewski and Piotr Miłoś},
      year={2023},
      eprint={2307.03170},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}

License

The source code and base LongLLaMA 3B models checkpoints are licensed under Apache License, Version 2.0.
The instruction/chat tuned models are for research purposes only.
For the LongLLaMA-Code 7B see codellama/CodeLlama-7b-hf license.
LongLLaMA-Code 7B Instruct is LongLLaMA-Code 7B tuned on TIGER-Lab/MathInstruct, OpenOrca and ShareGPT-Processed datasets.
Some of the examples use external code (see headers of files for copyright notices and licenses).

Acknowledgments

We gratefully acknowledge the TPU Research Cloud program, which was instrumental to our research by providing significant computational resources. We are also grateful to Xinyang Geng and Hao Liu for releasing OpenLLaMA checkpoints and the EasyLM library.

Special thanks to Keiran Paster for providing immensely valuable suggestions about the pre-training data for LongLLaMA-Code.

We would like to thank Xiaosong,He for suggestions on how to improve the explanations of cross-batch code.