当前位置: 首页 > news >正文

大模型训练框架DeepSpeed使用入门(1): 训练设置

文章目录

  • 一、安装
  • 二、训练设置
    • Step1 第一步参数解析
    • Step2 初始化后端
    • Step3 训练初始化
  • 三、训练代码展示


官方文档直接抄过来,留个笔记。
https://deepspeed.readthedocs.io/en/latest/initialize.html

使用案例来自:
https://github.com/OvJat/DeepSpeedTutorial


大模型训练的痛点是模型参数过大,动辄上百亿,如果单靠单个GPU来完成训练基本不可能。所以需要多卡或者分布式训练来完成这项工作。

DeepSpeed是由Microsoft提供的分布式训练工具,旨在支持更大规模的模型和提供更多的优化策略和工具。对于更大模型的训练来说,DeepSpeed提供了更多策略,例如:Zero、Offload等。

本文简单介绍下如何使用DeepSpeed。


一、安装

pip install deepspeed

二、训练设置

Step1 第一步参数解析

DeepSpeed 使用 argparse 来应用控制台的设置,使用

deepspeed.add_config_arguments()

可以将DeepSpeed内置的参数增加到我们自己的应用参数解析中。

parser = argparse.ArgumentParser(description='My training script.')
parser.add_argument('--local_rank', type=int, default=-1,help='local rank passed from distributed launcher')
# Include DeepSpeed configuration arguments
parser = deepspeed.add_config_arguments(parser)
cmd_args = parser.parse_args()

Step2 初始化后端

与Step3中的 deepspeed.initialize() 不同,
直接调用即可。
一般发生在以下场景

when using model parallelism, pipeline parallelism, or certain data loader scenarios.

在Step3的initialize前,进行调用

deepspeed.init_distributed()

Step3 训练初始化

首先调用 deepspeed.initialize() 进行初始化,是整个调用DeepSpeed训练的入口。
调用后,如果分布式后端没有被初始化后,此时会初始化分布式后端。
使用案例:

model_engine, optimizer, _, _ = deepspeed.initialize(args=cmd_args,model=net,model_parameters=net.parameters(),training_data=ds)

API如下:

def initialize(args=None,model: torch.nn.Module = None,optimizer: Optional[Union[Optimizer, DeepSpeedOptimizerCallable]] = None,model_parameters: Optional[torch.nn.Module] = None,training_data: Optional[torch.utils.data.Dataset] = None,lr_scheduler: Optional[Union[_LRScheduler, DeepSpeedSchedulerCallable]] = None,distributed_port: int = TORCH_DISTRIBUTED_DEFAULT_PORT,mpu=None,dist_init_required: Optional[bool] = None,collate_fn=None,config=None,config_params=None):"""Initialize the DeepSpeed Engine.Arguments:args: an object containing local_rank and deepspeed_config fields.This is optional if `config` is passed.model: Required: nn.module class before apply any wrappersoptimizer: Optional: a user defined Optimizer or Callable that returns an Optimizer object.This overrides any optimizer definition in the DeepSpeed json config.model_parameters: Optional: An iterable of torch.Tensors or dicts.Specifies what Tensors should be optimized.training_data: Optional: Dataset of type torch.utils.data.Datasetlr_scheduler: Optional: Learning Rate Scheduler Object or a Callable that takes an Optimizer and returns a Scheduler object.The scheduler object should define a get_lr(), step(), state_dict(), and load_state_dict() methodsdistributed_port: Optional: Master node (rank 0)'s free port that needs to be used for communication during distributed trainingmpu: Optional: A model parallelism unit object that implementsget_{model,data}_parallel_{rank,group,world_size}()dist_init_required: Optional: None will auto-initialize torch distributed if needed,otherwise the user can force it to be initialized or not via boolean.collate_fn: Optional: Merges a list of samples to form amini-batch of Tensor(s).  Used when using batched loading from amap-style dataset.config: Optional: Instead of requiring args.deepspeed_config you can pass your deepspeed configas an argument instead, as a path or a dictionary.config_params: Optional: Same as `config`, kept for backwards compatibility.Returns:A tuple of ``engine``, ``optimizer``, ``training_dataloader``, ``lr_scheduler``* ``engine``: DeepSpeed runtime engine which wraps the client model for distributed training.* ``optimizer``: Wrapped optimizer if a user defined ``optimizer`` is supplied, or ifoptimizer is specified in json config else ``None``.* ``training_dataloader``: DeepSpeed dataloader if ``training_data`` was supplied,otherwise ``None``.* ``lr_scheduler``: Wrapped lr scheduler if user ``lr_scheduler`` is passed, orif ``lr_scheduler`` specified in JSON configuration. Otherwise ``None``."""

三、训练代码展示

def parse_arguments():import argparseparser = argparse.ArgumentParser(description='deepspeed training script.')parser.add_argument('--local_rank', type=int, default=-1,help='local rank passed from distributed launcher')# Include DeepSpeed configuration argumentsparser = deepspeed.add_config_arguments(parser)args = parser.parse_args()return argsdef train():args = parse_arguments()# init distributeddeepspeed.init_distributed()# init modelmodel = MyClassifier(3, 100, ch_multi=128)# init datasetds = MyDataset((3, 512, 512), 100, sample_count=int(1e6))# init engineengine, optimizer, training_dataloader, lr_scheduler = deepspeed.initialize(args=args,model=model,model_parameters=model.parameters(),training_data=ds,# config=deepspeed_config,)# load checkpointengine.load_checkpoint("./data/checkpoints/MyClassifier/")# trainlast_time = time.time()loss_list = []echo_interval = 10engine.train()for step, (xx, yy) in enumerate(training_dataloader):step += 1xx = xx.to(device=engine.device, dtype=torch.float16)yy = yy.to(device=engine.device, dtype=torch.long).reshape(-1)outputs = engine(xx)loss = tnf.cross_entropy(outputs, yy)engine.backward(loss)engine.step()loss_list.append(loss.detach().cpu().numpy())if step % echo_interval == 0:loss_avg = np.mean(loss_list[-echo_interval:])used_time = time.time() - last_timetime_p_step = used_time / echo_intervalif args.local_rank == 0:logging.info("[Train Step] Step:{:10d}  Loss:{:8.4f} | Time/Batch: {:6.4f}s",step, loss_avg, time_p_step,)last_time = time.time()# save checkpointengine.save_checkpoint("./data/checkpoints/MyClassifier/")

最后~

码字不易~~

独乐不如众乐~~

如有帮助,欢迎点赞+收藏~~


相关文章:

大模型训练框架DeepSpeed使用入门(1): 训练设置

文章目录 一、安装二、训练设置Step1 第一步参数解析Step2 初始化后端Step3 训练初始化 三、训练代码展示 官方文档直接抄过来,留个笔记。 https://deepspeed.readthedocs.io/en/latest/initialize.html 使用案例来自: https://github.com/OvJat/DeepSp…...

自定义类型——结构体、枚举和联合

自定义类型——结构体、枚举和联合 结构体结构体的声明匿名结构体结构体的自引用结构体的初始化结构体的内存对齐修改默认对齐数结构体传参 位段枚举联合 结构体 结构是一些值的集合,这些值被称为成员变量,结构的每个成员可以是不同类型的变量。 数组是…...

Windows11系统安装Mysql8之后,启动服务net start mysql报错“服务没有响应控制功能”的解决办法

问题 系统环境:Windows11 数据库版本:Mysql8 双击安装,一路下一步,完成,很顺利,但是开启服务后 net start mysql 报错: 服务没有响应控制功能。 请键入 NET HELPMSG 2186 以获得更多的帮助 不…...

WIFI模块的AT指令联网数据交互--第十天

1.1.蓝牙,ESP-01s,Zigbee, NB-Iot等通信模块都是基于AT指令的设计 初始配置和验证 ESP-01s出厂波特率正常是115200, 注意:AT指令,控制类都要加回车,数据传输时不加回车 1.2.上电后,通过串口输出一串系统…...

设计模式Java实现-迭代器模式

✨这里是第七人格的博客✨小七,欢迎您的到来~✨ 🍅系列专栏:设计模式🍅 ✈️本篇内容: 迭代器模式✈️ 🍱 本篇收录完整代码地址:https://gitee.com/diqirenge/design-pattern 🍱 楔子 很久…...

单页源码加密屋zip文件加密API源码

简介: 单页源码加密屋zip文件加密API源码 api源码里面的参数已改好,往服务器或主机一丢就行,出现不能加密了就是加密次数达到上限了,告诉我在到后台修改加密次数 点击下载...

47.全排列

1.题目 47. 全排列 II - 力扣&#xff08;LeetCode&#xff09;https://leetcode.cn/problems/permutations-ii/description/ 2.思路 注意剪枝的条件 3.代码 class Solution {vector<int> path;vector<vector<int>> ret;bool check[9]; public:vector<…...

呼叫中心系统选pscc好还是okcc好

选择PSCC&#xff08;商业软件呼叫中心&#xff09;还是OKCC&#xff08;开源呼叫中心&#xff09;&#xff0c;应基于以下几个关键因素来决定&#xff1a; 技术能力&#xff1a;如果企业拥有或愿意投入资源培养内部技术团队&#xff0c;开源解决方案可能更合适&#xff0c;因为…...

【SRC实战】前端脱敏信息泄露

挖个洞先 https://mp.weixin.qq.com/s/xnCQQCAneT21vYH8Q3OCpw “ 以下漏洞均为实验靶场&#xff0c;如有雷同&#xff0c;纯属巧合 ” 01 — 漏洞证明 一、前端脱敏&#xff0c;请求包泄露明文 “ 前端脱敏处理&#xff0c;请求包是否存在泄露&#xff1f; ” 1、获取验…...

区块链 | NFT 水印:Review on Watermarking Techniques(三)

&#x1f34d;原文&#xff1a;Review on Watermarking Techniques Aiming Authentication of Digital Image Artistic Works Minted as NFTs into Blockchains 一个 NFT 的水印认证协议 可以引入第三方实体来实现对交易的认证&#xff0c;即通过使用 R S A \mathsf{RSA} RSA…...

初识C语言——第十九天

for循环 1.简单概述 2.执行流程 3.建议事项&#xff1a;...

软件需求工程习题

1.&#xff08;面谈&#xff09;是需求获取活动中发生的需求工程师和用户间面对面的会见。 2.使用原型法进行需求获取&#xff0c;&#xff08;演化式&#xff09;原型必须具有健壮性&#xff0c;代码质量要从一开始就能达到最终系统的要求 3.利用面谈进行需求获取时&#xf…...

Win10弹出这个:https://logincdn.msauth.ne

问题描述&#xff1a; Win10脚本错误 Windows10家庭版操作系统开机后弹出这个 https://logincdn.msauth.net/shared/1.0/content/js/ConvergedLogin_PCore_vi321_9jVworKN8EONYo0A2.js 解决方法&#xff1a; 重启计算机后手动关闭第三方安全优化软件&#xff0c;然后在任务管理…...

Vue2 动态路由

VUE CLI 项目 router.js import Vue from "vue"; import Router from "vue-router"; import base from "/view/404/404.vue";const originalPush Router.prototype.push Router.prototype.push function push (location) {return originalPu…...

LeetCode746:使用最小花费爬楼梯

题目描述 给你一个整数数组 cost &#xff0c;其中 cost[i] 是从楼梯第 i 个台阶向上爬需要支付的费用。一旦你支付此费用&#xff0c;即可选择向上爬一个或者两个台阶。 你可以选择从下标为 0 或下标为 1 的台阶开始爬楼梯。 请你计算并返回达到楼梯顶部的最低花费。 代码 …...

DockerFile介绍与使用

一、DockerFile介绍 大家好&#xff0c;今天给大家分享一下关于 DockerFile 的介绍与使用&#xff0c;DockerFile 是一个用于定义如何构建 Docker 镜像的文本文件&#xff0c;具体来说&#xff0c;具有以下重要作用&#xff1a; 标准化构建&#xff1a;提供了一种统一、可重复…...

Java基础知识(六) 字符串

六 字符串 6.1 String字符串 1、String类对象创建 定义String类对象格式&#xff1a;** 1&#xff09;String 字符串变量名“字符串常量”&#xff1b; 2&#xff09;String 字符串变量名new String(字符串常量); 3&#xff09;String 字符串变量名; 字符串变量名“字符串常…...

为什么跨境电商大佬都在自养号测评?看完你就懂了!

在跨境电商的激烈竞争中&#xff0c;各大平台如亚马逊、拼多多Temu、shopee、Lazada、wish、速卖通、煤炉、敦煌、独立站、雅虎、eBay、TikTok、Newegg、Allegro、乐天、美客多、阿里国际、沃尔玛、Nike、OZON、Target以及Joom等&#xff0c;纷纷成为商家们竞相角逐市场份额的焦…...

AtCoder Beginner Contest 353

A 题意&#xff1a;检查是否有比第一个数大的数 #include<bits/stdc.h>using namespace std;int main() {int n;cin>>n;int a;cin>>a;int f0;for(int i2;i<n;i){int k;cin>>k;if(k>a){cout<<i<<endl;f1;break;}}if(f0){cout<&l…...

深度解读《深度探索C++对象模型》之虚继承的实现分析和效率评测(一)

目录 前言 具有虚基类的对象的构造过程 通过子类的对象存取虚基类成员的实现分析 接下来我将持续更新“深度解读《深度探索C对象模型》”系列&#xff0c;敬请期待&#xff0c;欢迎左下角点击关注&#xff01;也可以关注公众号&#xff1a;iShare爱分享&#xff0c;或文章末…...

UDP(Echoserver)

网络命令 Ping 命令 检测网络是否连通 使用方法: ping -c 次数 网址ping -c 3 www.baidu.comnetstat 命令 netstat 是一个用来查看网络状态的重要工具. 语法&#xff1a;netstat [选项] 功能&#xff1a;查看网络状态 常用选项&#xff1a; n 拒绝显示别名&#…...

【机器视觉】单目测距——运动结构恢复

ps&#xff1a;图是随便找的&#xff0c;为了凑个封面 前言 在前面对光流法进行进一步改进&#xff0c;希望将2D光流推广至3D场景流时&#xff0c;发现2D转3D过程中存在尺度歧义问题&#xff0c;需要补全摄像头拍摄图像中缺失的深度信息&#xff0c;否则解空间不收敛&#xf…...

Java-41 深入浅出 Spring - 声明式事务的支持 事务配置 XML模式 XML+注解模式

点一下关注吧&#xff01;&#xff01;&#xff01;非常感谢&#xff01;&#xff01;持续更新&#xff01;&#xff01;&#xff01; &#x1f680; AI篇持续更新中&#xff01;&#xff08;长期更新&#xff09; 目前2025年06月05日更新到&#xff1a; AI炼丹日志-28 - Aud…...

【HTML-16】深入理解HTML中的块元素与行内元素

HTML元素根据其显示特性可以分为两大类&#xff1a;块元素(Block-level Elements)和行内元素(Inline Elements)。理解这两者的区别对于构建良好的网页布局至关重要。本文将全面解析这两种元素的特性、区别以及实际应用场景。 1. 块元素(Block-level Elements) 1.1 基本特性 …...

音视频——I2S 协议详解

I2S 协议详解 I2S (Inter-IC Sound) 协议是一种串行总线协议&#xff0c;专门用于在数字音频设备之间传输数字音频数据。它由飞利浦&#xff08;Philips&#xff09;公司开发&#xff0c;以其简单、高效和广泛的兼容性而闻名。 1. 信号线 I2S 协议通常使用三根或四根信号线&a…...

怎么让Comfyui导出的图像不包含工作流信息,

为了数据安全&#xff0c;让Comfyui导出的图像不包含工作流信息&#xff0c;导出的图像就不会拖到comfyui中加载出来工作流。 ComfyUI的目录下node.py 直接移除 pnginfo&#xff08;推荐&#xff09;​​ 在 save_images 方法中&#xff0c;​​删除或注释掉所有与 metadata …...

Python 训练营打卡 Day 47

注意力热力图可视化 在day 46代码的基础上&#xff0c;对比不同卷积层热力图可视化的结果 import torch import torch.nn as nn import torch.optim as optim from torchvision import datasets, transforms from torch.utils.data import DataLoader import matplotlib.pypl…...

Java求职者面试指南:Spring、Spring Boot、Spring MVC与MyBatis技术解析

Java求职者面试指南&#xff1a;Spring、Spring Boot、Spring MVC与MyBatis技术解析 一、第一轮基础概念问题 1. Spring框架的核心容器是什么&#xff1f;它的作用是什么&#xff1f; Spring框架的核心容器是IoC&#xff08;控制反转&#xff09;容器。它的主要作用是管理对…...

规则与人性的天平——由高考迟到事件引发的思考

当那位身着校服的考生在考场关闭1分钟后狂奔而至&#xff0c;他涨红的脸上写满绝望。铁门内秒针划过的弧度&#xff0c;成为改变人生的残酷抛物线。家长声嘶力竭的哀求与考务人员机械的"这是规定"&#xff0c;构成当代中国教育最尖锐的隐喻。 一、刚性规则的必要性 …...

STM32标准库-ADC数模转换器

文章目录 一、ADC1.1简介1. 2逐次逼近型ADC1.3ADC框图1.4ADC基本结构1.4.1 信号 “上车点”&#xff1a;输入模块&#xff08;GPIO、温度、V_REFINT&#xff09;1.4.2 信号 “调度站”&#xff1a;多路开关1.4.3 信号 “加工厂”&#xff1a;ADC 转换器&#xff08;规则组 注入…...