Unbelievable! Run 70B LLM Inference on a Single 4GB GPU with This NEW Technique

<p>

Large language models require huge amounts of GPU memory. Is it possible to run inference on a single GPU? If so, what is the minimum GPU memory required?</p>
<p><a href="https://cdn-images-1.medium.com/max/3280/1*H7xkrF-6ryxIcUPNwnQ4Xg.png" rel="nofollow"><img alt="" src="https://cdn-images-1.medium.com/max/3280/1*H7xkrF-6ryxIcUPNwnQ4Xg.png"/></a></p>
<p>The 70B large language model has parameter size of 130GB. <strong>Just loading the model into the GPU requires 2 A100 GPUs with 100GB memory each.</strong></p>
<p>During inference, the entire input sequence also needs to be loaded into memory for complex “attention” calculations. The memory requirement of this attention mechanism scales quadratically with the input length. On top of the 130GB model size, a lot more memory is needed.</p>
<p>So what techniques can save so much memory and enable inference on a single 4GB GPU?</p>
<p>Note that here the memory optimization techniques <strong>do not require any model compression like quantization, distillation, pruning that would sacrifice model performance.</strong></p>
<p>Today <strong>we will explain the key techniques for extreme memory optimization of large models.</strong></p>
<p>At the end of the article we also shared the open source library to achieve this with a few lines of codes!</p>
<p><strong>01</strong></p>
<p><strong>Layer-wise Inference</strong></p>
<p>The most critical technique is layer-wise inference. This is essentially the basic <strong>divide and conquer approach</strong> in computer science.</p>
<p>Let’s first look at the architecture of large language models. Today’s large language models all adopt the Multi-head self-attention structure proposed in Google’s paper “Attention is all you need”. This is what people later call the Transformer structure.</p>
<p><a href="https://cdn-images-1.medium.com/max/2000/0*wg1TK6QDogxId8Sv" rel="nofollow"><img alt="" src="https://cdn-images-1.medium.com/max/2000/0*wg1TK6QDogxId8Sv"/></a></p>
<p>The large language model first has an embedding projection layer. After that there are 80 completely identical transformer layers. Finally there is a normalization and fully connected layer to predict the token ID probabilities.</p>
<p>During inference, layers are executed sequentially. The output of the previous layer is the input to the next. Only one layer executes at a time.</p>
<p>Therefore, it is completely unnecessary to keep all layers in GPU memory. <strong>We can load whichever layer is needed from disk when executing that layer, do all the calculations, and then completely free the memory after.</strong></p>
<p>This way, the GPU memory required per layer is only about the parameter size of one transformer layer, 1/80 of the full model, around 1.6GB.</p>
<p>In addition, some output caches are also stored in GPU memory, the largest being the KV cache to avoid repeated computations.</p>
<p>A simple calculation, for the 70B model this KV cache size is about:</p>
<p>2 * input_length * num_layers * num_heads * vector_dim * 4</p>
<p>With input length 100, this cache = 2 * 100 * 80 * 8 * 128 * 4 = 30MB GPU memory.</p>
<p><strong>According to our monitoring, the entire inference process uses less than 4GB GPU memory!</strong></p>
<p><strong>02</strong></p>
<p><strong>Single Layer Optimization — Flash Attention</strong></p>
<p>Flash attention is perhaps one of the most important and critical optimizations in the development of large language models today.</p>
<p>All the various large language models use essentially the same underlying code, with flash attention being the biggest improvement.</p>
<p>The idea of flash attention optimization is not entirely novel though, we have to mention another paper “Self-attention Does Not Need O(n²) Memory”.</p>
<p>Originally self attention requires O(n²) memory (n being sequence length).</p>
<p>This paper proposes that we don’t actually need to keep the O(n²) intermediate results. We can compute them sequentially, continuously update one intermediate result and discard everything else. This reduces the memory complexity to O(logn).</p>
<p>Flash attention is similar in essence, with slightly higher memory complexity O(n), but <strong>flash attention deeply optimizes cuda memory access to achieve multi-fold speedups for inference and training.</strong></p>
<p><a href="https://cdn-images-1.medium.com/max/2000/0*Ah_AxED31aIT2cFz" rel="nofollow"><img alt="" src="https://cdn-images-1.medium.com/max/2000/0*Ah_AxED31aIT2cFz"/></a></p>
<p>As the figure shows, originally self attention computes and stores O(n²) intermediate results. Flash attention splits the computation into many small blocks, computing block by block and reducing memory to the size of one block.</p>
<p><strong>03</strong></p>
<p><strong>Model File Sharding</strong></p>
<p>The original model file is usually sharded into multiple chunks, typically 10GB each.</p>
<p>Our execution processes layer by layer. Each layer is only 1.6GB. If we load based on the original 10GB shards, every layer execution will require reloading the entire 10GB file but only using 1.6GB.</p>
<p>This process wastes a lot of memory for loading and disk reading. Disk reading speed is actually the slowest bottleneck in the whole inference process, so we want to minimize it as much as possible.</p>
<p>Therefore, we first <strong>pre-process the original HuggingFace model file and shard it by layers</strong>.</p>
<p>For storage we use safetensor technology (<a href="https://github.com/huggingface/safetensors" rel="nofollow">https://github.com/huggingface/safetensors</a>).</p>
<p><strong>Safetensor ensures the storage format and in-memory format match closely, and uses memory mapping for loading to maximize speed.</strong></p>
<p><strong>04</strong></p>
<p><strong>Meta Device</strong></p>
<p>In implementation we use the meta device feature provided by HuggingFace Accelerate (<a href="https://huggingface.co/docs/accelerate/usage_guides/big_modeling">https://huggingface.co/docs/accelerate/usage\_guides/big\_modeling</a>).</p>
<p>Meta device is a <strong>virtual device</strong> designed specifically for running ultra large models. <strong>When you load a model via meta device, the model data is not actually read in, only the code is loaded. Memory usage is 0.</strong></p>
<p>You can dynamically transfer parts of the model from meta device to a real device like CPU or GPU during execution. Only then is it actually loaded into memory.</p>
<p>Using init_empty_weights() allows model loading via meta device.</p>
<pre><code>from accelerate import init_empty_weights
with init_empty_weights():
    my_model = ModelClass(...)
</code></pre>
<p><strong>05</strong></p>
<p><strong>Open Source Library</strong></p>
<p>We open sourced all the code — AirLLM. Allows you to achieve this with a few lines of code.</p>
<p><strong>It can be found in the Anima github: <a href="https://github.com/lyogavin/Anima/tree/main/air_llm" rel="nofollow">**https://github.com/lyogavin/Anima/tree/main/air_llm</a></strong>.**</p>
<p>Usage is very simple. First install the package:</p>
<pre><code>pip install airllm
</code></pre>
<p>Then layered inference can be performed like a normal Transformer model:</p>
<pre><code>from airllm import AirLLMLlama2

MAX_LENGTH = 128
# could use hugging face model repo id:
model = AirLLMLlama2("garage-bAInd/Platypus2-70B-instruct")

# or use model's local path...
#model = AirLLMLlama2("/home/ubuntu/.cache/huggingface/hub/models--garage-bAInd--Platypus2-70B-instruct/snapshots/b585e74bcaae02e52665d9ac6d23f4d0dbc81a0f")

input_text = [
        'What is the capital of United States?',
    ]

input_tokens = model.tokenizer(input_text,
    return_tensors="pt", 
    return_attention_mask=False, 
    truncation=True, 
    max_length=MAX_LENGTH, 
    padding=True)
           
generation_output = model.generate(
    input_tokens['input_ids'].cuda(), 
    max_new_tokens=20,
    use_cache=True,
    return_dict_in_generate=True)

output = model.tokenizer.decode(generation_output.sequences[0])

print(output)
</code></pre>
<p>We have tested this code on a 16GB Nvidia T4 GPU. The entire inference process <strong>uses less than 4GB GPU memory</strong>.</p>
<p>Note that lower end GPUs like T4 will be quite slow for inference. Not very suitable for interactive scenarios like chatbots. More suited for some offline data analytics like RAG, PDF analysis etc.</p>
<p>Currently only Llam2 based models are supported. <strong>Leave a comment if you need support for other models!</strong></p>
<p><strong>06</strong></p>
<p><strong>Can 70B Training Fit on a Single GPU?</strong></p>
<p>While inference can be optimized with layering, can training work similarly on a single GPU?</p>
<p>Inference only needs the output of the previous layer when executing the next transformer layer, so layered execution with limited data is possible.</p>
<p><strong>Training requires more data. The training process first computes the forward propagation to get the output of every layer and tensor. Then does backpropagation to compute the gradient of every tensor.</strong></p>
<p><strong>Gradient calculation needs to save the results of previous forward layers, so layered execution does not reduce memory.</strong></p>
<p>There are some other techniques like gradient checkpointing that can achieve similar effects.</p>
<p><strong>If you are interested in how gradient checkpointing can significantly reduce training memory requirements, leave a comment!</strong></p>
<p><strong>07</strong></p>
<p>Our code references a lot from <a href="https://www.kaggle.com/simjeg" rel="nofollow">SIMJEG</a>’s implementation on Kaggle: <a href="https://www.kaggle.com/code/simjeg/platypus2-70b-with-wikipedia-rag/notebook" rel="nofollow">https://www.kaggle.com/code/simjeg/platypus2-70b-with-wikipedia-rag/notebook</a>. Shout out to the awesome Kaggle community for their contributions!</p>
<p><strong>We will continue open sourcing the latest and most effective new methods and advances in AI, contributing to the open source community. Please follow us.</strong></p>
