BitsAndBytesConfig参数描述
使用 Hugging Face Transformers 库中 BitsAndBytesConfig 进行动态量化时需要配置的核心参数:
一、核心量化参数配置
-
load_in_4bit
作用:启用 4 比特动态量化模式,将模型权重压缩为 4 位存储格式。
类型:bool,默认 False。
示例:
quantization_config = BitsAndBytesConfig(load_in_4bit=True)
适用场景:需显著减少模型显存占用的场景,例如在消费级 GPU(如 RTX 3090)上运行 7B 以上大模型。
-
bnb_4bit_quant_type
作用:指定 4 比特量化的数据类型,支持 nf4(NormalFloat4)和 fp4(自定义浮点4)两种格式。
nf4:基于正态分布优化的 4 位格式,适合预训练权重(信息论最优表示)。
fp4:4 位浮点格式,包含 1 符号位 + 2 指数位 + 1 尾数位,适用于激活值动态量化。
示例:
quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4")
-
bnb_4bit_compute_dtype
作用:指定计算时使用的数据类型,通常设为 torch.bfloat16 或 torch.float16 以加速计算。
类型:torch.dtype,默认 torch.float32。
示例:
quantization_config = BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_compute_dtype=torch.bfloat16 )
优化效果:将计算精度降至 16 位,可提升推理速度 30% 以上。
二、内存优化参数
-
bnb_4bit_use_double_quant
作用:启用嵌套量化(Double Quantization),对量化系数进行二次压缩,进一步减少内存占用。
类型:bool,默认 False。
示例:
quantization_config = BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_use_double_quant=True )
效果:可额外节省约 0.5GB 内存(以 7B 模型为例)。
-
llm_int8_threshold
作用:设定激活值异常检测阈值,超过该值的激活值保留为 FP16 计算以避免精度损失。
类型:float,默认 6.0。
示例:
quantization_config = BitsAndBytesConfig(load_in_4bit=True,llm_int8_threshold=10.0 # 适用于激活值波动较大的模型 )
调整建议:对于小模型或微调模型,建议降低至 4.0-8.0。
三、高级控制参数
-
llm_int8_skip_modules
作用:指定跳过量化的模块列表,避免敏感层(如输出层)因量化导致性能下降。
类型:List[str]。
示例:
quantization_config = BitsAndBytesConfig(load_in_4bit=True,llm_int8_skip_modules=["lm_head", "embed_tokens"] )
-
llm_int8_enable_fp32_cpu_offload
作用:启用 FP32 CPU 卸载,将部分计算转移至 CPU 以节省 GPU 显存。
类型:bool,默认 False。
示例:
quantization_config = BitsAndBytesConfig(load_in_4bit=True,llm_int8_enable_fp32_cpu_offload=True )
适用场景:显存不足时混合使用 CPU/GPU 资源。
四、典型配置示例
- 场景 1:高精度推理
from transformers import BitsAndBytesConfigquantization_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_threshold=6.0)
- 场景 2:低显存微调
quantization_config = BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type="fp4",llm_int8_skip_modules=["lm_head"],llm_int8_enable_fp32_cpu_offload=True
)