DeepSeek-V3的MoE架构与MLA机制
DeepSeek-V3是总参数671B、每token激活37B的MoE语言模型,采用多头潜在注意力与DeepSeekMoE架构,其公开实现仍以朴素注意力计算和逐专家循环为主,留有优化空间。
Copyright 2025 HuggingFace Team. 全权保留. 根据 Apache 许可, 版本 2.0 (“ License ”) 获得许可; 您不能使用此文件, 除非符合 您可在下列地点获得许可证副本: http://www.apache.org/licenses/LICENSE-2.0 除非适用法律要求或书面同意,否则根据许可证分发的软件在下列网址分发: a " :ASIS"BASIS,WITHOUTWARRANTIESORCONDITIONSOFANYKIND,或明示的或暗示的。 《许可证》规定的许可和限制的具体语言。 QQ 注意, 此文件在 Markdown 中, 但包含我们doc- buildinger( 类似于 MDX ) 的特定语法, 可能不是 在您的Markdown 查看器中正确渲染。 *这个模型发表在HF关于2024的论文中 - 12 - 27,并在2025上为Hugging Face Transformers作出贡献 - 03 - 28.* # DeepSeek-V3 ## 概览 DeepSeek-V3型号是在下列年份提出的: [DeepSeek-V3 技术报告](https://huggingface.co/papers/2412.19437) 由 DeepSeek 编辑 。AI团队。 本文的抽象内容如下: 我们提出DeepSeek-V3,是一种强大的专家混合(MoE)语言模型,其总参数为671B,每个符号都激活了37B. 为了实现高效的推论和成本效益高的培训,DeepSeek-V3采用了多头Latent 注意(MLA)和DeepSeekMoE架构,并在DeepSeek-V2中进行了彻底验证.此外,DeepSeek-V3还开创了载荷平衡的auxiliary-loss-free策略,并设定了增强性能的多键预测训练目标. 我们预先在14.8 万亿多元和优质的标志上训练DeepSeek-V3,随后是监督的精益求精和强化学习阶段,以充分利用其能力.全面评价显示,DeepSeek-V3超越了其他开源模式,并实现了与领先的闭源模式相当的性能. DeepSeek-V3尽管性能优异,但其全程训练只需要2.788M H800 GPU小时,此外,其训练过程也非常稳定.在整个培训过程中,我们没有遇到任何无法弥补的损失高峰,也没有出现任何退缩。 模拟检查站位于https://github.com/deepseek-ai/DeepSeek-V3。 > [!TIP] > 设定 `use_kernels=True` 输入 [`~PreTrainedModel.from_pretrained`] 将支持的层替换为 Hub 的优化内核。请参考 [正在装入内核](<https://github.com/huggingface/transformers/blob/HEAD/docs/source/en/kernel_doc/loading_kernels>) 来学习更多。 ## 限制和呼吁捐款! 我们非常乐意让这个代码成为社区动力, 并想看看你如何能最好地优化以下内容: - 当前执行使用“ naive” 注意计算( 所以实际上不是 MLA ) - 当前执行环路通过专家。应该替换此环路。指针要使用 `get_packed_weights` 从 `integrations/tensor_parallel`. - 当前执行使用 ROPE 的 eleuther 公式, 使用原来的公式会更有效率 ! ( 仍然应该遵循我们的 API ) - 不支持静态缓存( 这应该只是一代配置问题 / 配置形状问题) ### 用法提示 该模型使用多头Lateent Record(MLA)和DeepSeekMoE架构来进行高效推论和成本效益高的培训,它采用auxiliary-loss-free策略来进行负载平衡和多键预测培训目标,该模型在经过14.8万亿令牌的预训后,可以用于各种语言任务,并经过监督的精细化和强化的学习阶段. 你可以运行的模型 `FP8` 自动,使用2节点的8 H100应该足够多! ```python # `run_deepseek_v1.py` import torch from transformers import AutoModelForCausalLM, AutoTokenizer torch.manual_seed(30) tokenizer = AutoTokenizer.from_pretrained("deepseek-r1") chat = [ {"role": "user", "content": "Hello, how are you?"}, {"role": "assistant", "content": "I'm doing great. How can I help you today?"}, {"role": "user", "content": "I'd like to show off how chat templating works!"}, ] model = AutoModelForCausalLM.from_pretrained("deepseek-r1", device_map="auto") inputs = tokenizer.apply_chat_template(chat, tokenize=True, add_generation_prompt=True, return_tensors="pt").to(model.device) import time start = time.time() outputs = model.generate(inputs, max_new_tokens=50) print(tokenizer.batch_decode(outputs)) print(time.time()-start) ``` 由此产生了: ``````text <|Assistant|><think> Okay, the user wants to demonstrate how chat templating works. Let me break down what that means. Chat templating is about structuring the conversation data, especially for models that need specific input formats. Maybe they're referring to something like how messages are formatted with roles (user, assistant, system) in APIs like OpenAI. First, I should explain what chat templating is. It's the process of formatting conversation data into a structured format that the model can understand. This usually includes roles and content. For example, user messages, assistant responses, and system messages each have their own role tags. They might want an example. Let me think of a simple conversation. The user says "Hello, how are you?" and the assistant responds "I'm doing great. How can I help you today?" Then the user follows up with wanting to show off chat templating. So the example should include the history and the new message. In some frameworks, like Hugging Face's Transformers, chat templates are applied using Jinja2 templates. The template might look something like combining system messages, then looping through user and assistant messages with appropriate tags. For instance, using {% for message in messages %} and assigning roles like <|user|>, <|assistant|>, etc. I should structure the example with the messages array, showing each role and content. Then apply a hypothetical template to convert that into a formatted string the model uses. Also, mention that different models have different templating requirements, like using special tokens or varying role labels. Wait, the user mentioned "chat templating" in the context of showing off. Maybe they want a practical example they can present. So providing a code snippet or a structured data example would be helpful. Let me outline a typical messages array and then the templated output. Also, it's important to note that proper templating ensures the model knows the conversation flow, which is crucial for generating coherent responses. Maybe include a note about why it's important, like maintaining context and role-specific processing. Let me check if there are any common mistakes or things to avoid. For example, not closing tags properly, or mismatching roles. But maybe that's too detailed unless the user asks. Focus on the positive example first. Putting it all together, the response should have an example messages array, the applied template, and the final formatted string. Maybe use angle brackets or special tokens as placeholders. Also, mention that this helps in training or fine-tuning models with structured data. I think that's a solid approach. Let me structure it step by step to make it clear. </think> Chat templating is a way to structure conversation data (e.g., user/assistant interactions) into a format that language models understand. This is especially important for models trained to handle multi-turn dialogues, where the input must explicitly separate roles (user, assistant, system, etc.) and messages. Let’s break this down with an example! --- ### **Step 1: Raw Conversation History** Suppose we have this conversation: - **User**: "Hello, how are you?" - **Assistant**: "I'm doing great. How can I help you today?" - **User**: "I'd like to show off how chat templating works!" --- ### **Step 2: Structured Messages** In frameworks like Hugging Face Transformers or OpenAI, conversations are often formatted as a list of dictionaries with `role` and `content`: ```python messages = [ {"role": "user", "content": "Hello, how are you?"}, {"role": "assistant", "content": "I'm doing great. How can I help you today?"}, {"role": "user", "content": "I'd like to show off how chat templating works!"}, ] ``` --- ### **Step 3: Apply a Chat Template** A **chat template** converts this structured data into a single string formatted for the model. For example, using a Jinja-style template (common in Hugging Face): ```jinja {% for message in messages %} {% if message['role'] == 'user' %} <|user|>{{ message['content'] }}<|end|> {% elif message['role'] == 'assistant' %} <|assistant|>{{ message['content'] }}<|end|> {% endif %} {% endfor %} <|assistant|> ``` --- ### **Step 4: Final Templated Output** Applying the template to our `messages` list would produce: ```text <|user|>Hello, how are you?<|end|> <|assistant|>I'm doing great. How can I help you today?<|end|> <|user|>I'd like to show off how chat templating works!<|end|> <|assistant|> ``` This tells the model: 1. The conversation history (user/assistant turns). 2. The model's turn to generate a response (`<|assistant|>` at the end). --- ### **Key Notes**: - **Role Separation**: Tags like `<|user|>` and `<|assistant|>` help the model distinguish speakers. - **Special Tokens**: Models often use unique tokens (e.g., `<|end|>`) to mark message boundaries. - **Flexibility**: Templates vary by model (e.g., OpenAI uses `{"role": "user", "content": "..."}` instead of tags). --- ### **Why This Matters**: - **Consistency**: Ensures the model understands dialogue structure. - **Context Preservation**: Maintains the flow of multi-turn conversations. - **Alignment**: Matches the format the model was trained on for better performance. Want to dive deeper or see a specific framework’s implementation (e.g., OpenAI, Llama, Mistral)? Let me know! 😊<|end▁of▁sentence|> `````` 用以下操作它 ```bash torchrun --nproc_per_node=8 --nnodes=2 --node_rank=0|1 --rdzv-id an_id --rdzv-backend c10d --rdzv-endpoint master_addr:master_port run_deepseek_r1.py ``` 如果有的话: ```bash [rank0]: ncclInternalError: Internal check failed. [rank0]: Last error: [rank0]: Bootstrap : no socket interface found ``` 错误,这意味着NCCL很可能没有被装入. ## DeepseekV3Config [[自动doc]] DeepseekV3Config ## DeepseekV3Model [[自动doc]] DeepseekV3Model - 转发 ## DeepseekV3ForCausalLM [[自动doc]] DeepseekV3ForCausalLM - 转发 ## DeepseekV3ForSequenceClassification [[自动doc]] DeepseekV3ForSequenceClassification - 转发 ## DeepseekV3ForTokenClassification [[自动doc]] DeepseekV3ForTokenClassification - 转发
查看原始来源