以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

相关文章

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

如何通过Python实现一个消息队列

《如何通过Python实现一个消息队列》这篇文章主要为大家详细介绍了如何通过Python实现一个简单的消息队列,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录如何通过 python 实现消息队列如何把 http 请求放在队列中执行1. 使用 queue.Queue 和 reque

Python如何实现PDF隐私信息检测

《Python如何实现PDF隐私信息检测》随着越来越多的个人信息以电子形式存储和传输,确保这些信息的安全至关重要,本文将介绍如何使用Python检测PDF文件中的隐私信息,需要的可以参考下... 目录项目背景技术栈代码解析功能说明运行结php果在当今,数据隐私保护变得尤为重要。随着越来越多的个人信息以电子形

使用 sql-research-assistant进行 SQL 数据库研究的实战指南(代码实现演示)

《使用sql-research-assistant进行SQL数据库研究的实战指南(代码实现演示)》本文介绍了sql-research-assistant工具,该工具基于LangChain框架,集... 目录技术背景介绍核心原理解析代码实现演示安装和配置项目集成LangSmith 配置(可选)启动服务应用场景

使用Python快速实现链接转word文档

《使用Python快速实现链接转word文档》这篇文章主要为大家详细介绍了如何使用Python快速实现链接转word文档功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 演示代码展示from newspaper import Articlefrom docx import

前端原生js实现拖拽排课效果实例

《前端原生js实现拖拽排课效果实例》:本文主要介绍如何实现一个简单的课程表拖拽功能,通过HTML、CSS和JavaScript的配合,我们实现了课程项的拖拽、放置和显示功能,文中通过实例代码介绍的... 目录1. 效果展示2. 效果分析2.1 关键点2.2 实现方法3. 代码实现3.1 html部分3.2