-
Notifications
You must be signed in to change notification settings - Fork 0
/
bitsandbytes_llama8B-NF4.py
55 lines (44 loc) · 1.41 KB
/
bitsandbytes_llama8B-NF4.py
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
import os
from dotenv import load_dotenv
import time
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
import torch
# Load the .env file
load_dotenv()
# Set environment variables
os.environ['HF_TOKEN'] = os.getenv('HF_TOKEN')
os.environ['HF_HOME'] = '.'
hf_home = os.environ['HF_HOME'] ## Custom cache directory, **path to save the model**
# Set model and device
model_id = "meta-llama/Meta-Llama-3.1-8B-Instruct"
hf_home = os.environ['HF_HOME']
# Load tokenizer
tokenizer = AutoTokenizer.from_pretrained(
model_id,
cache_dir=hf_home,
device_map="auto",
)
# Load model
## Quantization config
quantization_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
bnb_4bit_use_double_quant=True,
llm_int8_enable_fp32_cpu_offload=True,
)
## Quantized model
model = AutoModelForCausalLM.from_pretrained(
model_id,
cache_dir=hf_home,
low_cpu_mem_usage=True,
device_map="auto", ### Loads to multiple devices!!
quantization_config=quantization_config,
torch_dtype=torch.bfloat16,
)
# Save model
model.save_pretrained("models--fsaudm--Meta-Llama-3.1-8B-Instruct-NF4")
tokenizer.save_pretrained("models--fsaudm--Meta-Llama-3.1-8B-Instruct-NF4")
# Push model to hub
model.push_to_hub("fsaudm/Meta-Llama-3.1-8B-Instruct-NF4")
tokenizer.push_to_hub("fsaudm/Meta-Llama-3.1-8B-Instruct-NF4")