You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用Unsloth微调Orpheus-3b时,Trainer训练阶段报AttributeError: 'int' object has no attribute 'mean'错误

Unsloth微调Orpheus-3b时,Trainer训练阶段报AttributeError: 'int' object has no attribute 'mean'错误

看起来你在Unsloth上微调Orpheus-3b时卡到了训练环节的属性错误,我来帮你一步步排查解决~

问题核心定位

从你的代码和错误栈来看,这个错误出现在Unsloth的自定义训练步骤里,提示'int' object has no attribute 'mean'——说明训练时计算损失的环节,某个本该是tensor的变量变成了单个int值,大概率是数据整理(Data Collator)的环节出了格式不匹配的问题

仔细看你的代码:你已经专门写了适配Orpheus的orpheus_data_collator,但Trainer里却没用到它,反而用了默认的DataCollatorForLanguageModeling实例,这就是最可能的核心矛盾——默认collator返回的batch格式,和Unsloth优化后的训练逻辑期望的格式不兼容。

分步解决方案

1. 替换为自定义的Data Collator

立刻把Trainer参数里的data_collator换成你自己写的orpheus_data_collator,修改后的代码片段如下:

trainer = Trainer(
    model = model,
    train_dataset = processed_train_ds,
    data_collator = orpheus_data_collator,  # 这里换成自定义的collator
    args = TrainingArguments(
        # 你的训练参数保持不变
        per_device_train_batch_size = 8,
        gradient_accumulation_steps = 4,
        ...
    )
)

同时确保你的代码开头已经导入了torch(不然torch.stack会报错):

import torch

2. 验证数据集样本的格式

虽然你打印了第一个样本的labels是正常tensor,但建议批量检查几个样本,确保所有样本的核心字段都是符合要求的tensor:

# 检查前3个样本的格式是否合规
for i in range(3):
    sample = processed_train_ds[i]
    print(f"样本{i}格式检查:")
    print(f"input_ids: 形状{sample['input_ids'].shape},类型{type(sample['input_ids'])}")
    print(f"attention_mask: 形状{sample['attention_mask'].shape},类型{type(sample['attention_mask'])}")
    print(f"labels: 形状{sample['labels'].shape},类型{type(sample['labels'])}")

所有字段都应该是一维tensor(比如torch.Size([1024]),对应你设置的序列长度),不能是单个int值、numpy数组或者形状错误的tensor。

3. 回溯Labels的生成逻辑

如果前两步还没解决问题,再检查你的tokenization过程:

  • 确保labels是input_ids的副本,并且把不需要模型预测的部分(比如提示词前缀)设置为-100(这个值会被PyTorch的损失函数自动忽略)
  • 不要在tokenize后把labels转成numpy数组再转回tensor时出错,确保全程都是PyTorch tensor类型

4. 确认Unsloth模型加载正确

最后确认你是用Unsloth的官方方式加载的Orpheus-3b模型,比如:

from unsloth import FastLanguageModel
model, tokenizer = FastLanguageModel.from_pretrained(
    model_name = "unsloth/orpheus-3b",
    max_seq_length = 1024,  # 和你的数据集序列长度保持一致
    dtype = None,  # 自动检测bf16/fp16
    load_in_4bit = True,  # 如果用4bit量化训练
)

错误的模型加载方式也可能导致训练时的数据格式不兼容。

额外调试小技巧

如果还是遇到问题,可以先把per_device_train_batch_size调小到4,关闭梯度累积(gradient_accumulation_steps=1),用小批量数据快速测试,这样能更快定位是批量处理还是单样本的问题。

按这个步骤走,应该就能解决这个AttributeError的问题了,有新问题随时说~

火山引擎 最新活动