本文主要是介绍以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并行的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!