以MixtralForCausalLM为例,演示如何不依赖框架实现pipeline并行

本文主要是介绍以MixtralForCausalLM为例,演示如何不依赖框架实现pipeline并行,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

以MixtralForCausalLM为例,演示如何不依赖框架实现pipeline并行

  • 1.创建Mixtral-8x7B配置文件
  • 2.测试代码

本文以MixtralForCausalLM为例,演示如何不依赖框架实现pipeline并行
主要步骤:

  • 1.分析网络结构,确定拆分规则:
    第一部分:embed_tokens+MixtralDecoderLayer[:8]
    第二部分:MixtralDecoderLayer[8:16]
    第三部分:MixtralDecoderLayer[16:24]
    第四部分:MixtralDecoderLayer[24:32]+norm+lm_head
  • 2.因为,MixtralDecoderLayer要求输入attention_mask,position_ids
    为此增加一个LayerAdapterModule,根据输入生成attention_mask,position_ids
  • 3.增加SubLayer把上面切分后的模块组装起来
  • 4.CPU上运行原始模型推理以及切分后模型的推理,确认结果一致
  • 5.GPU上4卡推理,每个rank算自己的那一部分,采用异步p2p,充分overlap,最后一个rank的输出为最终的输出

1.创建Mixtral-8x7B配置文件

tee ./config.json <<-'EOF'
{"architectures": ["MixtralForCausalLM"],"attention_dropout": 0.0,"bos_token_id": 1,"eos_token_id": 2,"hidden_act": "silu","hidden_size": 1024,"initializer_range": 0.02,"intermediate_size": 4096,"max_position_embeddings": 1024,"model_type": "mixtral","num_attention_heads": 32,"num_experts_per_tok": 2,"num_hidden_layers": 32,"num_key_value_heads": 8,"num_local_experts": 8,"output_router_logits": false,"rms_norm_eps": 1e-05,"rope_theta": 1000000.0,"router_aux_loss_coef": 0.02,"sliding_window": 128,"tie_word_embeddings": false,"torch_dtype": "bfloat16","transformers_version": "4.36.0.dev0","use_cache": true,"vocab_size": 32000
}
EOF

2.测试代码

tee open_model.py <<-'EOF'
import torch
import os
import numpy as np
import time
from accelerate import init_empty_weights
import json
import torch.distributed as dist
from collections import OrderedDict
from safetensors import safe_open
from safetensors.torch import save_file, load_file
from transformers import MixtralForCausalLM, MixtralConfig
from transformers.models.mixtral.modeling_mixtral import MixtralDecoderLayer
from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
from thop import profile
np.set_printoptions(precision=3)class EmptyModule(torch.nn.Module):'''用于tensor切分'''def __init__(self):super(EmptyModule, self).__init__()passdef forward(self,x,*args):return x[0]class LayerAdapterModule(torch.nn.Module):'''为每一个子图的输入生成attention_mask和position_ids'''def __init__(self,config):super(LayerAdapterModule, self).__init__()self.config=configdef forward(self,x):past_key_values_length = 0batch_size, seq_length,_ = x.shapeposition_ids = torch.arange(past_key_values_length, seq_length + past_key_values_length, dtype=torch.long)position_ids = position_ids.unsqueeze(0).view(-1, seq_length)attention_mask = _prepare_4d_causal_attention_mask(None,(batch_size, seq_length),x,past_key_values_length,sliding_window=self.config.sliding_window)return (x,attention_mask.to(x.device),position_ids.to(x.device))class SubLayer(torch.nn.Module):'''每一个rank计算的子图'''def __init__(self,pre=None,adapter=None,layers=None):super(SubLayer, self).__init__()self.config=configself.pre=preself.adapter=adapterself.layers=torch.nn.ModuleList(layers)def forward(self,x):if self.pre:x=self.pre(x)if self.adapter:x,attention_mask,position_ids=self.adapter(x)for layer in self.layers:if isinstance(layer,MixtralDecoderLayer):x=layer(x,attention_mask,position_ids)else:x=layer(x)return x# 1.模型初始化
config=MixtralConfig.from_pretrained("./config.json")
with init_empty_weights():model = MixtralForCausalLM(config).half()buffer_dict = {}
for name, param in model.named_buffers():buffer_dict[name] = param.clone()with open("Mixtral-8x7B/model.safetensors.index.json", "r") as file:index_data = json.load(file)weight_files = index_data.get('weight_map', [])
state_dict = {}
for k,v in weight_files.items():weights_path = os.path.join("Mixtral-8x7B", v)with safe_open(weights_path, framework="pt") as f:for k in f.keys():state_dict[k] = f.get_tensor(k)model=model.to_empty(device="cpu")
model.load_state_dict(state_dict, strict=True)
for name, param in model.named_buffers():param.copy_(buffer_dict[name])model=model.float()# 2.生成输入
torch.manual_seed(2)
example_input=torch.randint(0,32000,(1,128)).to("cpu")# 3.将模型切分成4块
divided=[]
block_size=len(model.model.layers)//4  
offset=0submodules=[]
for i,m in enumerate(model.model.layers[:block_size]):submodules.append(m)submodules.append(EmptyModule())
divided.append(SubLayer(model.model.embed_tokens,LayerAdapterModule(config),submodules))
offset+=block_sizesubmodules=[]
for i,m in enumerate(model.model.layers[offset:offset+block_size]):submodules.append(m)submodules.append(EmptyModule())
divided.append(SubLayer(None,LayerAdapterModule(config),submodules))
offset+=block_sizesubmodules=[]
for i,m in enumerate(model.model.layers[offset:offset+block_size]):submodules.append(m)submodules.append(EmptyModule())
divided.append(SubLayer(None,LayerAdapterModule(config),submodules))
offset+=block_sizesubmodules=[]
for i,m in enumerate(model.model.layers[offset:]):submodules.append(m)submodules.append(EmptyModule())
submodules.append(model.model.norm)
submodules.append(model.lm_head)
divided.append(SubLayer(None,LayerAdapterModule(config),submodules))# 4.初始化分布式环境
dist.init_process_group(backend='nccl')
world_size = torch.distributed.get_world_size()
rank=torch.distributed.get_rank()
local_rank=int(os.environ['LOCAL_RANK'])# 5.运行CPU上的推理
if local_rank==world_size-1:output=model(example_input)output=output.logits.detach().reshape(-1).cpu().numpy()[:8]print("baseline:",output)for i in range(4):submodule=divided[i].float().to("cpu")example_input=submodule(example_input)dump=example_input.detach().reshape(-1).cpu().numpy()[:8]output=example_input.detach().reshape(-1).cpu().numpy()[:8]print("by layer:",output)torch.cuda.set_device(local_rank)
device=f"cuda:{local_rank}"example_input=example_input.to(device)
submodule=divided[local_rank].half().to(device)# 6.运行设备上的推理及吞吐测试
sreq=None
ts=[]
dist.barrier()epoch=64
t0=time.time()
for epoch in range(epoch):if sreq is not None and not sreq.is_completed():sreq.wait()sreq=Noneif local_rank!=0:tensor_size = torch.empty((3,), dtype=torch.int64).to(device)torch.distributed.recv(tensor_size,local_rank-1)example_input = torch.empty(tensor_size.tolist()).to(device).half()torch.distributed.recv(example_input,local_rank-1)        else:torch.manual_seed(1)    output=submodule(example_input)if epoch==0:flops, params = profile(submodule, inputs=(example_input,))print(f"{rank} 模型的FLOPs: {flops:,} 模型的参数量: {params:,}")  if local_rank<world_size-1:        tensor_size = torch.tensor(output.size(), dtype=torch.int64).to(device)torch.distributed.isend(tensor_size,local_rank+1)sreq=torch.distributed.isend(output,local_rank+1)#torch.distributed.send(output,local_rank+1)elif local_rank==world_size-1:ts.append(time.time())dist.barrier()
t1=time.time()time.sleep(0.2*local_rank)
if local_rank==world_size-1:ts=ts[len(ts)//2:]print("latency:{:.2f} qps0:{:.2f} qps1:{:.2f}".format(ts[1]-ts[0],len(ts)/(ts[-1]-ts[0]),epoch/(t1-t0)))output=output.detach().reshape(-1).cpu().numpy()[:8]print(output)
EOF
python -m torch.distributed.run --nnodes=1 --nproc_per_node=4  open_model.py

这篇关于以MixtralForCausalLM为例,演示如何不依赖框架实现pipeline并行的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1071439

相关文章

使用animation.css库快速实现CSS3旋转动画效果

《使用animation.css库快速实现CSS3旋转动画效果》随着Web技术的不断发展,动画效果已经成为了网页设计中不可或缺的一部分,本文将深入探讨animation.css的工作原理,如何使用以及... 目录1. css3动画技术简介2. animation.css库介绍2.1 animation.cs

Java进行日期解析与格式化的实现代码

《Java进行日期解析与格式化的实现代码》使用Java搭配ApacheCommonsLang3和Natty库,可以实现灵活高效的日期解析与格式化,本文将通过相关示例为大家讲讲具体的实践操作,需要的可以... 目录一、背景二、依赖介绍1. Apache Commons Lang32. Natty三、核心实现代

SpringBoot实现接口数据加解密的三种实战方案

《SpringBoot实现接口数据加解密的三种实战方案》在金融支付、用户隐私信息传输等场景中,接口数据若以明文传输,极易被中间人攻击窃取,SpringBoot提供了多种优雅的加解密实现方案,本文将从原... 目录一、为什么需要接口数据加解密?二、核心加解密算法选择1. 对称加密(AES)2. 非对称加密(R

基于Go语言实现Base62编码的三种方式以及对比分析

《基于Go语言实现Base62编码的三种方式以及对比分析》Base62编码是一种在字符编码中使用62个字符的编码方式,在计算机科学中,,Go语言是一种静态类型、编译型语言,它由Google开发并开源,... 目录一、标准库现状与解决方案1. 标准库对比表2. 解决方案完整实现代码(含边界处理)二、关键实现细

python通过curl实现访问deepseek的API

《python通过curl实现访问deepseek的API》这篇文章主要为大家详细介绍了python如何通过curl实现访问deepseek的API,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编... API申请和充值下面是deepeek的API网站https://platform.deepsee

SpringBoot实现二维码生成的详细步骤与完整代码

《SpringBoot实现二维码生成的详细步骤与完整代码》如今,二维码的应用场景非常广泛,从支付到信息分享,二维码都扮演着重要角色,SpringBoot是一个非常流行的Java基于Spring框架的微... 目录一、环境搭建二、创建 Spring Boot 项目三、引入二维码生成依赖四、编写二维码生成代码五

MyBatisX逆向工程的实现示例

《MyBatisX逆向工程的实现示例》本文主要介绍了MyBatisX逆向工程的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录逆向工程准备好数据库、表安装MyBATisX插件项目连接数据库引入依赖pom.XML生成实体类、

C#实现查找并删除PDF中的空白页面

《C#实现查找并删除PDF中的空白页面》PDF文件中的空白页并不少见,因为它们有可能是作者有意留下的,也有可能是在处理文档时不小心添加的,下面我们来看看如何使用Spire.PDFfor.NET通过C#... 目录安装 Spire.PDF for .NETC# 查找并删除 PDF 文档中的空白页C# 添加与删

Java实现MinIO文件上传的加解密操作

《Java实现MinIO文件上传的加解密操作》在云存储场景中,数据安全是核心需求之一,MinIO作为高性能对象存储服务,支持通过客户端加密(CSE)在数据上传前完成加密,下面我们来看看如何通过Java... 目录一、背景与需求二、技术选型与原理1. 加密方案对比2. 核心算法选择三、完整代码实现1. 加密上

Java使用WebView实现桌面程序的技术指南

《Java使用WebView实现桌面程序的技术指南》在现代软件开发中,许多应用需要在桌面程序中嵌入Web页面,例如,你可能需要在Java桌面应用中嵌入一部分Web前端,或者加载一个HTML5界面以增强... 目录1、简述2、WebView 特点3、搭建 WebView 示例3.1 添加 JavaFX 依赖3