File size: 8,426 Bytes
51daf1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
---
license: other
language:
- en
- de
- fr
- it
- pt
- hi
- es
- th
library_name: transformers
pipeline_tag: text-generation
tags:
- llama-3.1
- meta
- autogptq
---

> [!IMPORTANT]
> This repository is a community-driven quantized version of the original model [`meta-llama/Meta-Llama-3.1-405B-Instruct`](https://huggingface.co/meta-llama/Meta-Llama-3.1-405B-Instruct) which is the FP16 half-precision official version released by Meta AI.

## Model Information

The Meta Llama 3.1 collection of multilingual large language models (LLMs) is a collection of pretrained and instruction tuned generative models in 8B, 70B and 405B sizes (text in/text out). The Llama 3.1 instruction tuned text only models (8B, 70B, 405B) are optimized for multilingual dialogue use cases and outperform many of the available open source and closed chat models on common industry benchmarks.

This repository contains [`meta-llama/Meta-Llama-3.1-405B-Instruct`](https://huggingface.co/meta-llama/Meta-Llama-3.1-405B-Instruct) quantized using [AutoGPTQ](https://github.com/AutoGPTQ/AutoGPTQ) from FP16 down to INT4 using the GPTQ kernels performing zero-point quantization with a group size of 128.

## Model Usage

> [!NOTE]
> In order to run the inference with Llama 3.1 405B Instruct GPTQ in INT4, around 203 GiB of VRAM are needed only for loading the model checkpoint, without including the KV cache or the CUDA graphs, meaning that there should be a bit over that VRAM available.

In order to use the current quantized model, support is offered for different solutions as `transformers`, `autogptq`, or `text-generation-inference`.

### 🤗 transformers

In order to run the inference with Llama 3.1 405B Instruct GPTQ in INT4, both `torch` and `autogptq` need to be installed as:

```bash
pip install "torch>=2.2.0,<2.3.0" --upgrade
pip install auto-gptq --no-build-isolation
```

Otherwise, running the model may fail, since the AutoGPTQ kernels are built with PyTorch 2.2.1, meaning that those will break with PyTorch 2.3.0.

Then, the latest version of `transformers` need to be installed including the `accelerate` extra, being 4.43.0 or higher, as:

```bash
pip install "transformers[accelerate]>=4.43.0" --upgrade
```

Finally, in order to use `autogptq`, `optimum` also needs to be installed:

```bash
pip install optimum --upgrade
```

To run the inference on top of Llama 3.1 405B Instruct GPTQ in INT4 precision, the GPTQ model can be instantiated as any other causal language modeling model via `AutoModelForCausalLM` and run the inference normally.

```python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_id = "hugging-quants/Meta-Llama-3.1-405B-Instruct-GPTQ-INT4"
prompt = [
  {"role": "system", "content": "You are a helpful assistant, that responds as a pirate."},
  {"role": "user", "content": "What's Deep Learning?"},
]

tokenizer = AutoTokenizer.from_pretrained(model_id)

inputs = tokenizer.apply_chat_template(
  prompt,
  tokenize=True,
  add_generation_prompt=True,
  return_tensors="pt",
  return_dict=True,
).to("cuda")

model = AutoModelForCausalLM.from_pretrained(
  model_id,
  torch_dtype=torch.float16,
  low_cpu_mem_usage=True,
  device_map="auto",
)

outputs = model.generate(**inputs, do_sample=True, max_new_tokens=256)
print(tokenizer.batch_decode(outputs, skip_special_tokens=True))
```

### AutoGPTQ

Alternatively, one may want to run that via `AutoGPTQ` even though it's built on top of 🤗 `transformers`, which is the recommended approach instead as described above.

In order to run the inference with Llama 3.1 405B Instruct GPTQ in INT4, both `torch` and `autogptq` need to be installed as:

```bash
pip install "torch>=2.2.0,<2.3.0" --upgrade
pip install auto-gptq --no-build-isolation
```

Otherwise, running the model may fail, since the AutoGPTQ kernels are built with PyTorch 2.2.1, meaning that those will break with PyTorch 2.3.0.

Then, the latest version of `transformers` need to be installed including the `accelerate` extra, being 4.43.0 or higher, as:

```bash
pip install "transformers[accelerate]>=4.43.0" --upgrade
```

Finally, in order to use `autogptq`, `optimum` also needs to be installed:

```bash
pip install optimum --upgrade
```

And then run it as follows:

```python
import torch
from auto_gptq import AutoGPTQForCausalLM
from transformers import AutoModelForCausalLM, AutoTokenizer

model_id = "hugging-quants/Meta-Llama-3.1-405B-Instruct-GPTQ-INT4"
prompt = [
  {"role": "system", "content": "You are a helpful assistant, that responds as a pirate."},
  {"role": "user", "content": "What's Deep Learning?"},
]

tokenizer = AutoTokenizer.from_pretrained(model_id)

inputs = tokenizer.apply_chat_template(prompt, tokenize=True, add_generation_prompt=True, return_tensors="pt").cuda()

model = AutoGPTQForCausalLM.from_pretrained(
  model_id,
  torch_dtype=torch.float16,
  low_cpu_mem_usage=True,
  device_map="auto",
)

outputs = model.generate(inputs, do_sample=True, max_new_tokens=256)
print(tokenizer.batch_decode(outputs, skip_special_tokens=True))
```

The AutoGPTQ script has been adapted from [AutoGPTQ/examples/quantization/basic_usage.py](https://github.com/AutoGPTQ/AutoGPTQ/blob/main/examples/quantization/basic_usage.py).

### 🤗 Text Generation Inference (TGI)

Coming soon!

## Quantization Reproduction

> [!NOTE]
> In order to quantize Llama 3.1 405B Instruct using AutoGPTQ, you will need to use an instance with at least enough CPU RAM to fit the whole model i.e. ~800GiB, and an NVIDIA GPU with 80GiB of VRAM to quantize it.

In order to quantize Llama 3.1 405B Instruct, first install `torch` and `autoqptq` as follows:

```bash
pip install "torch>=2.2.0,<2.3.0" --upgrade
pip install auto-gptq --no-build-isolation
```

Otherwise the quantization may fail, since the AutoGPTQ kernels are built with PyTorch 2.2.1, meaning that those will break with PyTorch 2.3.0.

Then install the latest version of `transformers` as follows:

```bash
pip install "transformers>=4.43.0" --upgrade
```

Finally, in order to use `autogptq`, `optimum` also needs to be installed:

```bash
pip install optimum --upgrade
```

And then, run the following script, adapted from [AutoGPTQ/examples/quantization/basic_usage.py](https://github.com/AutoGPTQ/AutoGPTQ/blob/main/examples/quantization/basic_usage.py).

```python
import random

import numpy as np
import torch

from auto_gptq import AutoGPTQForCausalLM, BaseQuantizeConfig
from datasets import load_dataset
from transformers import AutoTokenizer

pretrained_model_dir = "meta-llama/Meta-Llama-3.1-405B-Instruct"
quantized_model_dir = "meta-llama/Meta-Llama-3.1-405B-Instruct-GPTQ-INT4"

print("Loading tokenizer, dataset, and tokenizing the dataset...")
tokenizer = AutoTokenizer.from_pretrained(pretrained_model_dir, use_fast=True)
dataset = load_dataset("Salesforce/wikitext", "wikitext-2-raw-v1", split="train")
encodings = tokenizer("\n\n".join(dataset["text"]), return_tensors="pt")

print("Setting random seeds...")
random.seed(0)
np.random.seed(0)
torch.random.manual_seed(0)

print("Setting calibration samples...")
nsamples = 128
seqlen = 2048
calibration_samples = []
for _ in range(nsamples):
    i = random.randint(0, encodings.input_ids.shape[1] - seqlen - 1)
    j = i + seqlen
    input_ids = encodings.input_ids[:, i:j]
    attention_mask = torch.ones_like(input_ids)
    calibration_samples.append({"input_ids": input_ids, "attention_mask": attention_mask})

quantize_config = BaseQuantizeConfig(
    bits=4,  # quantize model to 4-bit
    group_size=128,  # it is recommended to set the value to 128
    desc_act=True,  # set to False can significantly speed up inference but the perplexity may slightly bad
    sym=True,  # using symmetric quantization so that the range is symmetric allowing the value 0 to be precisely represented (can provide speedups)
    damp_percent=0.1,  # see https://github.com/AutoGPTQ/AutoGPTQ/issues/196
)

# load un-quantized model, by default, the model will always be loaded into CPU memory
print("Load unquantized model...")
model = AutoGPTQForCausalLM.from_pretrained(pretrained_model_dir, quantize_config)

# quantize model, the examples should be list of dict whose keys can only be "input_ids" and "attention_mask"
print("Quantize model with calibration samples...")
model.quantize(calibration_samples)

# save quantized model using safetensors
model.save_quantized(quantized_model_dir, use_safetensors=True)
```