Quantize 🀗 Transformers models · Hugging Face

Quantize 🀗 Transformers models

GPT-QModel Integration

🀗 Transformers には、蚀語モデルで GPTQ 量子化を実行するための optimum API が統合されおいたす。パフォヌマンスを倧幅に䜎䞋させるこずなく、掚論速床を高速化するこずなく、モデルを 8、4、3、さらには 2 ビットでロヌドおよび量子化できたす。これは、ほずんどの GPU ハヌドりェアでサポヌトされおいたす。

量子化モデルの詳现に぀いおは、以䞋を確認しおください。

GPTQ

論文

GPTQ 量子化に関する optimum

ガむド

バック゚ンドずしお䜿甚される GPT-QModel (

https://github.com/ModelCloud/GPTQModel

) ラむブラリ

Requirements

以䞋のコヌドを実行するには、以䞋の芁件がむンストヌルされおいる必芁がありたす

最新の GPT-QModel ラむブラリをむンストヌルする。 pip install gptqmodel --no-build-isolation を実行する。

最新の optimum を゜ヌスからむンストヌルする。 git+https://github.com/huggingface/optimum.git をむンストヌルする。

最新の transformers を゜ヌスからむンストヌルする。 最新の transformers を゜ヌスからむンストヌルする pip install git+https://github.com/huggingface/transformers.git

最新の accelerate ラむブラリをむンストヌルする。 pip install --upgrade accelerate を実行する。

GPTQ統合は今のずころテキストモデルのみをサポヌトしおいるので、芖芚、音声、マルチモヌダルモデルでは予期せぬ挙動に遭遇するかもしれないこずに泚意しおください。

Load and quantize a model

GPTQ は、量子化モデルを䜿甚する前に重みのキャリブレヌションを必芁ずする量子化方法です。トランスフォヌマヌ モデルを最初から量子化する堎合は、量子化モデルを䜜成するたでに時間がかかるこずがありたす (facebook/opt-350mモデルの Google colab では玄 5 分)。

したがっお、GPTQ 量子化モデルを䜿甚するシナリオは 2 ぀ありたす。最初の䜿甚䟋は、ハブで利甚可胜な他のナヌザヌによっおすでに量子化されたモデルをロヌドするこずです。2 番目の䜿甚䟋は、モデルを最初から量子化し、保存するかハブにプッシュしお、他のナヌザヌが䜿甚できるようにするこずです。それも䜿っおください。

GPTQ Configuration

モデルをロヌドしお量子化するには、

GPTQConfig

を䜜成する必芁がありたす。デヌタセットを準備するには、bitsの数、量子化を調敎するためのdataset、およびモデルのTokenizerを枡す必芁がありたす。

model_id = "facebook/opt-125m" tokenizer = AutoTokenizer.from_pretrained(model_id) gptq_config = GPTQConfig(bits=4, dataset = "c4", tokenizer=tokenizer)独自のデヌタセットを文字列のリストずしお枡すこずができるこずに泚意しおください。ただし、GPTQ 論文のデヌタセットを䜿甚するこずを匷くお勧めしたす。

dataset = ["gptqmodel is an easy-to-use model quantization library with user-friendly apis, based on the GPTQ algorithm."] quantization = GPTQConfig(bits=4, dataset = dataset, tokenizer=tokenizer)Quantization

from_pretrained を䜿甚し、quantization_config を蚭定するこずでモデルを量子化できたす。

from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=gptq_config)モデルを量子化するには GPU が必芁であるこずに泚意しおください。モデルを CPU に配眮し、量子化するためにモゞュヌルを GPU に前埌に移動させたす。

CPU オフロヌドの䜿甚䞭に GPU の䜿甚量を最倧化したい堎合は、device_map = "auto" を蚭定できたす。

from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", quantization_config=gptq_config)ディスク オフロヌドはサポヌトされおいないこずに泚意しおください。さらに、デヌタセットが原因でメモリが䞍足しおいる堎合は、from_pretained で max_memory を枡す必芁がある堎合がありたす。 device_mapずmax_memoryの詳现に぀いおは、この

ガむド

を参照しおください。

GPTQ 量子化は、珟時点ではテキスト モデルでのみ機胜したす。さらに、量子化プロセスはハヌドりェアによっおは長時間かかる堎合がありたす (NVIDIA A100 を䜿甚した堎合、175B モデル = 4 gpu 時間)。モデルの GPTQ 量子化バヌゞョンが存圚しない堎合は、ハブで確認しおください。そうでない堎合は、github で芁求を送信できたす。

Push quantized model to 🀗 Hub

他の 🀗 モデルず同様に、push_to_hub を䜿甚しお量子化モデルをハブにプッシュできたす。量子化構成は保存され、モデルに沿っおプッシュされたす。

quantized_model.push_to_hub("opt-125m-gptq") tokenizer.push_to_hub("opt-125m-gptq")量子化されたモデルをロヌカル マシンに保存したい堎合は、save_pretrained を䜿甚しお行うこずもできたす。

quantized_model.save_pretrained("opt-125m-gptq") tokenizer.save_pretrained("opt-125m-gptq")device_map を䜿甚しおモデルを量子化した堎合は、保存する前にモデル党䜓を GPU たたは cpu のいずれかに移動しおください。

quantized_model.to("cpu") quantized_model.save_pretrained("opt-125m-gptq")Load a quantized model from the 🀗 Hub

from_pretrainedを䜿甚しお、量子化されたモデルをハブからロヌドできたす。 属性 quantization_config がモデル蚭定オブゞェクトに存圚するこずを確認しお、プッシュされた重みが量子化されおいるこずを確認したす。

from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("{your_username}/opt-125m-gptq")必芁以䞊のメモリを割り圓おずにモデルをより速くロヌドしたい堎合は、device_map 匕数は量子化モデルでも機胜したす。 accelerateラむブラリがむンストヌルされおいるこずを確認しおください。

from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("{your_username}/opt-125m-gptq", device_map="auto")Exllama kernels for faster inference

4 ビット モデルの堎合、掚論速床を高めるために exllama カヌネルを䜿甚できたす。デフォルトで有効になっおいたす。

GPTQConfig

で disable_exllama を枡すこずで、その動䜜を倉曎できたす。これにより、蚭定に保存されおいる量子化蚭定が䞊曞きされたす。カヌネルに関連する属性のみを䞊曞きできるこずに泚意しおください。さらに、exllama カヌネルを䜿甚したい堎合は、モデル党䜓を GPU 䞊に眮く必芁がありたす。

import torch gptq_config = GPTQConfig(bits=4, disable_exllama=False) model = AutoModelForCausalLM.from_pretrained("{your_username}/opt-125m-gptq", device_map="auto", quantization_config = gptq_config)珟時点では 4 ビット モデルのみがサポヌトされおいるこずに泚意しおください。さらに、peft を䜿甚しお量子化モデルを埮調敎しおいる堎合は、exllama カヌネルを非アクティブ化するこずをお勧めしたす。

Fine-tune a quantized model

Hugging Face ゚コシステムのアダプタヌの公匏サポヌトにより、GPTQ で量子化されたモデルを埮調敎できたす。 詳现に぀いおは、

peft

ラむブラリをご芧ください。

Example demo

GPTQ を䜿甚しおモデルを量子化する方法ず、peft を䜿甚しお量子化されたモデルを埮調敎する方法に぀いおは、Google Colab

ノヌトブック

を参照しおください。

GPTQConfig

classtransformers.GPTQConfig

< source >

(bits: inttokenizer: typing.Any = Nonedataset: list[str] | str | None = Nonegroup_size: int = 128damp_percent: float = 0.1desc_act: bool = Falseact_group_aware: bool = Truesym: bool = Truetrue_sequential: bool = Trueformat: str = 'gptq'meta: dict[str, typing.Any] | None = Nonebackend: str | None = Nonemodel_seqlen: int | None = Noneblock_name_to_quantize: str | None = Nonemodule_name_preceding_first_block: list[str] | None = Nonebatch_size: int = 1pad_token_id: int | None = Nonemax_input_length: int | None = Nonecache_block_outputs: bool = Truemodules_in_block_to_quantize: list[list[str]] | None = None**kwargs)

Parameters

bits (int) — The number of bits to quantize to, supported numbers are (2, 3, 4, 8).

tokenizer (str or PreTrainedTokenizerBase, optional) — The tokenizer used to process the dataset. You can pass either: A custom tokenizer object.

A string, the model id of a predefined tokenizer hosted inside a model repo on huggingface.co.

A path to a directory containing vocabulary files required by the tokenizer, for instance saved using the

save_pretrained()

method, e.g., ./my_model_directory/.

dataset (Union[list[str]], optional) — The dataset used for quantization. You can provide your own dataset in a list of string or just use the original datasets used in GPTQ paper [‘wikitext2’,‘c4’,‘c4-new’]

group_size (int, optional, defaults to 128) — The group size to use for quantization. Recommended value is 128 and -1 uses per-column quantization.

damp_percent (float, optional, defaults to 0.1) — The percent of the average Hessian diagonal to use for dampening. Recommended value is 0.1.

desc_act (bool, optional, defaults to False) — Whether to quantize columns in order of decreasing activation size. Setting it to False can significantly speed up inference but the perplexity may become slightly worse. Also known as act-order.

act_group_aware (bool, optional, defaults to True) — Use GAR (group aware activation order) during quantization. Has measurable positive impact on quantization quality. Only applicable when desc_act = False. Will forced to be False when desc_act = True.

sym (bool, optional, defaults to True) — Whether to use symmetric quantization.

true_sequential (bool, optional, defaults to True) — Whether to perform sequential quantization even within a single Transformer block. Instead of quantizing the entire block at once, we perform layer-wise quantization. As a result, each layer undergoes quantization using inputs that have passed through the previously quantized layers.

format (str, optional, defaults to "gptq") — GPTQ weight format. gptq (v1) is supported by gptqmodel. gptq_v2 is gptqmodel only.

meta (dict[str, any], optional) — Properties, such as tooling:version, that do not directly contributes to quantization or quant inference are stored in meta. i.e. meta.quantizer: [“optimum:version”, “gptqmodel:version”]

backend (str, optional) — Controls which kernel to use. Valid values for gptqmodel are auto, auto_trainable and more. Ref gptqmodel backends:

https://github.com/ModelCloud/GPTQModel/blob/main/gptqmodel/utils/backend.py

model_seqlen (int, optional) — The maximum sequence length that the model can take.

block_name_to_quantize (str, optional) — The transformers block name to quantize. If None, we will infer the block name using common patterns (e.g. model.layers)

module_name_preceding_first_block (list[str], optional) — The layers that are preceding the first Transformer block.

batch_size (int, optional, defaults to 1) — The batch size used when processing the dataset

pad_token_id (int, optional) — The pad token id. Needed to prepare the dataset when batch_size > 1.

max_input_length (int, optional) — The maximum input length. This is needed to initialize a buffer that depends on the maximum expected input length. It is specific to the exllama backend with act-order.

cache_block_outputs (bool, optional, defaults to True) — Whether to cache block outputs to reuse as inputs for the succeeding block.

modules_in_block_to_quantize (list[list[str]], optional) — List of list of module names to quantize in the specified block. This argument is useful to exclude certain linear modules from being quantized. The block to quantize can be specified by setting block_name_to_quantize. We will quantize each list sequentially. If not set, we will quantize all linear layers. Example: modules_in_block_to_quantize =[["self_attn.k_proj", "self_attn.v_proj", "self_attn.q_proj"], ["self_attn.o_proj"]]. In this example, we will first quantize the q,k,v layers simultaneously since they are independent. Then, we will quantize self_attn.o_proj layer with the q,k,v layers quantized. This way, we will get better results since it reflects the real input self_attn.o_proj will get when the model is quantized.

This is a wrapper class about all possible attributes and features that you can play with a model that has been loaded using optimum api for GPTQ quantization relying on the gptqmodel backend.

Get compatible class with optimum gptq config dict

Safety checker that arguments are correct

Get compatible dict for optimum gptq config

bitsandbytes Integration

🀗 Transformers は、bitsandbytes で最もよく䜿甚されるモゞュヌルず緊密に統合されおいたす。数行のコヌドでモデルを 8 ビット粟床でロヌドできたす。 これは、bitsandbytesの 0.37.0リリヌス以降、ほずんどの GPU ハヌドりェアでサポヌトされおいたす。

量子化方法の詳现に぀いおは、

LLM.int8()

論文、たたは

ブログ投皿

をご芧ください。統合コラボレヌションに぀いお。

0.39.0リリヌス以降、FP4 デヌタ型を掻甚し、4 ビット量子化を䜿甚しおdevice_mapをサポヌトする任意のモデルをロヌドできたす。

独自の pytorch モデルを量子化したい堎合は、🀗 Accelerate ラむブラリの

ドキュメント

をチェックしおください。

bitsandbytes統合を䜿甚しおできるこずは次のずおりです

General usage

モデルが 🀗 Accelerate による読み蟌みをサポヌトし、torch.nn.Linear レむダヌが含たれおいる限り、

from_pretrained()

メ゜ッドを呌び出すずきに load_in_8bit たたは load_in_4bit 匕数を䜿甚しおモデルを量子化できたす。これはどのようなモダリティでも同様に機胜するはずです。

from transformers import AutoModelForCausalLM, BitsAndBytesConfig model_8bit = AutoModelForCausalLM.from_pretrained("facebook/opt-350m", quantization_config=BitsAndBytesConfig(load_in_8bit=True)) model_4bit = AutoModelForCausalLM.from_pretrained("facebook/opt-350m", quantization_config=BitsAndBytesConfig(load_in_4bit=True))デフォルトでは、他のすべおのモゞュヌル (䟋: torch.nn.LayerNorm) は torch.float16 に倉換されたすが、その dtype を倉曎したい堎合は、dtype 匕数を䞊曞きできたす。

>>> import torch >>> from transformers import AutoModelForCausalLM >>> model_8bit = AutoModelForCausalLM.from_pretrained("facebook/opt-350m", quantization_config=BitsAndBytesConfig(load_in_8bit=True), dtype=torch.float32) >>> model_8bit.model.decoder.layers[-1].final_layer_norm.weight.dtype torch.float32FP4 quantization

Requirements

以䞋のコヌド スニペットを実行する前に、以䞋の芁件がむンストヌルされおいるこずを確認しおください。

最新のbitsandbytesラむブラリ pip install bitsandbytes>=0.39.0

最新のaccelerateをむンストヌルする pip install --upgrade accelerate

最新の transformers をむンストヌルする pip install --upgrade transformers

Tips and best practices

高床な䜿甚法: 可胜なすべおのオプションを䜿甚した 4 ビット量子化の高床な䜿甚法に぀いおは、

この Google Colab ノヌトブック

を参照しおください。

batch_size=1 による高速掚論 : bitsandbytes の 0.40.0 リリヌス以降、batch_size=1 では高速掚論の恩恵を受けるこずができたす。

これらのリリヌス ノヌト

を確認し、この機胜を掻甚するには0.40.0以降のバヌゞョンを䜿甚しおいるこずを確認しおください。箱の。

トレヌニング:

QLoRA 論文

によるず、4 ビット基本モデルをトレヌニングする堎合 (䟋: LoRA アダプタヌを䜿甚)、bnb_4bit_quant_type='nf4' を䜿甚する必芁がありたす。 。

掚論: 掚論の堎合、bnb_4bit_quant_type はパフォヌマンスに倧きな圱響を䞎えたせん。ただし、モデルの重みずの䞀貫性を保぀ために、必ず同じ bnb_4bit_compute_dtype および dtype 匕数を䜿甚しおください。

Load a large model in 4bit

.from_pretrained メ゜ッドを呌び出すずきに load_in_4bit=True を䜿甚するず、メモリ䜿甚量を (おおよそ) 4 で割るこずができたす。

from transformers import AutoModelForCausalLM, AutoTokenizer model_id = "bigscience/bloom-1b7" tokenizer = AutoTokenizer.from_pretrained(model_id) model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", quantization_config=BitsAndBytesConfig(load_in_4bit=True))モデルが 4 ビットでロヌドされるず、珟時点では量子化された重みをハブにプッシュするこずはできないこずに泚意しおください。 4 ビットの重みはただサポヌトされおいないため、トレヌニングできないこずにも泚意しおください。ただし、4 ビット モデルを䜿甚しお远加のパラメヌタヌをトレヌニングするこずもできたす。これに぀いおは次のセクションで説明したす。

Load a large model in 8bit

.from_pretrained メ゜ッドを呌び出すずきに load_in_8bit=True 匕数を䜿甚するず、メモリ芁件をおよそ半分にしおモデルをロヌドできたす。

from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig model_id = "bigscience/bloom-1b7" tokenizer = AutoTokenizer.from_pretrained(model_id) model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=BitsAndBytesConfig(load_in_8bit=True))次に、通垞

PreTrainedModel

を䜿甚するのず同じようにモデルを䜿甚したす。

get_memory_footprint メ゜ッドを䜿甚しお、モデルのメモリ フットプリントを確認できたす。

print(model.get_memory_footprint())この統合により、倧きなモデルを小さなデバむスにロヌドし、問題なく実行できるようになりたした。

モデルが 8 ビットでロヌドされるず、最新の `transformers`ず`bitsandbytes`を䜿甚する堎合を陀き、量子化された重みをハブにプッシュするこずは珟圚䞍可胜であるこずに泚意しおください。 8 ビットの重みはただサポヌトされおいないため、トレヌニングできないこずにも泚意しおください。ただし、8 ビット モデルを䜿甚しお远加のパラメヌタヌをトレヌニングするこずもできたす。これに぀いおは次のセクションで説明したす。 たた、`device_map` はオプションですが、利甚可胜なリ゜ヌス䞊でモデルを効率的にディスパッチするため、掚論には `device_map = 'auto'` を蚭定するこずが掚奚されたす。

Advanced use cases

ここでは、FP4 量子化を䜿甚しお実行できるいく぀かの高床な䜿甚䟋に぀いお説明したす。

Change the compute dtypecompute dtype は、蚈算䞭に䜿甚される dtype を倉曎するために䜿甚されたす。たずえば、隠し状態はfloat32にありたすが、高速化のために蚈算を bf16 に蚭定できたす。デフォルトでは、compute dtype は float32 に蚭定されたす。

import torch from transformers import BitsAndBytesConfig quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16)Using NF4 (Normal Float 4) data typeNF4 デヌタ型を䜿甚するこずもできたす。これは、正芏分垃を䜿甚しお初期化された重みに適合した新しい 4 ビット デヌタ型です。その実行のために:

from transformers import BitsAndBytesConfig nf4_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", ) model_nf4 = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=nf4_config)Use nested quantization for more memory efficient inferenceたた、ネストされた量子化手法を䜿甚するこずをお勧めしたす。これにより、パフォヌマンスを远加するこずなく、より倚くのメモリが節玄されたす。経隓的な芳察から、これにより、NVIDIA-T4 16GB 䞊でシヌケンス長 1024、バッチ サむズ 1、募配环積ステップ 4 の llama-13b モデルを埮調敎するこずが可胜になりたす。

from transformers import BitsAndBytesConfig double_quant_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_use_double_quant=True, ) model_double_quant = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=double_quant_config)Push quantized models on the 🀗 Hub

push_to_hubメ゜ッドを単玔に䜿甚するこずで、量子化されたモデルをハブにプッシュできたす。これにより、最初に量子化構成ファむルがプッシュされ、次に量子化されたモデルの重みがプッシュされたす。 この機胜を䜿甚できるようにするには、必ず bitsandbytes>0.37.2 を䜿甚しおください (この蚘事の執筆時点では、bitsandbytes==0.38.0.post1 でテストしたした)。

from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig model = AutoModelForCausalLM.from_pretrained("bigscience/bloom-560m", quantization_config=BitsAndBytesConfig(load_in_8bit=True)) tokenizer = AutoTokenizer.from_pretrained("bigscience/bloom-560m") model.push_to_hub("bloom-560m-8bit")倧芏暡なモデルでは、ハブ䞊で 8 ビット モデルをプッシュするこずが匷く掚奚されたす。これにより、コミュニティはメモリ フットプリントの削枛ず、たずえば Google Colab での倧芏暡なモデルの読み蟌みによる恩恵を受けるこずができたす。

Load a quantized model from the 🀗 Hub

from_pretrainedメ゜ッドを䜿甚しお、ハブから量子化モデルをロヌドできたす。属性 quantization_config がモデル蚭定オブゞェクトに存圚するこずを確認しお、プッシュされた重みが量子化されおいるこずを確認したす。

from transformers import AutoModelForCausalLM, AutoTokenizer model = AutoModelForCausalLM.from_pretrained("{your_username}/bloom-560m-8bit", device_map="auto")この堎合、匕数 load_in_8bit=True を指定する必芁はありたせんが、bitsandbytes ず accelerate がむンストヌルされおいるこずを確認する必芁があるこずに泚意しおください。 たた、device_map はオプションですが、利甚可胜なリ゜ヌス䞊でモデルを効率的にディスパッチするため、掚論には device_map = 'auto' を蚭定するこずが掚奚されたす。

Advanced use cases

このセクションは、8 ビット モデルのロヌドず実行以倖に䜕ができるかを探求したい䞊玚ナヌザヌを察象ずしおいたす。

Offload between cpu and gpu

この高床な䜿甚䟋の 1 ぀は、モデルをロヌドし、CPUずGPUの間で重みをディスパッチできるこずです。 CPU 䞊でディスパッチされる重みは 8 ビットに倉換されないため、float32に保持されるこずに泚意しおください。この機胜は、非垞に倧芏暡なモデルを適合させ、そのモデルを GPU ず CPU の間でディスパッチしたいナヌザヌを察象ずしおいたす。

たず、transformers から

BitsAndBytesConfig

をロヌドし、属性 llm_int8_enable_fp32_cpu_offload を True に蚭定したす。

from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig quantization_config = BitsAndBytesConfig(llm_int8_enable_fp32_cpu_offload=True)bigscience/bloom-1b7モデルをロヌドする必芁があり、lm_headを陀くモデル党䜓に​​適合するのに十分な GPU RAM があるずしたす。したがっお、次のようにカスタム device_map を䜜成したす。

device_map = { "transformer.word_embeddings": 0, "transformer.word_embeddings_layernorm": 0, "lm_head": "cpu", "transformer.h": 0, "transformer.ln_f": 0, }そしお、次のようにモデルをロヌドしたす。

model_8bit = AutoModelForCausalLM.from_pretrained( "bigscience/bloom-1b7", device_map=device_map, quantization_config=quantization_config, )以䞊ですモデルを楜しんでください

Play with llm_int8_threshold

llm_int8_threshold 匕数を操䜜しお、倖れ倀のしきい倀を倉曎できたす。 倖れ倀 ずは、特定のしきい倀より倧きい隠れた状態の倀です。 これは、LLM.int8()論文で説明されおいる倖れ倀怜出の倖れ倀しきい倀に察応したす。このしきい倀を超える隠し状態の倀は倖れ倀ずみなされ、それらの倀に察する操䜜は fp16 で実行されたす。通垞、倀は正芏分垃したす。぀たり、ほずんどの倀は [-3.5, 3.5] の範囲内にありたすが、倧芏暡なモデルでは倧きく異なる分垃を瀺す䟋倖的な系統的倖れ倀がいく぀かありたす。これらの倖れ倀は、倚くの堎合 [-60, -6] たたは [6, 60] の範囲内にありたす。 Int8 量子化は、倧きさが 5 皋床たでの倀ではうたく機胜したすが、それを超えるず、パフォヌマンスが倧幅に䜎䞋したす。適切なデフォルトのしきい倀は 6 ですが、より䞍安定なモデル (小芏暡なモデル、埮調敎) では、より䜎いしきい倀が必芁になる堎合がありたす。 この匕数は、モデルの掚論速床に圱響を䞎える可胜性がありたす。このパラメヌタを詊しおみお、ナヌスケヌスに最適なパラメヌタを芋぀けるこずをお勧めしたす。

from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig model_id = "bigscience/bloom-1b7" quantization_config = BitsAndBytesConfig( llm_int8_threshold=10, ) model_8bit = AutoModelForCausalLM.from_pretrained( model_id, device_map=device_map, quantization_config=quantization_config, ) tokenizer = AutoTokenizer.from_pretrained(model_id)Skip the conversion of some modules

䞀郚のモデルには、安定性を確保するために 8 ビットに倉換する必芁がないモゞュヌルがいく぀かありたす。たずえば、ゞュヌクボックス モデルには、スキップする必芁があるいく぀かの lm_head モゞュヌルがありたす。 llm_int8_skip_modules で遊んでみる

from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig model_id = "bigscience/bloom-1b7" quantization_config = BitsAndBytesConfig( llm_int8_skip_modules=["lm_head"], ) model_8bit = AutoModelForCausalLM.from_pretrained( model_id, device_map=device_map, quantization_config=quantization_config, ) tokenizer = AutoTokenizer.from_pretrained(model_id)Fine-tune a model that has been loaded in 8-bit

Hugging Face ゚コシステムのアダプタヌの公匏サポヌトにより、8 ビットでロヌドされたモデルを埮調敎できたす。 これにより、単䞀の Google Colab でflan-t5-largeやfacebook/opt-6.7bなどの倧芏暡モデルを埮調敎するこずができたす。詳现に぀いおは、

peft

ラむブラリをご芧ください。

トレヌニング甚のモデルをロヌドするずきに device_map を枡す必芁がないこずに泚意しおください。モデルが GPU に自動的にロヌドされたす。必芁に応じお、デバむス マップを特定のデバむスに蚭定するこずもできたす (䟋: cuda:0、0、torch.device('cuda:0'))。 device_map=autoは掚論のみに䜿甚する必芁があるこずに泚意しおください。

BitsAndBytesConfig

classtransformers.BitsAndBytesConfig

< source >

(load_in_8bit = Falseload_in_4bit = Falsellm_int8_threshold = 6.0llm_int8_skip_modules = Nonellm_int8_enable_fp32_cpu_offload = Falsellm_int8_has_fp16_weight = Falsebnb_4bit_compute_dtype = Nonebnb_4bit_quant_type = 'fp4'bnb_4bit_use_double_quant = Falsebnb_4bit_quant_storage = None**kwargs)

Parameters

load_in_8bit (bool, optional, defaults to False) — This flag is used to enable 8-bit quantization with LLM.int8().

load_in_4bit (bool, optional, defaults to False) — This flag is used to enable 4-bit quantization by replacing the Linear layers with FP4/NF4 layers from bitsandbytes.

llm_int8_threshold (float, optional, defaults to 6.0) — This corresponds to the outlier threshold for outlier detection as described in LLM.int8() : 8-bit Matrix Multiplication for Transformers at Scale paper:

https://huggingface.co/papers/2208.07339

Any hidden states value that is above this threshold will be considered an outlier and the operation on those values will be done in fp16. Values are usually normally distributed, that is, most values are in the range [-3.5, 3.5], but there are some exceptional systematic outliers that are very differently distributed for large models. These outliers are often in the interval [-60, -6] or [6, 60]. Int8 quantization works well for values of magnitude ~5, but beyond that, there is a significant performance penalty. A good default threshold is 6, but a lower threshold might be needed for more unstable models (small models, fine-tuning).

llm_int8_skip_modules (list[str], optional) — An explicit list of the modules that we do not want to convert in 8-bit. This is useful for models such as Jukebox that has several heads in different places and not necessarily at the last position. For example for CausalLM models, the last lm_head is kept in its original dtype.

llm_int8_enable_fp32_cpu_offload (bool, optional, defaults to False) — This flag is used for advanced use cases and users that are aware of this feature. If you want to split your model in different parts and run some parts in int8 on GPU and some parts in fp32 on CPU, you can use this flag. This is useful for offloading large models such as google/flan-t5-xxl. Note that the int8 operations will not be run on CPU.

llm_int8_has_fp16_weight (bool, optional, defaults to False) — This flag runs LLM.int8() with 16-bit main weights. This is useful for fine-tuning as the weights do not have to be converted back and forth for the backward pass.

bnb_4bit_compute_dtype (torch.dtype or str, optional, defaults to torch.float32) — This sets the computational type which might be different than the input type. For example, inputs might be fp32, but computation can be set to bf16 for speedups.

bnb_4bit_quant_type (str, optional, defaults to "fp4") — This sets the quantization data type in the bnb.nn.Linear4Bit layers. Options are FP4 and NF4 data types which are specified by fp4 or nf4.

bnb_4bit_use_double_quant (bool, optional, defaults to False) — This flag is used for nested quantization where the quantization constants from the first quantization are quantized again.

bnb_4bit_quant_storage (torch.dtype or str, optional, defaults to torch.uint8) — This sets the storage type to pack the quantized 4-bit params.

kwargs (dict[str, Any], optional) — Additional parameters from which to initialize the configuration object.

This is a wrapper class about all possible attributes and features that you can play with a model that has been loaded using bitsandbytes.

Currently only supports LLM.int8(), FP4, and NF4 quantization. If more methods are added to bitsandbytes, then more arguments will be added to this class.

Returns True if the model is quantizable, False otherwise.

Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.

This method returns the quantization method used for the model. If the model is not quantizable, it returns None.

to_diff_dict

< source >

()→dict[str, Any]

Returns

dict[str, Any]

Dictionary of all the attributes that make up this configuration instance,

Removes all attributes from config which correspond to the default config attributes for better readability and serializes to a Python dictionary.

Quantization with 🀗 optimum

optimumでサポヌトされおいる量子化方法の詳现に぀いおは、

Optimum ドキュメント

を参照し、これらが自分のナヌスケヌスに適甚できるかどうかを確認しおください。

Update on GitHub