BitsAndBytesConfig量化及注意事项
基础操作
# 设置参数,4bit量化的默认参数,可适用大部分场景
quantization_config = BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type="nf4",bnb_4bit_use_double_quant=True,bnb_4bit_compute_dtype=torch.bfloat16,llm_int8_skip_modules=["resampler", "lm_head"])
# 加载模型时载入上述参数,即可实现量化
model = FM9GV.from_pretrained(model_file,attn_implementation='sdpa', torch_dtype=torch.bfloat16,quantization_config=quantization_config)
QLoRA
QLoRA的实现原理其实是:
- 对原模型进行量化,从而减少训练时原参数的显存占用
- 使用LoRA增加额外需要微调的参数,这部分参数不量化
QLoRA Demo
可能出现的问题
(1)一些模块不能量化
对于VLM,在vpm(视觉特征提取器)和llm之间会有resampler,一些resampler使用了nn.MultiheadAttention。似乎是BitsAndBytesConfig的bug,直接对nn.MultiheadAttention量化会报错,如下:
RuntimeError: self and mat2 must have the same dtype, but got BFloat16 and Byte
所以在llm_int8_skip_modules
中加入"resampler",代表不对模型中的self.resampler进行量化。
同理,测试发现"lm_head"也不能量化,否则报错。