Pengembangan AutogptQ telah berhenti. Silakan beralih ke GPTQModel sebagai pengganti drop-in.
Paket kuantisasi LLM yang mudah digunakan dengan API yang ramah pengguna, berdasarkan algoritma GPTQ (kuantisasi berat-saja).
use_marlin=True saat memuat model.auto-gptq terintegrasi, jadi sekarang menjalankan dan melatih model GPTQ dapat lebih tersedia untuk semua orang! Lihat blog ini dan sumber daya untuk lebih jelasnya!Untuk lebih banyak sejarah, silakan beralih ke sini
Hasilnya dihasilkan menggunakan skrip ini, ukuran batch input adalah 1, strategi decode adalah pencarian balok dan menegakkan model untuk menghasilkan 512 token, metrik kecepatan adalah token/s (semakin besar, semakin baik).
Model terkuantisasi dimuat menggunakan pengaturan yang dapat memperoleh kecepatan inferensi tercepat.
| model | GPU | num_beams | FP16 | GPTQ-INT4 |
|---|---|---|---|---|
| llama-7b | 1XA100-40G | 1 | 18.87 | 25.53 |
| llama-7b | 1XA100-40G | 4 | 68.79 | 91.30 |
| Moss-Moon 16b | 1XA100-40G | 1 | 12.48 | 15.25 |
| Moss-Moon 16b | 1XA100-40G | 4 | Oom | 42.67 |
| Moss-Moon 16b | 2XA100-40G | 1 | 06.83 | 06.78 |
| Moss-Moon 16b | 2XA100-40G | 4 | 13.10 | 10.80 |
| GPT-J 6B | 1xrtx3060-12g | 1 | Oom | 29.55 |
| GPT-J 6B | 1xrtx3060-12g | 4 | Oom | 47.36 |
Untuk perbandingan kebingungan, Anda dapat beralih ke sini dan di sini
AutogptQ tersedia di Linux dan Windows saja. Anda dapat menginstal rilis stabil AutoGptQ terbaru dari PIP dengan roda pra-built:
| Versi platform | Instalasi | Dibangun melawan Pytorch |
|---|---|---|
| CUDA 11.8 | pip install auto-gptq --no-build-isolation --extra-index-url https://huggingface.github.io/autogptq-index/whl/cu118/ | 2.2.1+Cu118 |
| CUDA 12.1 | pip install auto-gptq --no-build-isolation | 2.2.1+Cu121 |
| ROCM 5.7 | pip install auto-gptq --no-build-isolation --extra-index-url https://huggingface.github.io/autogptq-index/whl/rocm573/ | 2.2.1+rocm5.7 |
AutoGptQ dapat diinstal dengan ketergantungan Triton dengan pip install auto-gptq[triton] --no-build-isolation untuk dapat menggunakan backend Triton (saat ini hanya mendukung Linux, tidak ada kuantisasi 3-bit).
Untuk AutogptQ yang lebih lama, silakan merujuk ke tabel instalasi rilis sebelumnya.
Pada sistem NVIDIA, AutogptQ tidak mendukung Maxwell atau GPU yang lebih rendah.
Klon Kode Sumber:
git clone https://github.com/PanQiWei/AutoGPTQ.git && cd AutoGPTQ Beberapa paket diperlukan untuk membangun dari sumber: pip install numpy gekko pandas .
Kemudian, instal secara lokal dari sumber:
pip install -vvv --no-build-isolation -e . Anda dapat mengatur BUILD_CUDA_EXT=0 untuk menonaktifkan pembangunan ekstensi Pytorch, tetapi ini sangat berkecil hati karena autogptq kemudian jatuh kembali pada implementasi Python yang lambat.
Sebagai upaya terakhir, jika perintah di atas gagal, Anda dapat mencoba python setup.py install .
Untuk menginstal dari sumber untuk AMD GPU yang mendukung ROCM, harap tentukan variabel lingkungan ROCM_VERSION . Contoh:
ROCM_VERSION=5.6 pip install -vvv --no-build-isolation -e . Kompilasi dapat dipercepat dengan menentukan variabel (referensi) PYTORCH_ROCM_ARCH untuk membangun perangkat target tunggal, misalnya gfx90a untuk perangkat seri MI200.
Untuk sistem ROCM, paket rocsparse-dev , hipsparse-dev , rocthrust-dev , rocblas-dev dan hipblas-dev harus dibangun.
Perhatikan: Pastikan Anda berada di Commit 65c2e15 atau lebih baru
Untuk menginstal dari sumber untuk Intel Gaudi 2 HPU, atur variabel BUILD_CUDA_EXT=0 Variabel Lingkungan untuk menonaktifkan pembangunan ekstensi CUDA Pytorch. Contoh:
BUILD_CUDA_EXT=0 pip install -vvv --no-build-isolation -e .Perhatikan bahwa Intel Gaudi 2 menggunakan kernel yang dioptimalkan pada inferensi, dan membutuhkan
BUILD_CUDA_EXT=0pada mesin non-cuda.
PERINGATAN: Ini hanyalah sebuah karya penggunaan API dasar di AutogptQ, yang hanya menggunakan satu sampel untuk mengukur model yang jauh lebih kecil, kualitas model terkuantisasi menggunakan sampel kecil seperti itu mungkin tidak baik.
Di bawah ini adalah contoh untuk penggunaan auto_gptq paling sederhana untuk mengukur model dan inferensi setelah kuantisasi:
from transformers import AutoTokenizer , TextGenerationPipeline
from auto_gptq import AutoGPTQForCausalLM , BaseQuantizeConfig
import logging
logging . basicConfig (
format = "%(asctime)s %(levelname)s [%(name)s] %(message)s" , level = logging . INFO , datefmt = "%Y-%m-%d %H:%M:%S"
)
pretrained_model_dir = "facebook/opt-125m"
quantized_model_dir = "opt-125m-4bit"
tokenizer = AutoTokenizer . from_pretrained ( pretrained_model_dir , use_fast = True )
examples = [
tokenizer (
"auto-gptq is an easy-to-use model quantization library with user-friendly apis, based on GPTQ algorithm."
)
]
quantize_config = BaseQuantizeConfig (
bits = 4 , # quantize model to 4-bit
group_size = 128 , # it is recommended to set the value to 128
desc_act = False , # set to False can significantly speed up inference but the perplexity may slightly bad
)
# load un-quantized model, by default, the model will always be loaded into CPU memory
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"
model . quantize ( examples )
# save quantized model
model . save_quantized ( quantized_model_dir )
# save quantized model using safetensors
model . save_quantized ( quantized_model_dir , use_safetensors = True )
# push quantized model to Hugging Face Hub.
# to use use_auth_token=True, Login first via huggingface-cli login.
# or pass explcit token with: use_auth_token="hf_xxxxxxx"
# (uncomment the following three lines to enable this feature)
# repo_id = f"YourUserName/{quantized_model_dir}"
# commit_message = f"AutoGPTQ model for {pretrained_model_dir}: {quantize_config.bits}bits, gr{quantize_config.group_size}, desc_act={quantize_config.desc_act}"
# model.push_to_hub(repo_id, commit_message=commit_message, use_auth_token=True)
# alternatively you can save and push at the same time
# (uncomment the following three lines to enable this feature)
# repo_id = f"YourUserName/{quantized_model_dir}"
# commit_message = f"AutoGPTQ model for {pretrained_model_dir}: {quantize_config.bits}bits, gr{quantize_config.group_size}, desc_act={quantize_config.desc_act}"
# model.push_to_hub(repo_id, save_dir=quantized_model_dir, use_safetensors=True, commit_message=commit_message, use_auth_token=True)
# load quantized model to the first GPU
model = AutoGPTQForCausalLM . from_quantized ( quantized_model_dir , device = "cuda:0" )
# download quantized model from Hugging Face Hub and load to the first GPU
# model = AutoGPTQForCausalLM.from_quantized(repo_id, device="cuda:0", use_safetensors=True, use_triton=False)
# inference with model.generate
print ( tokenizer . decode ( model . generate ( ** tokenizer ( "auto_gptq is" , return_tensors = "pt" ). to ( model . device ))[ 0 ]))
# or you can also use pipeline
pipeline = TextGenerationPipeline ( model = model , tokenizer = tokenizer )
print ( pipeline ( "auto-gptq is" )[ 0 ][ "generated_text" ])Untuk fitur kuantisasi model yang lebih canggih, silakan referensi ke skrip ini
from auto_gptq . modeling import BaseGPTQForCausalLM
class OPTGPTQForCausalLM ( BaseGPTQForCausalLM ):
# chained attribute name of transformer layer block
layers_block_name = "model.decoder.layers"
# chained attribute names of other nn modules that in the same level as the transformer layer block
outside_layer_modules = [
"model.decoder.embed_tokens" , "model.decoder.embed_positions" , "model.decoder.project_out" ,
"model.decoder.project_in" , "model.decoder.final_layer_norm"
]
# chained attribute names of linear layers in transformer layer module
# normally, there are four sub lists, for each one the modules in it can be seen as one operation,
# and the order should be the order when they are truly executed, in this case (and usually in most cases),
# they are: attention q_k_v projection, attention output projection, MLP project input, MLP project output
inside_layer_modules = [
[ "self_attn.k_proj" , "self_attn.v_proj" , "self_attn.q_proj" ],
[ "self_attn.out_proj" ],
[ "fc1" ],
[ "fc2" ]
] Setelah ini, Anda dapat menggunakan OPTGPTQForCausalLM.from_pretrained dan metode lain seperti yang ditunjukkan dalam dasar.
Anda dapat menggunakan tugas yang didefinisikan dalam auto_gptq.eval_tasks untuk mengevaluasi kinerja model pada tugas down-stream spesifik sebelum dan sesudah kuantisasi.
Tugas yang telah ditentukan mendukung semua model-model kausal yang diterapkan? transformer dan dalam proyek ini.
from functools import partial
import datasets
from transformers import AutoTokenizer , AutoModelForCausalLM , GenerationConfig
from auto_gptq import AutoGPTQForCausalLM , BaseQuantizeConfig
from auto_gptq . eval_tasks import SequenceClassificationTask
MODEL = "EleutherAI/gpt-j-6b"
DATASET = "cardiffnlp/tweet_sentiment_multilingual"
TEMPLATE = "Question:What's the sentiment of the given text? Choices are {labels}. n Text: {text} n Answer:"
ID2LABEL = {
0 : "negative" ,
1 : "neutral" ,
2 : "positive"
}
LABELS = list ( ID2LABEL . values ())
def ds_refactor_fn ( samples ):
text_data = samples [ "text" ]
label_data = samples [ "label" ]
new_samples = { "prompt" : [], "label" : []}
for text , label in zip ( text_data , label_data ):
prompt = TEMPLATE . format ( labels = LABELS , text = text )
new_samples [ "prompt" ]. append ( prompt )
new_samples [ "label" ]. append ( ID2LABEL [ label ])
return new_samples
# model = AutoModelForCausalLM.from_pretrained(MODEL).eval().half().to("cuda:0")
model = AutoGPTQForCausalLM . from_pretrained ( MODEL , BaseQuantizeConfig ())
tokenizer = AutoTokenizer . from_pretrained ( MODEL )
task = SequenceClassificationTask (
model = model ,
tokenizer = tokenizer ,
classes = LABELS ,
data_name_or_path = DATASET ,
prompt_col_name = "prompt" ,
label_col_name = "label" ,
** {
"num_samples" : 1000 , # how many samples will be sampled to evaluation
"sample_max_len" : 1024 , # max tokens for each sample
"block_max_len" : 2048 , # max tokens for each data block
# function to load dataset, one must only accept data_name_or_path as input
# and return datasets.Dataset
"load_fn" : partial ( datasets . load_dataset , name = "english" ),
# function to preprocess dataset, which is used for datasets.Dataset.map,
# must return Dict[str, list] with only two keys: [prompt_col_name, label_col_name]
"preprocess_fn" : ds_refactor_fn ,
# truncate label when sample's length exceed sample_max_len
"truncate_prompt" : False
}
)
# note that max_new_tokens will be automatically specified internally based on given classes
print ( task . run ())
# self-consistency
print (
task . run (
generation_config = GenerationConfig (
num_beams = 3 ,
num_return_sequences = 3 ,
do_sample = True
)
)
) Tutorial memberikan panduan langkah demi langkah untuk mengintegrasikan auto_gptq dengan proyek Anda sendiri dan beberapa prinsip praktik terbaik.
Contoh memberikan banyak contoh skrip untuk menggunakan auto_gptq dengan cara yang berbeda.
Anda dapat menggunakan
model.config.model_typeuntuk membandingkan dengan tabel di bawah ini untuk memeriksa apakah model yang Anda gunakan didukung olehauto_gptq.Misalnya, model_type dari
WizardLM,vicunadangpt4allsemuanya adalahllama, maka mereka semua didukung olehauto_gptq.
| tipe model | kuantisasi | kesimpulan | peft-lora | peft-ada-lora | peft-adaption_prompt |
|---|---|---|---|---|---|
| bunga | ✅ | ✅ | ✅ | ✅ | |
| gpt2 | ✅ | ✅ | ✅ | ✅ | |
| GPT_NEOX | ✅ | ✅ | ✅ | ✅ | ✅Bequires Cabang Peft ini |
| GPTJ | ✅ | ✅ | ✅ | ✅ | ✅Bequires Cabang Peft ini |
| llama | ✅ | ✅ | ✅ | ✅ | ✅ |
| lumut | ✅ | ✅ | ✅ | ✅ | ✅Bequires Cabang Peft ini |
| memilih | ✅ | ✅ | ✅ | ✅ | |
| GPT_BIGCODE | ✅ | ✅ | ✅ | ✅ | |
| codegen | ✅ | ✅ | ✅ | ✅ | |
| Falcon (RefinedWebModel/RefinedWeb) | ✅ | ✅ | ✅ | ✅ |
Saat ini, auto_gptq mendukung: LanguageModelingTask , SequenceClassificationTask dan TextSummarizationTask ; Lebih banyak tugas akan segera datang!
Tes dapat dijalankan dengan:
pytest tests/ -s
AutogptQ default untuk menggunakan ekslasi exllAmav2 int4*fp16 untuk multiplikasi matriks.
Marlin adalah kernel INT4 * FP16 yang dioptimalkan baru-baru ini diusulkan di https://github.com/ist-daslab/marlin. Ini terintegrasi dalam AutogptQ saat memuat model dengan use_marlin=True . Kernel ini hanya tersedia di perangkat dengan kemampuan komputasi 8.0 atau 8.6 (Ampere GPU).