Bitsandbytes 文档
4 位量化
并获得增强的文档体验
开始使用
4 位量化
QLoRA 是一种微调方法,它将模型量化为 4 位,并在模型中添加一组低秩适应(LoRA)权重,通过量化权重对其进行微调。该方法除了标准的 Float4 数据类型 (LinearFP4
) 外,还引入了一种新的数据类型,即 4 位 NormalFloat (LinearNF4
)。LinearNF4
是一种用于正态分布数据的量化数据类型,可以提高性能。
Linear4bit
class bitsandbytes.nn.Linear4bit
< 源代码 >( input_features output_features bias = True compute_dtype = None compress_statistics = True quant_type = 'fp4' quant_storage = torch.uint8 device = None )
该类是 QLoRA 中提出的 4 位量化算法的基础模块。QLoRA 4 位线性层在底层使用块级 k 位量化,并可以选择各种计算数据类型,如 FP4 和 NF4。
为了量化一个线性层,首先应将原始的 fp16 / bf16 权重加载到 Linear4bit 模块中,然后调用 quantized_module.to("cuda")
来量化 fp16 / bf16 权重。
示例
import torch
import torch.nn as nn
import bitsandbytes as bnb
from bnb.nn import Linear4bit
fp16_model = nn.Sequential(
nn.Linear(64, 64),
nn.Linear(64, 64)
)
quantized_model = nn.Sequential(
Linear4bit(64, 64),
Linear4bit(64, 64)
)
quantized_model.load_state_dict(fp16_model.state_dict())
quantized_model = quantized_model.to(0) # Quantization happens here
__init__
< 源代码 >( input_features output_features bias = True compute_dtype = None compress_statistics = True quant_type = 'fp4' quant_storage = torch.uint8 device = None )
初始化 Linear4bit 类。
LinearFP4
class bitsandbytes.nn.LinearFP4
< 源代码 >( input_features output_features bias = True compute_dtype = None compress_statistics = True quant_storage = torch.uint8 device = None )
实现 FP4 数据类型。
__init__
< 源代码 >( input_features output_features bias = True compute_dtype = None compress_statistics = True quant_storage = torch.uint8 device = None )
LinearNF4
class bitsandbytes.nn.LinearNF4
< 源代码 >( input_features output_features bias = True compute_dtype = None compress_statistics = True quant_storage = torch.uint8 device = None )
实现 NF4 数据类型。
构造一种量化数据类型,其中每个分箱在标准正态分布 N(0, 1) 下的面积相等,并归一化到 [-1, 1] 范围内。
更多信息请阅读论文:QLoRA: Efficient Finetuning of Quantized LLMs (https://arxiv.org/abs/2305.14314)
NF4 数据类型在 bitsandbytes 中的实现可以在 `functional.py` 文件中的 `create_normal_map` 函数中找到:https://github.com/TimDettmers/bitsandbytes/blob/main/bitsandbytes/functional.py#L236。
__init__
< 源代码 >( input_features output_features bias = True compute_dtype = None compress_statistics = True quant_storage = torch.uint8 device = None )
Params4bit
class bitsandbytes.nn.Params4bit
< 源代码 >( data: typing.Optional[torch.Tensor] = None requires_grad = False quant_state: typing.Optional[bitsandbytes.functional.QuantState] = None blocksize: int = 64 compress_statistics: bool = True quant_type: str = 'fp4' quant_storage: dtype = torch.uint8 module: typing.Optional[ForwardRef('Linear4bit')] = None bnb_quantized: bool = False )