首页 > 其他分享 >LLM面面观之MoE

LLM面面观之MoE

时间:2024-04-02 09:33:54浏览次数:20  
标签:dim self 面面观 states LLM hidden MoE size

1. 背景

根据本qiang~最新的趋势观察,基于MoE架构的开源大模型越来越多,比如马斯克的Grok-1(314B), Qwen1.5-MoE-A2.7B等,因此想探究一下MoE里面的部分细节。

此文是本qiang~针对大语言模型的MoE的整理,包括原理、流程及部分源码。

2. MoE原理

MoE的流行源于”欧洲的OpenAI” Mistral AI发布的论文及模型《Mixtral of Experts》,评测集上的效果吊打众多开源模型,如Llama 2 70B和GPT3.5。

《Mixtral of Experts》基础模型使用的是Mistral AI自研的Mistral 7B,该模型的特点包括:滑窗注意力(Sliding Window Aattention), 滚动缓冲区缓存(Rolling Buffer Cache)以及预填充-分块(Pre-fill and Chunking),具体细节可以查阅文末的论文地址。

本文以《Mixtral of Experts》为引子,探究MoE的相关细节,MoE的原理如下图所示:

 

 

图2.1 MoE的原理 

(1) Transformers架构中的每一层中的FFN网络均替换为了8个FFN(专家),且由一个网关路由(gate router)进行控制

(2) 针对每一个token,每一层的网关路由仅选择其中的2个FFN(专家)来处理当前状态并进行加权输出

(3) 结果就是,每一个token访问了47B参数,但是在推理阶段仅仅使用了13B的激活参数(即,只使用2个专家,冻结其他6个专家)。

(4) 与Dropout机制对比,Dropout让部分神经元失活,而MoE是让部分专家失活。

3. 源码

本qiang~研读并尝试执行了Mistral官网的github推理代码,该代码框架非常适合新手,无他,只因其几乎只是在torch上层做的封装,很少引擎其他第三方库,不像transformers,功能强大,但不适合新手研读代码…

为了普适性,下面的代码截取了transformers框架中的代码。

首先看下通用Transformers中FFN中的代码模块,代码位置在transformers.models.mistral.modeling_mistral, 主要流程是:

(1) 先经过gate_proj和up_proj的2个[hidden_size, intermediate_size]的线性转换

(2) 使用激活函数对gate_proj进行激活

(3) 二者的内积再经过down_proj线性转换。

 1 class MistralMLP(nn.Module):
 2     def __init__(self, config):
 3         super().__init__()
 4         self.config = config
 5         self.hidden_size = config.hidden_size
 6         self.intermediate_size = config.intermediate_size
 7         self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
 8         self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
 9         self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
10         self.act_fn = ACT2FN[config.hidden_act]
11 
12     def forward(self, x):
13         return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))

 再来看下MoE中的专家模块,代码位置在transformers.models.mixtral.modeling_mixtral,主要流程是:

(1) 首先经过网关路由self.gate

(2) 然后选择其中2个专家,并归一化

(3) 之后遍历每个专家网络,并按照expert_mask进行筛选

(4) 如果expert_mask有值,则选择指定部分的隐藏层进行FFN操作,且输出结果进行加权

(5) 最后原地增加先前初始化的最终结果变量final_hidden_states

class MixtralSparseMoeBlock(nn.Module):

    def __init__(self, config):
        super().__init__()
        self.hidden_dim = config.hidden_size
        self.ffn_dim = config.intermediate_size
        self.num_experts = config.num_local_experts
        self.top_k = config.num_experts_per_tok

        # gating
        self.gate = nn.Linear(self.hidden_dim, self.num_experts, bias=False)

        self.experts = nn.ModuleList([MixtralBlockSparseTop2MLP(config) for _ in range(self.num_experts)])

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        """ """
        batch_size, sequence_length, hidden_dim = hidden_states.shape
        hidden_states = hidden_states.view(-1, hidden_dim)
        # router_logits: (batch * sequence_length, n_experts)
        router_logits = self.gate(hidden_states)

        routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
        routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
        routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
        # we cast back to the input dtype
        routing_weights = routing_weights.to(hidden_states.dtype)

        final_hidden_states = torch.zeros(
            (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
        )

        # One hot encode the selected experts to create an expert mask
        # this will be used to easily index which expert is going to be sollicitated
        expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)

        # Loop over all available experts in the model and perform the computation on each expert
        for expert_idx in range(self.num_experts):
            expert_layer = self.experts[expert_idx]
            idx, top_x = torch.where(expert_mask[expert_idx])

            if top_x.shape[0] == 0:
                continue

            # in torch it is faster to index using lists than torch tensors
            top_x_list = top_x.tolist()
            idx_list = idx.tolist()

            # Index the correct hidden states and compute the expert hidden state for
            # the current expert. We need to make sure to multiply the output hidden
            # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
            current_state = hidden_states[None, top_x_list].reshape(-1, hidden_dim)
            current_hidden_states = expert_layer(current_state) * routing_weights[top_x_list, idx_list, None]

            # However `index_add_` only support torch tensors for indexing so we'll use
            # the `top_x` tensor here.
            final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
        final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
        return final_hidden_states, router_logits

 

其中MixtralBlockSparseTop2MLP代码如下,可以看到和传统MistralMLP内容完全一致。 

class MixtralBlockSparseTop2MLP(nn.Module):
    def __init__(self, config: MixtralConfig):
        super().__init__()
        self.ffn_dim = config.intermediate_size
        self.hidden_dim = config.hidden_size

        self.w1 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False)
        self.w2 = nn.Linear(self.ffn_dim, self.hidden_dim, bias=False)
        self.w3 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False)

        self.act_fn = ACT2FN[config.hidden_act]

    def forward(self, hidden_states):
        current_hidden_states = self.act_fn(self.w1(hidden_states)) * self.w3(hidden_states)
        current_hidden_states = self.w2(current_hidden_states)
        return current_hidden_states

 

4. MoE微调

由于MoE只是将每一层的FFN改变为了每一层的gate网关路由+8个FFN专家,且gate网关路由和8个专家内部均为线性运算,所以可以无缝地结合LoRA、QLoRA进行指令微调。

可以参考开源项目:https://github.com/yangjianxin1/Firefly

5. 答疑解惑

(1) 问:MoE 8*7B的模型是56B参数?

答:MoE 8*7B的参数量是47B,而不是56B,原因是每一层除了8个专家网络外,其他层均是复用的。

(2) 问:MoE的基础模型是Mistral 7B?

答:不是,MoE的模型架构与Mistral 7B相同,但其中的FFN替换为了8个FFN,且MoE是基于多语言数据集预训练而来的。

(3) MoE的稀疏性(sparse)体现在哪里?

答:在训练和推理时,同时只有两个专家网络会被激活,进行前向计算,其它专家网络处于失活状态。

6. 总结

一句话足矣~

本文主要针对大语言模型的MoE,包括原理及部分源码。

此外,建议大家可以针对源码进行运行,关于源码,欢迎大家一块交流。

7. 参考

(1) Mistral 7B:https://arxiv.org/pdf/2310.06825v1.pdf

(2) MoE: https://arxiv.org/pdf/2401.04088v1.pdf

(3) MoE开源指令微调框架Firefly: https://github.com/yangjianxin1/Firefly

 

标签:dim,self,面面观,states,LLM,hidden,MoE,size
From: https://www.cnblogs.com/mengrennwpu/p/18109871

相关文章

  • LLM RAG系列
    RAG系列本文介绍了RAG以及RAGpipeline的整个流程,包括请求转换、路由和请求构造、索引和检索、生成和评估等,其中引用了大量有价值的论文。参考AdvancedRAGSeries:GenerationandEvaluation中的5篇文章,并丰富了相关内容。请求转换请求转换是为了提高查询结果的准确性而对......
  • 书生浦语LLM全链路开源体系笔记
    书生浦语LLM全链路开源体系LLM介绍大模型LLM成为发展通用人工智能的重要途径。专用模型:针对特定人物,一个模型解决一个问题;通用大模型:一个模型应对多种任务、多种模态。书生浦语LLM发展历程及LM2InternLM->InternLM-7B开源+全链路开源工具体系->书生万卷1.0多模......
  • 大语言模型(LLM)
    大语言模型LLM人工智能ArtificialIntelligence一门研究如何使计算机能够模拟和执行人类智能任务的科学和技术领域是研究、开发用于模拟、延伸和扩展人的智能的理论、方法、技术及应用系统的一门新的技术科学。人工:计算机来模拟人智能:人的某些思维过程和智能行为(如学习、......
  • 使用MergeKit创建自己的专家混合模型:将多个模型组合成单个MoE
    由于Mixtral的发布,专家混合(MoE)架构在最近几个月变得流行起来。虽然Mixtral和其他MoE架构是从头开始预训练的,但最近出现了另一种创建MoE的方法:Arcee的MergeKit库可以通过集成几个预训练模型来创建moe。这些人通常被称为frankenMoEs或MoErges,以区别于预先训练的MoEs。在本文中,我......
  • LLMRec论文阅读笔记
    LLMRec论文阅读笔记Abstract​ 长期以来,数据稀疏性的问题一直是推荐系统中的一个挑战,以前的研究都试图通过合并侧边信息来解决这个问题。然而,这种方法经常会引入副作用,如噪声、可用性问题和低数据质量,这反过来会阻碍用户偏好的准确建模,并对推荐性能产生不利影响。鉴于大型语言模......
  • NVIDIA H200 创下 MLPerf LLM 最新推理记录
    NVIDIAH200TensorCoreGPU和NVIDIATensorRT-LLM创下MLPerfLLM最新推理记录生成式人工智能正在解锁新的计算应用程序,通过持续的模型创新来极大地增强人类的能力。生成式AI模型(包括大型语言模型(LLM))用于制作营销文案、编写计算机代码、渲染详细图像、创作音......
  • 7种RAG工具,让你的LLMs发挥最大效用
    公众号:Halo咯咯开源的检索增强型生成(RAG)模型随着对大型语言模型中增强功能需求的增长而变得越来越庞大。那它们是什么呢?RAG模型是密集检索(DPR)和序列到序列模型的结合。其设计目的是通过引入外部知识来增强LLMs的能力。这是通过检索与查询相关的文档,并使用这些文档来作为......
  • AI实用指南:5分钟搭建你自己的LLM聊天应用
    今天,我们将迅速着手搭建一个高效且富有创意的混元聊天应用,其核心理念可以用一个字来概括——快。在这个快节奏的时代,构建一个基础的LLM(LargeLanguageModel,大型语言模型)聊天应用并不需要耗费太多时间。市面上充斥着各种功能强大的大型语言模型,我们可以根据项目需求灵活选择,而今天......
  • Python中Keras微调Google Gemma:定制化指令增强大型语言模型LLM
    全文链接:https://tecdat.cn/?p=35476原文出处:拓端数据部落公众号像谷歌、Meta和Twitter这样的大公司正大力推动其大型语言模型(LLM)的开源。最近,谷歌DeepMind团队推出了Gemma——一个由与创建谷歌Gemini模型相同的研究和技术构建的轻量级、开源LLM系列。本文,我们将帮助客户了解Ge......
  • 使用TensorRT-LLM部署ChatGLM3
    说明:TensorRT-LLM是NVIDIA开发的高性能推理TensorRT-LLM是NVIDIA推出的一个专门用于编译和优化大语言模型推理的综合程序库。可在NVIDIAGPU上加速和优化最新的大语言模型(LLM)的推理性能。官网地址为:https://github.com/THUDM/ChatGLM3/blob/main/tensorrt_llm_demo/READ......