You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PEFT qLoRA训练模型时遇Device参数无效错误求助

解决PEFT qLoRA训练中的设备类型错误

问题根源

手动调用 .to(device) 移动量化后的PEFT模型会与BitsAndBytes和Trainer的设备管理逻辑冲突,导致部分模型组件的设备索引变为None,触发类型错误。

修复方案

1. 移除手动设备移动操作

创建Trainer时不要手动将模型移到指定设备,让Trainer自动处理设备分配。同时加载原始模型时需正确配置device_map。

2. 正确加载量化模型

加载原始模型时,通过device_map参数让框架自动分配设备(或指定具体GPU),配合BitsAndBytesConfig完成量化。

修正后的代码示例

from transformers import AutoModelForCausalLM, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model
from transformers import TrainingArguments, Trainer
import torch
import time

# BitsAndBytes量化配置(示例)
bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_use_double_quant=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16
)

# 加载原始模型,配置device_map自动分配设备
original_model = AutoModelForCausalLM.from_pretrained(
    "你的模型名称",
    quantization_config=bnb_config,
    device_map="auto",  # 或指定"cuda:0"锁定单GPU
    trust_remote_code=True
)

# Lora配置保持不变
lora_config = LoraConfig(
    r=8,
    lora_alpha=16,
    target_modules=[
        "q_proj",
        "k_proj",
        "v_proj",
        "o_proj",
        "gate_proj",
        "up_proj",
        "down_proj",
        "lm_head",
    ],
    bias="none",
    lora_dropout=0.05,
    task_type="CAUSAL_LM",
)
peft_model = get_peft_model(original_model, lora_config)

output_dir = f'./peft-bn-mistral-training-{str(int(time.time()))}'

peft_training_args = TrainingArguments(
    output_dir=output_dir,
    auto_find_batch_size=True,
    learning_rate=1e-3,
    num_train_epochs=1,
    logging_steps=1,
    max_steps=1,
    fp16=True  # 可选,根据GPU支持开启混合精度
)

# 移除.to(device),直接传入peft_model
peft_trainer = Trainer(
    model=peft_model,
    args=peft_training_args,
    train_dataset=tokenized_datasets["train"],
)
peft_trainer.train()

peft_model_path="./peft-bn-mistral-checkpoint-local"
peft_trainer.model.save_pretrained(peft_model_path)

额外说明

  • 使用BitsAndBytes量化时,模型的设备管理由框架自动处理,手动移动模型会破坏内部设备状态一致性。
  • device_map="auto"会自动将模型层分配到可用GPU/CPU,若需指定单GPU可设为device_map="cuda:0"。
  • 确保transformers、peft、bitsandbytes库版本兼容(建议使用最新稳定版)。

内容的提问来源于stack exchange,提问作者Syed Mohammad Fahim Abrar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 20:05:54