Deepspeed : AttributeError: ‘DummyOptim‘ object has no attribute ‘step‘

题意 :尝试在一个名为 DummyOptim 的对象上调用 .step() 方法,但是这个对象并没有定义这个方法

问题背景:

I want to use deepspeed for training LLMs along with Huggingface Trainer. But when I use deepspeed along with trainer I get error "AttributeError: 'DummyOptim' object has no attribute 'step'". Below is my code

尝试结合使用 DeepSpeed 和 Hugging Face 的 Trainer API 来训练大型语言模型(LLMs)时遇到 "AttributeError: 'DummyOptim' object has no attribute 'step'" 这个错误,下面是我的代码:

python 复制代码
import argparse
import numpy as np
import torch
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForCausalLM

from trl import DPOTrainer, DPOConfig
def preprocess_data(item):
    return {
        'prompt': 'Instruct: ' + item['prompt'] + '\n',
        'chosen': 'Output: ' + item['chosen'],
        'rejected': 'Output: ' + item['rejected']
    }        

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--epochs", type=int, default=1)
    parser.add_argument("--beta", type=float, default=0.1)
    parser.add_argument("--batch_size", type=int, default=4)
    parser.add_argument("--lr", type=float, default=1e-6)
    parser.add_argument("--seed", type=int, default=2003)
    parser.add_argument("--model_name", type=str, default="EleutherAI/pythia-14m")
    parser.add_argument("--dataset_name", type=str, default="jondurbin/truthy-dpo-v0.1")
    parser.add_argument("--local_rank", type=int, default=0)

    args = parser.parse_args()

    # Determine device based on local_rank
    device = torch.device("cuda", args.local_rank) if torch.cuda.is_available() else torch.device("cpu")


    tokenizer = AutoTokenizer.from_pretrained(args.model_name)
    tokenizer.pad_token = tokenizer.eos_token
    model = AutoModelForCausalLM.from_pretrained(args.model_name).to(device)
    ref_model = AutoModelForCausalLM.from_pretrained(args.model_name).to(device)

    dataset = load_dataset(args.dataset_name, split="train")
    dataset = dataset.map(preprocess_data)

    # Split the dataset into training and validation sets
    dataset = dataset.train_test_split(test_size=0.1, seed=args.seed)
    train_dataset = dataset['train']
    val_dataset = dataset['test']

    training_args = DPOConfig(
        learning_rate=args.lr,
        num_train_epochs=args.epochs,
        per_device_train_batch_size=args.batch_size,
        logging_steps=10,
        remove_unused_columns=False,
        max_length=1024,
        max_prompt_length=512,
        deepspeed="ds_config.json"       
    )

    

    # Verify and print embedding dimensions before finetuning
    print("Base model embedding dimension:", model.config.hidden_size)

    model.train()
    ref_model.eval()

    dpo_trainer = DPOTrainer(
        model,
        ref_model,
        beta=args.beta,
        train_dataset=train_dataset,
        eval_dataset=val_dataset,
        tokenizer=tokenizer,
        args=training_args,
    )

    dpo_trainer.train()
    # Evaluate
    evaluation_results = dpo_trainer.evaluate()
    print("Evaluation Results:", evaluation_results)

    save_model_name = 'finetuned_model'
    model.save_pretrained(save_model_name)

if __name__ == "__main__":
    main()

The config file used is the below one 使用的配置文件是下面的这个:

python 复制代码
{
"zero_optimization": {
        "stage": 3,
        "offload_optimizer": {
            "device": "cpu",
            "pin_memory": true
        },
        "offload_param": {
            "device": "cpu",
            "pin_memory": true
        },
        "overlap_comm": true,
        "contiguous_gradients": true,
        "sub_group_size": 1e9,
        "reduce_bucket_size": "auto",
        "stage3_prefetch_bucket_size": "auto",
        "stage3_param_persistence_threshold": "auto",
        "stage3_max_live_parameters": 1e9,
        "stage3_max_reuse_distance": 1e9,
        "stage3_gather_16bit_weights_on_model_save": true
    },
"bf16": {
    "enabled": "auto"
},
"fp16": {
    "enabled": "auto",
    "loss_scale": 0,
    "initial_scale_power": 32,
    "loss_scale_window": 1000,
    "hysteresis": 2,
    "min_loss_scale": 1
},

"gradient_accumulation_steps": "auto",
"gradient_clipping": "auto",
"train_batch_size": "auto",
"train_micro_batch_size_per_gpu": "auto",
"wall_clock_breakdown": false,
"flops_profiler": {
    "enabled": false,
    "detailed": false
},
"optimizer": {
    "type": "Lamb",
    "params": {
    "lr": "auto",
    "betas": [0.9, 0.999],
    "eps": "auto",
    "weight_decay": "auto"
    }
},
"zero_allow_untested_optimizer": true
}

The code works with out deepspeed. I have torch=2.3.1, deepspeed =0.14.5, trl=0.9.4 and CUDA Version: 12.5.

在没有使用 DeepSpeed 的情况下,代码可以正常工作。当前的软件版本配置为:PyTorch 2.3.1,DeepSpeed 0.14.5,TRL 0.9.4,以及 CUDA 版本 12.5。

Appreciate any hint on this ! 非常感谢您在这方面的任何提示!

问题解决:

python 复制代码
from accelerate.utils import DistributedType

training_args.distributed_state.distributed_type = DistributedType.DEEPSPEED

adding this solves the issue 添加这个解决了问题

相关推荐
新手小袁_J1 小时前
实现Python将csv数据导入到Neo4j
数据库·python·neo4j·《我是刑警》·python连接neo4j·python导入csv·csv数据集导入neo4j
清风ꦿ1 小时前
neo4j 图表数据导入到 TuGraph
python·neo4j·knowledge graph
深度学习lover3 小时前
[项目代码] YOLOv8 遥感航拍飞机和船舶识别 [目标检测]
python·yolo·目标检测·计算机视觉·遥感航拍飞机和船舶识别
水木流年追梦4 小时前
【python因果库实战10】为何需要因果分析
开发语言·python
m0_675988235 小时前
Leetcode2545:根据第 K 场考试的分数排序
python·算法·leetcode
凡人的AI工具箱7 小时前
每天40分玩转Django:Django测试
数据库·人工智能·后端·python·django·sqlite
qyq17 小时前
Django框架与ORM框架
后端·python·django
企业软文推广7 小时前
企业如何选择媒体发稿平台及相关事项?媒介盒子分享
python
JM_life7 小时前
你的第一个博客-第一弹
python
No0d1es8 小时前
GESP CCF python二级编程等级考试认证真题 2024年12月
开发语言·python·青少年编程·gesp·ccf·二级