Unsloth - 动态 4 bit 量化


本文翻译自:Unsloth - Dynamic 4-bit Quantization (2024年12月4日 Daniel & Michael

https://unsloth.ai/blog/dynamic-4bit


我们能否将一个20GB的语言模型缩小到仅5GB,同时不牺牲准确性?使用量化技术!

流行的算法如AWQ、Bitsandbytes、GPTQ和HQQ 旨在压缩模型,但简单的量化 通常会损害准确性,使得模型变得不可用。
我们很高兴地介绍 Unsloth - 动态4位量化,这涉及到 动态选择 不对某些参数进行量化,并且它建立在 BitsandBytes 4位之上。这种方法在仅使用比BnB 4位多10%的VRAM的情况下,实现了显著的精度提升。

2025年1月更新: 我们动态量化专家的有效性有一个很好的例子,就是我们对微软的Phi-4的最新动态量化。

我们修复了Phi-4中的错误并将我们的动态4位量化提交到了Hugging Face的OpenLLM排行榜。

我们的动态4位模型得分几乎与我们的16位版本一样高——并且远高于标准的Bnb 4位和微软官方的16位模型,特别是在MMLU方面。


在这里插入图片描述


我们已经在 Hugging Face 上上传了视觉模型,包括 Llama 3.2 Vision,使用名为 unsloth-bnb-4bit 的新方法进行量化此处
基于文本的模型,如Llama 3.1(8B)也上传了我们也有一个Colab笔记本微调Llama 3.2(11B)视觉与我们的新的动态量化方法 这里

下面的测试表明,标准4位量化的性能比原来的16位差,而 Unsloth的动态4位量化 提供了非常准确和可靠的结果。


💔 量化可能会破坏模型

Unsloth 默认使用金标准的 Bitsandbytes 对所有线性层进行优化。例如,Llama 3.2 Vision (11B) 在全精度下使用 20GB,但使用 nf4 时只需 6.5GB——减少了 68%。
例如,将Qwen2 Vision (2B)的量化降低到4位会完全破坏模型。事实表明,较小的模型仅使用6到8位量化,而较大的模型如 8B 及以上则使用4位量化。


在这里插入图片描述


Qwen2-VL-2B-InstructDescriptionSizeResult
16bitThe image shows a train traveling on tracks.4.11GB
Default 4bit all layersThe image depicts a vibrant and colorful scene of a coastal area.1.36GB
Unsloth quantThe image shows a train traveling on tracks.1.81GB

例如,将所有层量化到4位 将使模型将上面的图像描述为 a vibrant and colorful scene of a coastal area,这是错误的。

通过仔细选择 不量化一些参数,模型恢复了其准确性,并且与全精度格式相似,内存使用额外增加了450MB。全精度使用4.11GB。
大多数视觉模型都有一个线性投影,所以如果我们也关闭对所有中间线性投影的量化,我们会看到模型仍然损坏。


Qwen2 VL (2B) InstructDescriptionSizeResult
Except linear layersThe image depicts a vibrant and colorful scene of a coastal area during a sunny day.4.11GB
Unsloth quantThe image shows a train traveling on tracks.1.81GB

在错误分析中,我们看到 Qwen2 VL 2B Instruct 在前几层有大的激活量化错误(左图)。

也存在一个大的峰值,以及激活错误的逐渐下降。我们还看到有一个参数有大的权重量化错误。

在这里插入图片描述


我们上传了我们的动态4位量化模型,用于Qwen2 VL:


🦙 Llama 3.2 Vision 细节

Llama 3.2 11B Vision 对量化不那么敏感。因此,目标是尽可能匹配 16 位精度。

在这里插入图片描述


Llama-3.2-Vision-11B-InstructDescriptionSizeResult
16bitThe image depicts a serene scene of a wooden bench situated near a body of water, with a group of birds perched on the backrest. The purpose of the image appears to be capturing a peaceful moment in nature.19.87GB
Default 4bit all layersThe image depicts a serene scene featuring a wooden bench with a row of small birds perched on its backrest, set against the backdrop of a body of water. The bench, made of light-colored wood, has a horizontal slat design and is positioned at an angle, facing the water.6.54GB🆗 No mention of the purpose of the image
Unsloth quantThe image depicts a serene scene featuring a wooden bench with a row of small birds perched on its backrest, set against the backdrop of a body of water. The purpose of the image appears to be capturing a peaceful moment in nature.7.23GB✅Purpose of image returns

有趣的是,4位量化去除了描述图像目的的句子。

Unsloth的动态量化使用了更多的内存,但再次将图像的目的恢复回来了!!


在这里插入图片描述


Llama的错误图看起来非常有趣!视觉编码器似乎没有极其大的错误,除了1个大的峰值。权重量化错误看起来非常有趣!我们发现除了第一层之外,所有层的交叉注意力输出投影都不应该进行量化。
我们的动态4位量化Llama 3.2(11B)视觉模型:


Pixtral (12B) 视觉

Pixtral 是最有趣的分析对象!权重量化误差相对温和,尽管有一个较大的峰值。激活误差非常有趣!我们发现整个视觉编码器不应该量化到 4bit,因为它会导致很大的差异。


在这里插入图片描述


最有趣的是,如果我们使用我们的动态量化方法,它确实使模型变得更好,但它仍然奇怪地不匹配16位全精度。

如果我们放宽约束并捕捉所有“坏”模块,我们就能恢复模型的全部功能!

以下您可以看到4位版本表现不错,但16位版本对X射线的分析更加深入。

我们的动态量化使用了400MB更多的内存,但实际上开始分析X射线,这与完整的4位模型不同。

如果我们再使用3.5GB的内存(这已经相当多了),那么我们就可以完全模拟16位的精度!

我们还将比较使用额外1GB内存的8bit版本,有趣的是,它看起来与4bit版本相似,因此8bit似乎表现不佳。但这确实需要更多的调查!


在这里插入图片描述


Pixtral-12BDescriptionSizeResult
16bitThe image is a dental X-ray (radiograph) of a child’s mouth, showing the arrangement of teeth and jaw structure. The X-ray highlights several key features: 1. Upper Arrows: These arrows point to the upper jaw area, likely indicating the presence of unerupted or impacted teeth, which are teeth that have not erupted through the gums but are trapped beneath the surface.26.32GB
Default 4bit all layersThis is a dental X-ray image of a child’s mouth, highlighting several teeth with arrows. The image shows the positions of different types of teeth: primary (baby teeth), secondary (adult teeth), and tertiary (permanent teeth). The primary teeth are already fallen, the secondary teeth are coming out, and the tertiary teeth have not yet come out.7.83GB🆗 No mention of arrows’ purpose. No detailed analysis.
Unsloth quantThis is an X-ray image of a child’s mouth, highlighting several teeth with arrows. The image shows the arrangement and presence of primary (baby) teeth and permanent teeth. The arrows are pointing to specific teeth that may require attention, possibly for removal or other dental treatment.8.42GB🆗 Much better - analyses the X-ray more.
8bit quantThe image is a dental X-ray of a child’s mouth, highlighting specific areas with arrows. The X-ray shows the arrangement and development of the child’s teeth and jaw structure. The arrows likely indicate areas of concern or interest, such as potential issues with tooth alignment, decay, or other dental problems.13.1GB🆗Also better than full 4bit - analysis the X-ray.

🦙 Llama 3.2 (90B) 视觉指令

对于Llama最大的视觉模型,我们看到了一些峰值,但并不多。来自11B模型的交叉注意力现象似乎要少得多。


在这里插入图片描述


在这里插入图片描述


2025-03-09(日)

<think>好的,用户想要使用unsloth来微调deepseek-r1-8B模型,并希望得到完整的代码。首先,我需要确认unsloth是否支持这个模型。unsloth主要用于优化微调过程,比如减少内存占用和加快训练速度,通常与Hugging Face的transformers库结合使用。deepseek-r1-8B可能是一个基于类似LLaMA架构的模型,所以可能需要检查是否支持。 接下来,用户可能需要代码示例,包括数据准备、模型加载、训练配置、训练过程和保存模型。需要确保步骤完整,例如安装必要的库,加载数据集,使用正确的模型名称,设置训练参数如batch size、learning rate等,以及处理可能的内存问题,比如使用4量化。 另外,用户可能对数据格式有疑问,所以需要提供一个示例数据集的结构,比如alpaca格式。还要注意可能出现的错误,比如OOM(内存不足),这时候可能需要调整batch size或者使用梯度累积。 需要提醒用户替换数据集路径,并根据硬件调整参数,比如device_map和dtype设置。最后,保存模型并演示如何加载使用,确保代码的可运行性。 可能还需要验证代码的准确性,比如检查unsloth的最新文档,确认支持的模型类型,以及是否有额外的参数需要注意。同时,确保训练器的设置正确,比如使用Seq2SeqTrainer,因为可能是生成任务。 总结:步骤包括安装库、准备数据、加载模型和分词器、配置训练参数、训练、保存模型。需要注意模型兼容性、硬件限制和参数调整,确保用户能顺利运行代码。</think>以下是一个使用Unsloth微调DeepSeek-R1-8B模型的完整代码示例。请注意根据您的硬件调整参数(如batch_size、gradient_accumulation_steps等): ```python # 首先安装必要库(建议使用Python 3.10+) # pip install "unsloth[colab] @ git+https://github.com/unslothai/unsloth.git" # pip install --no-deps "xformers<0.26.0" trl peft accelerate datasets bitsandbytes import torch from unsloth import FastLanguageModel from datasets import load_dataset from trl import SFTTrainer from transformers import TrainingArguments # 参数配置 max_seq_length = 2048 # 根据GPU内存调整 dtype = None # None自动检测,或指定为torch.float16/torch.bfloat16 load_in_4bit = True # 使用4量化节省内存 # 加载DeepSeek-R1-8B模型 model, tokenizer = FastLanguageModel.from_pretrained( model_name = "deepseek-ai/deepseek-llm-7b-r1", # 确认HuggingFace模型名称 max_seq_length = max_seq_length, dtype = dtype, load_in_4bit = load_in_4bit, ) # 添加LoRA适配器(可选) model = FastLanguageModel.get_peft_model( model, r=16, # LoRA秩 target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj"], # 常见目标模块 lora_alpha=16, lora_dropout=0, bias="none", use_gradient_checkpointing=True, ) # 准备数据集(示例使用Alpaca格式) dataset = load_dataset("yahma/alpaca-cleaned", split="train") dataset = dataset.map(lambda sample: { "text": f"""Below is an instruction that describes a task. Write a response that appropriately completes the request. ### Instruction: {sample['instruction']} ### Input: {sample['input']} ### Response: {sample['output']}""" }) # 训练参数配置 trainer = SFTTrainer( model = model, tokenizer = tokenizer, train_dataset = dataset, dataset_text_field = "text", max_seq_length = max_seq_length, dataset_num_proc = 2, packing = True, # 序列打包提高效率 args = TrainingArguments( per_device_train_batch_size = 2, gradient_accumulation_steps = 4, warmup_steps = 5, num_train_epochs = 3, learning_rate = 2e-5, fp16 = not torch.cuda.is_bf16_supported(), bf16 = torch.cuda.is_bf16_supported(), logging_steps = 1, optim = "adamw_8bit", weight_decay = 0.01, lr_scheduler_type = "linear", seed = 3407, output_dir = "outputs", save_strategy="steps", save_steps=500, ), ) # 执行训练 trainer.train() # 保存微调后的模型 model.save_pretrained("lora_adapter") # 保存LoRA适配器 # model.push_to_hub("your_username/model_name") # 可选:上传到HuggingFace Hub # 使用微调后的模型生成文本 inputs = tokenizer( ["### Instruction:\nExplain deep learning in 3 sentences\n\n### Response:"], return_tensors="pt" ).to("cuda") outputs = model.generate(**inputs, max_new_tokens=128) print(tokenizer.decode(outputs[0], skip_special_tokens=True)) ``` 注意事项: 1. 硬件要求:至少需要24GB显存(建议A100/A6000等) 2. 数据集:示例使用Alpaca格式,请替换为您的实际数据集 3. 模型名称:请确认HuggingFace上的准确模型名称 4. 内存优化:如遇OOM错误,可以尝试: - 降低`per_device_train_batch_size` - 增加`gradient_accumulation_steps` - 使用`load_in_4bit=True` - 减小`max_seq_length` 建议在微调前: 1. 检查CUDA可用性:`print(torch.cuda.is_available())` 2. 验证模型加载:`print(model)` 3. 测试基本推理:先运行生成代码确保基础模型正常工作 如需完整生产级实现,建议参考: - Unsloth官方文档:https://github.com/unslothai/unsloth - DeepSeek官方微调指南:https://huggingface.co/deepseek-ai
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程乐园

请我喝杯伯爵奶茶~!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值