{"notes":[{"id":"deepseek/deepseek-v2","category":"deepseek","legacyPath":"deepseek/2405-deepseek-v2","legacySlug":"2405-deepseek-v2","legacyPaths":[],"title":"DeepSeek-V2","subtitle":"Cost-Effective Optimization","author":"Z. Yuan","paperDate":"2024-05-07","publishedOn":"2025-03-27","paperTitle":"DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model","paperUrl":"https://arxiv.org/abs/2405.04434v5","bibliography":{"title":"DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model","authors":["DeepSeek-AI"],"url":"https://arxiv.org/abs/2405.04434v5","pdfUrl":"https://arxiv.org/pdf/2405.04434v5","codeUrl":"https://github.com/deepseek-ai/DeepSeek-V2","preprint":{"id":"2405.04434","submittedOn":"2024-05-07","url":"https://arxiv.org/abs/2405.04434v5"},"publication":null,"citation":"@misc{deepseekdeepseekv22024,\n  title = {{DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model}},\n  author = {DeepSeek-AI},\n  year = {2024},\n  eprint = {2405.04434},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/2405.04434v5}\n}\n","citationPath":"/content/papers/citations/deepseek/deepseek-v2.2792b9f48a76.bib"},"thumbnail":{"src":"/content/papers/assets/0c5c924a685f79d8a0037fb9862aa1358d05058a19ab295c1b1983dae491355d.jpg","width":1224,"height":984},"locale":"en","path":"/content/papers/en/deepseek/deepseek-v2.1b15b1df97c5.md","headings":[{"id":"defining-the-problem","text":"Defining the Problem","depth":2},{"id":"solving-the-problem","text":"Solving the Problem","depth":2},{"id":"multi-head-latent-attention","text":"Multi-head Latent Attention","depth":3},{"id":"decoupling-rotary-position-embedding","text":"Decoupling Rotary Position Embedding","depth":3},{"id":"deepseekmoe","text":"DeepSeekMoE","depth":3},{"id":"auxiliary-balance-loss","text":"Auxiliary Balance Loss","depth":3},{"id":"training-strategy","text":"Training Strategy","depth":3},{"id":"model-alignment","text":"Model Alignment","depth":2},{"id":"discussion","text":"Discussion","depth":2},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"transformers/mixtral","relation":"background","topic":"Routing tokens to sparse experts"},{"id":"deepseek/deepseek-llm","relation":"background","topic":"DeepSeek language models and reasoning training"},{"id":"deepseek/deepseek-v3","relation":"next","topic":"DeepSeek language models and reasoning training"}]},{"id":"transformers/mixtral","category":"transformers","legacyPath":"","legacySlug":"","legacyPaths":[],"title":"Mixtral of Experts","subtitle":"Eight experts, two at work","author":"Z. Yuan","paperDate":"2024-01-08","publishedOn":"2026-10-14","paperTitle":"Mixtral of Experts","paperUrl":"https://arxiv.org/abs/2401.04088","bibliography":{"title":"Mixtral of Experts","authors":["Albert Q. Jiang","Alexandre Sablayrolles","Antoine Roux","Arthur Mensch","Blanche Savary","Chris Bamford","Devendra Singh Chaplot","Diego de las Casas","Emma Bou Hanna","Florian Bressand","Gianna Lengyel","Guillaume Bour","Guillaume Lample","Lélio Renard Lavaud","Lucile Saulnier","Marie-Anne Lachaux","Pierre Stock","Sandeep Subramanian","Sophia Yang","Szymon Antoniak","Teven Le Scao","Théophile Gervet","Thibaut Lavril","Thomas Wang","Timothée Lacroix","William El Sayed"],"url":"https://arxiv.org/abs/2401.04088","pdfUrl":"https://arxiv.org/pdf/2401.04088v1","codeUrl":"https://github.com/mistralai/mistral-inference","preprint":{"id":"2401.04088","submittedOn":"2024-01-08","url":"https://arxiv.org/abs/2401.04088"},"publication":null,"citation":"@misc{transformersmixtral2024,\n  title = {{Mixtral of Experts}},\n  author = {Albert Q. Jiang and Alexandre Sablayrolles and Antoine Roux and Arthur Mensch and Blanche Savary and Chris Bamford and Devendra Singh Chaplot and Diego de las Casas and Emma Bou Hanna and Florian Bressand and Gianna Lengyel and Guillaume Bour and Guillaume Lample and Lélio Renard Lavaud and Lucile Saulnier and Marie-Anne Lachaux and Pierre Stock and Sandeep Subramanian and Sophia Yang and Szymon Antoniak and Teven Le Scao and Théophile Gervet and Thibaut Lavril and Thomas Wang and Timothée Lacroix and William El Sayed},\n  year = {2024},\n  eprint = {2401.04088},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/2401.04088}\n}\n","citationPath":"/content/papers/citations/transformers/mixtral.2b2db338a9b5.bib"},"thumbnail":{"src":"/content/papers/assets/1347eb75040f1144f7ea5820cae7b4bd60c49b6bf351fb1c9e77b4c20e642c46.png","width":2116,"height":968},"locale":"en","path":"/content/papers/en/transformers/mixtral.6a2c1ecb31db.md","headings":[{"id":"defining-the-problem","text":"Defining the problem","depth":2},{"id":"first-picture-a-token-and-a-model-layer","text":"First, picture a token and a model layer","depth":3},{"id":"solving-the-problem","text":"Solving the problem","depth":2},{"id":"where-do-the-eight-experts-go","text":"Where do the eight experts go?","depth":3},{"id":"follow-meeting-through-one-layer","text":"Follow “meeting” through one layer","depth":3},{"id":"what-does-an-expert-do-with-its-input","text":"What does an expert do with its input?","depth":3},{"id":"why-does-87b-mean-only-47b-parameters","text":"Why does 8×7B mean only 47B parameters?","depth":3},{"id":"discussion","text":"Discussion","depth":2},{"id":"scores-improvedbut-what-are-those-scores","text":"Scores improved—but what are those scores?","depth":3},{"id":"did-the-eight-experts-really-choose-subjects","text":"Did the eight experts really choose subjects?","depth":3},{"id":"what-does-a-32k-context-mean","text":"What does a 32K context mean?","depth":3},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"transformers/switch-transformer","relation":"background","topic":"Routing tokens to sparse experts"},{"id":"deepseek/deepseek-v2","relation":"next","topic":"Routing tokens to sparse experts"}]},{"id":"deepseek/deepseek-llm","category":"deepseek","legacyPath":"deepseek/2401-deepseek-llm","legacySlug":"2401-deepseek-llm","legacyPaths":[],"title":"DeepSeek LLM","subtitle":"New Scaling Laws","author":"Z. Yuan","paperDate":"2024-01-05","publishedOn":"2025-03-25","paperTitle":"DeepSeek LLM: Scaling Open-Source Language Models with Longtermism","paperUrl":"https://arxiv.org/abs/2401.02954v1","bibliography":{"title":"DeepSeek LLM: Scaling Open-Source Language Models with Longtermism","authors":["DeepSeek-AI"],"url":"https://arxiv.org/abs/2401.02954v1","pdfUrl":"https://arxiv.org/pdf/2401.02954v1","codeUrl":"https://github.com/deepseek-ai/DeepSeek-LLM","preprint":{"id":"2401.02954","submittedOn":"2024-01-05","url":"https://arxiv.org/abs/2401.02954v1"},"publication":null,"citation":"@misc{deepseekdeepseekllm2024,\n  title = {{DeepSeek LLM: Scaling Open-Source Language Models with Longtermism}},\n  author = {DeepSeek-AI},\n  year = {2024},\n  eprint = {2401.02954},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/2401.02954v1}\n}\n","citationPath":"/content/papers/citations/deepseek/deepseek-llm.1c9f986d4df6.bib"},"thumbnail":{"src":"/content/papers/assets/2e1273eb4e5fe86379a9c17f7811379777024e4f8dfd78d32143b67fc21e126d.jpg","width":1398,"height":512},"locale":"en","path":"/content/papers/en/deepseek/deepseek-llm.4d02011949aa.md","headings":[{"id":"defining-the-problem","text":"Defining the Problem","depth":2},{"id":"solving-the-problem","text":"Solving the Problem","depth":2},{"id":"data-processing-strategy","text":"Data Processing Strategy","depth":3},{"id":"model-architecture-design","text":"Model Architecture Design","depth":3},{"id":"parameter-configuration","text":"Parameter Configuration","depth":3},{"id":"scaling-laws","text":"Scaling Laws","depth":2},{"id":"hyperparameter-configuration","text":"Hyperparameter Configuration","depth":3},{"id":"optimal-model-and-data-scaling-estimates","text":"Optimal Model and Data Scaling Estimates","depth":3},{"id":"impact-of-data-quality","text":"Impact of Data Quality","depth":3},{"id":"model-alignment","text":"Model Alignment","depth":2},{"id":"discussion","text":"Discussion","depth":2},{"id":"chinese-open-ended-evaluation","text":"Chinese Open-Ended Evaluation","depth":3},{"id":"english-open-ended-evaluation","text":"English Open-Ended Evaluation","depth":3},{"id":"other-interesting-findings","text":"Other Interesting Findings","depth":3},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"deepseek/deepseek-v2","relation":"next","topic":"DeepSeek language models and reasoning training"}]},{"id":"deepseek/deepseek-v3","category":"deepseek","legacyPath":"deepseek/2412-deepseek-v3","legacySlug":"2412-deepseek-v3","legacyPaths":[],"title":"DeepSeek-V3","subtitle":"The Expert’s Far-Sighted View","author":"Z. Yuan","paperDate":"2024-12-27","publishedOn":"2025-03-29","paperTitle":"DeepSeek-V3 Technical Report","paperUrl":"https://arxiv.org/abs/2412.19437v2","bibliography":{"title":"DeepSeek-V3 Technical Report","authors":["DeepSeek-AI"],"url":"https://arxiv.org/abs/2412.19437v2","pdfUrl":"https://arxiv.org/pdf/2412.19437v2","codeUrl":"https://github.com/deepseek-ai/DeepSeek-V3","preprint":{"id":"2412.19437","submittedOn":"2024-12-27","url":"https://arxiv.org/abs/2412.19437v2"},"publication":null,"citation":"@misc{deepseekdeepseekv32024,\n  title = {{DeepSeek-V3 Technical Report}},\n  author = {DeepSeek-AI},\n  year = {2024},\n  eprint = {2412.19437},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/2412.19437v2}\n}\n","citationPath":"/content/papers/citations/deepseek/deepseek-v3.be22b3ba4d67.bib"},"thumbnail":{"src":"/content/papers/assets/b8d2616142a70acbc98edf7ed2c61027966273f0bce6cfff57a8969c007b3c05.jpg","width":1224,"height":560},"locale":"en","path":"/content/papers/en/deepseek/deepseek-v3.114b72d3b291.md","headings":[{"id":"defining-the-problem","text":"Defining the Problem","depth":2},{"id":"solving-the-problem","text":"Solving the Problem","depth":2},{"id":"auxiliary-loss-free-strategy","text":"Auxiliary-Loss-Free Strategy","depth":3},{"id":"multi-token-prediction","text":"Multi-Token Prediction","depth":3},{"id":"infrastructures","text":"Infrastructures","depth":2},{"id":"pre-training","text":"Pre-training","depth":2},{"id":"post-training","text":"Post-training","depth":2},{"id":"supervised-fine-tuning-sft","text":"Supervised Fine-Tuning (SFT)","depth":3},{"id":"reinforcement-learning-rl","text":"Reinforcement Learning (RL)","depth":3},{"id":"discussion","text":"Discussion","depth":2},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"deepseek/deepseek-v2","relation":"background","topic":"DeepSeek language models and reasoning training"},{"id":"deepseek/deepseek-r1","relation":"next","topic":"DeepSeek language models and reasoning training"}]}],"text":"The previous paper was discussing testing the effects of MoE, and not even three months later, here comes another paper.\n\nThis paper has 52 pages, with a large amount of experimental data and technical details. As usual, we'll focus on the key points.\n\n\n> [!WARNING]\n> \n> Mathematics warning: The main focus of this paper is on optimizing the model modules, which involves a significant amount of mathematics. Please read carefully.\n\n\n## Defining the Problem\n\nIn recent years, with the rapid development of large language models, the increase in the number of parameters has indeed brought about significant improvements in model performance, even showcasing some \"emergent capabilities,\" giving us hope of moving towards general artificial intelligence.\n\nHowever, this improvement often comes with a huge consumption of computational resources, which not only makes training extremely expensive but also results in efficiency loss during inference due to computational and memory bottlenecks. This, in turn, affects the widespread adoption and deployment of these models in real-world applications.\n\nTherefore, the DeepSeek research team focused on the computational bottleneck and efficiency issues and proposed the DeepSeek-V2 model, aiming to improve computational efficiency and reduce training and inference costs while maintaining strong performance.\n\n## Solving the Problem\n\nDeepSeek-V2 still adopts the standard Transformer structure, where each Transformer block contains an attention module and a feed-forward network (FFN).\n- **Attention Module**: The research team proposed MLA, which uses low-rank key-value joint compression to address the KV cache bottleneck faced by traditional MHA during generation.\n- **Feed-Forward Network**: The DeepSeekMoE architecture is used, which is a high-performance Mixture-of-Experts model that allows training powerful models within limited costs.\n\nOther details (such as Layer Normalization and activation functions) follow the setup of DeepSeek 67B. The overall architecture is shown in the figure below:\n\n\n\n![modal_arch](/content/papers/assets/0c5c924a685f79d8a0037fb9862aa1358d05058a19ab295c1b1983dae491355d.jpg)\n\n*Paper Figure 2: the MLA and DeepSeekMoE architecture.*\n\n\n\n### Multi-head Latent Attention\n\n\n\n![modal_arch](/content/papers/assets/38c080e5bcc397475b724702ee13917131d3d5891c53ed47c552cfa0451e883b.jpg)\n\n*Cropped from paper Figure 2: the hatched vectors cached during MLA inference include the latent KV vector and decoupled positional key.*\n\n\n\nIn the standard multi-head attention mechanism (MHA), assume:\n- $d$: embedding dimension\n- $n_h$: number of attention heads\n- $d_h$: dimension of each head\n- $h_t \\in \\mathbb{R}^{d}$: input representation of the $t$-th token\n\nUsing three projection matrices $W_Q$, $W_K$, and $W_V$, each of size $\\mathbb{R}^{d_h n_h \\times d}$, the query (q), key (k), and value (v) are computed:\n\n$$\n\\begin{aligned}\nq_t &= W_Q h_t\\\\[1mm]\nk_t &= W_K h_t\\\\[1mm]\nv_t &= W_V h_t\n\\end{aligned}\n$$\n\nThese vectors are then split into $n_h$ heads as follows:\n$$\n[q_{t,1};\\, q_{t,2};\\, \\dots; \\, q_{t,n_h}] = q_t\n$$\n$$\n[k_{t,1};\\, k_{t,2};\\, \\dots; \\, k_{t,n_h}] = k_t\n$$\n$$\n[v_{t,1};\\, v_{t,2};\\, \\dots; \\, v_{t,n_h}] = v_t\n$$\n\nEach head then performs the attention calculation:\n\n$$\no_{t,i} = \\sum_{j=1}^{t} \\text{Softmax}_j\\!\\left(\\frac{q_{t,i}^\\top k_{j,i}}{\\sqrt{d_h}}\\right) v_{j,i}\n$$\n\nFinally, the outputs of the heads are combined through an output projection matrix $W_O \\in \\mathbb{R}^{d \\times d_h n_h}$:\n\n$$\nu_t = W_O [o_{t,1};\\, o_{t,2};\\, \\dots; \\, o_{t,n_h}]\n$$\n\nUp to this point, this is the standard MHA computation process.\n\nHowever, during inference, caching the keys and values requires $2 n_h d_h$ elements per token per layer. With fixed model dimensions and layers, KV-cache memory grows linearly with the cached sequence length, making it a significant bottleneck.\n\nThus, the core of MLA is to reduce the KV cache using \"low-rank compression.\"\n\nThe specific steps are as follows:\n\n1. **Key-Value Compression**: For each token, we first compute its compressed latent representation:\n\n   $$\n   c_{KV,t} = W_{DKV} h_t\n   $$\n\n   where $c_{KV,t} \\in \\mathbb{R}^{d_c}$, $d_c \\ll d_h n_h$, and $W_{DKV} \\in \\mathbb{R}^{d_c \\times d}$ is the down-projection matrix.\n\n2. **Up-Projection to Recover Keys and Values**: The keys and values are recovered from the compressed representation:\n\n   $$\n   k_C,t = W_{UK} c_{KV,t}\n   $$\n\n   $$\n   v_C,t = W_{UV} c_{KV,t}\n   $$\n\n   where $W_{UK}$ and $W_{UV}$ are the up-projection matrices for the key and value, respectively, with dimensions $\\mathbb{R}^{d_h n_h \\times d_c}$.\n\nBefore adding positional encoding, inference can cache only $c_{KV,t}$, or $d_c$ elements per token per layer. With decoupled RoPE, the shared positional key $k^R_t$ must also be cached: the full MLA budget is $d_c+d_h^R=512+64=576$ elements per token per layer in this configuration.\n\nAdditionally, because $W_{UK}$ can be absorbed into $W_Q$, and $W_{UV}$ can be absorbed into $W_O$, there is no need for explicit key and value computation during the actual attention calculation.\n\nFinally, to reduce activation memory during training, the research team also applied a similar low-rank compression to the query vectors:\n\n$$\nc_{Q,t} = W_{DQ} h_t\n$$\n\n$$\nq_C,t = W_{UQ} c_{Q,t}\n$$\n\nwhere $c_{Q,t} \\in \\mathbb{R}^{d'_c}$ is the compressed representation of the query, and $d'_c \\ll d_h n_h$.\n\n### Decoupling Rotary Position Embedding\n\nRotary Position Embedding (RoPE) is a method for incorporating position information in Transformer models, but it is sensitive to both keys and queries. In the case of low-rank compression, if RoPE is directly applied to the compressed key $k_C,t$, it will couple the up-projection matrix $W_{UK}$ with the positional information, thus breaking the earlier absorption optimization and forcing the need to recompute the keys for previous tokens during inference.\n\n\n> [!TIP]\n> \n> Wait, this section might seem confusing?\n> \n> No worries, let’s simplify it: Imagine compressing ten people’s names into one single name.\n> \n> Suppose you originally have ten names, like “Xiaoming, Ahua, Xiaomei, Aqiang…” Each name has its own position. To save space, you decide to merge these ten names into a comprehensive name, such as “MinghuaMeiqiang…” This method saves storage space and is easier to manage.\n> \n> However, if you then add the position information of each original name to this merged name (for example, marking the original order in front of the merged name), this new combined name becomes tightly bound with the position information.\n> \n> The result is: whenever you want to add a new name or query the order of previous names, you must first break apart the merged name and recompute the correct order for each person. This undermines the convenience brought by the initial compression and increases the burden for further processing.\n> \n> In a Transformer model, RoPE is used to add position information to keys and queries, but if you apply RoPE directly to the already compressed (low-rank compressed) key, it’s like adding position information to that merged name. This couples the up-projection matrix (which corresponds to our subsequent processing tool) with the positional information, forcing the need to recompute the keys for the prefix tokens during inference. This not only reduces efficiency but also undermines the benefits of the compression.\n\n\nThe research team proposed a decoupled RoPE strategy. Specifically, they added extra multi-head queries $q_{R,t,i} \\in \\mathbb{R}^{d^R_h}$ and shared keys $k_{R,t} \\in \\mathbb{R}^{d^R_h}$ to carry the positional information of RoPE.\n\nThen, they computed the following:\n\n$$\n[q_{R,t,1};\\, q_{R,t,2};\\, \\dots; \\, q_{R,t,n_h}] = q_{R,t} = \\text{RoPE}(W_{QR} c_{Q,t})\n$$\n\n$$\nk_{R,t} = \\text{RoPE}(W_{KR} h_t)\n$$\n\nWhere $W_{QR} \\in \\mathbb{R}^{d^R_h n_h \\times d'_c}$ and $W_{KR} \\in \\mathbb{R}^{d^R_h \\times d}$ are the matrices used to generate decoupled queries and keys.\n\nFinally, the compressed part and the decoupled part are concatenated:\n\n$$\nq_{t,i} = [q_{C,t,i};\\, q_{R,t,i}]\n$$\n\n$$\nk_{t,i} = [k_{C,t,i};\\, k_{R,t}]\n$$\n\nAnd the attention calculation is performed:\n\n$$\no_{t,i} = \\sum_{j=1}^{t} \\text{Softmax}_j\\!\\left(\\frac{q_{t,i}^\\top k_{j,i}}{\\sqrt{d_h + d^R_h}}\\right) v_{C,j,i}\n$$\n\nFinally, the outputs of the heads are combined using $W_O$:\n\n$$\nu_t = W_O [o_{t,1};\\, o_{t,2};\\, \\dots; \\, o_{t,n_h}]\n$$\n\nThe independent positional key $k^R_t$ leaves the content-key up-projection absorbable into the query side. Inference caches $c^{KV}_t$ and $k^R_t$, rather than full multi-head K/V vectors for every prefix token.\n\n### DeepSeekMoE\n\n\n\n![modal_moe](/content/papers/assets/70017d5a2b8b5523e53a34db643a17adc6d522e2933fbdd43d45aebe3eab5fae.jpg)\n\n*Cropped from paper Figure 2: shared and routed experts in DeepSeekMoE.*\n\n\n\nUnlike traditional MoE models, DeepSeekMoE performs a more detailed segmentation of the experts: splitting the FFN module into two parts:\n\n- **Shared Experts**: A fixed number of experts that each token will use.\n- **Routed Experts**: Experts that are dynamically selected to participate in the computation.\n\nFor the $t$-th token, its FFN input is $u_t$, and the final FFN output $h'_t$ is defined as:\n\n$$\nh'_t = u_t + \\sum_{i=1}^{N_s} \\text{FFN}^{(s)}_i(u_t) + \\sum_{i=1}^{N_r} g_{i,t} \\,\\text{FFN}^{(r)}_i(u_t)\n$$\n\nWhere:\n- $N_s$ is the number of shared experts,\n- $N_r$ is the number of routed experts,\n- $\\text{FFN}^{(s)}_i(\\cdot)$ and $\\text{FFN}^{(r)}_i(\\cdot)$ represent the feed-forward operations of the $i$-th shared expert and routed expert, respectively.\n\nThe selection of routed experts depends on a gating mechanism, defined as follows:\n\n$$\ng_{i,t} =\n\\begin{cases}\ns_{i,t}, & \\text{if } s_{i,t} \\in \\text{Topk}(\\{ s_{j,t} \\mid 1 \\le j \\le N_r\\}, K_r),\\\\[1mm]\n0, & \\text{otherwise},\n\\end{cases}\n$$\n\nWhere $K_r$ is the number of active routed experts, and $s_{i,t}$ is the affinity score between the token and the $i$-th routed expert, computed as:\n\n$$\ns_{i,t} = \\text{Softmax}_i\\bigl(u_t^\\top e_i\\bigr)\n$$\n\nHere $e_i$ is a learned routing vector for expert $i$, called a centroid in the paper; it is not a fixed centroid computed by clustering the dataset.\n\nIn MoE models, when experts are distributed across multiple devices, the routing decision for each token may involve cross-device communication. If a large number of experts are activated, this will incur additional communication costs. To control this, DeepSeekMoE uses a **device-limited routing** mechanism:\n\n1. For each token, select $M$ devices with the highest affinity scores across all devices.\n2. Then, perform Top-K expert selection only within these $M$ devices.\n\nExperimental observations show that when $M \\ge 3$, this limitation significantly reduces cross-device communication while maintaining performance close to the unrestricted Top-K selection.\n\nThe core of this strategy is to balance routing quality with communication costs between devices, achieving high computational efficiency in large-scale distributed environments.\n\n\n> [!TIP]\n> \n> If you’re not familiar with Mixture-of-Experts (MoE), you can refer to our previous notes:\n> \n> - [**[21.01] Switch Transformer: Let the Experts Speak**](/blog/papers/transformers/switch-transformer)\n\n\n### Auxiliary Balance Loss\n\nSince MoE models often experience situations where some experts are overactivated (or even completely unused), this can lead to \"routing collapse\" and reduce computational efficiency. To address this, DeepSeekMoE has designed three auxiliary losses to promote load balancing:\n\n1. **Expert-Level Balance Loss**\n\n    $$\n    L_{ExpBal} = \\alpha_1 \\sum_{i=1}^{N_r} f_i\\, P_i\n    $$\n\n    Where:\n\n    $$\n    f_i = \\frac{N_r}{K_r\\,T} \\sum_{t=1}^{T} 1(\\text{Token } t \\text{ selects Expert } i)\n    $$\n\n    $$\n    P_i = \\frac{1}{T} \\sum_{t=1}^{T} s_{i,t}\n    $$\n\n    - $T$ is the total number of tokens in the sequence,\n    - $1(\\cdot)$ is an indicator function,\n    - $\\alpha_1$ is a hyperparameter used to adjust the loss weight.\n\n    This loss aims to balance the activation frequency and average affinity score of each routed expert.\n\n---\n\n2. **Device-Level Balance Loss**\n\n    The routed experts are grouped into $D$ groups (each group $E_i$ placed on the same device). The loss is defined as:\n\n    $$\n    L_{DevBal} = \\alpha_2 \\sum_{i=1}^{D} f'_i\\, P'_i\n    $$\n\n    Where:\n\n    $$\n    f'_i = \\frac{1}{|E_i|} \\sum_{j \\in E_i} f_j\n    $$\n\n    $$\n    P'_i = \\sum_{j \\in E_i} P_j\n    $$\n\n    - $\\alpha_2$ is the device-level balance hyperparameter.\n\n    This helps ensure the computation load is balanced between devices, preventing any one device from becoming overloaded and causing bottlenecks.\n\n---\n\n3. **Communication Balance Loss**\n\n    Even with device-limited routing, if some devices receive significantly more tokens than others, this can affect communication efficiency. Therefore, the following loss is introduced:\n\n    $$\n    L_{CommBal} = \\alpha_3 \\sum_{i=1}^{D} f''_i\\, P''_i\n    $$\n\n    Where:\n\n    $$\n    f''_i = \\frac{D}{M\\,T} \\sum_{t=1}^{T} 1(\\text{Token } t \\text{ is sent to device } i)\n    $$\n\n    $$\n    P''_i = \\sum_{j \\in E_i} P_j\n    $$\n\n    - $\\alpha_3$ is the communication balance hyperparameter.\n\n    This design encourages each device to maintain a similar level of communication, improving computational coordination efficiency across devices.\n\n---\n\nFinally, in addition to balance losses, the research team introduced a **device-level token dropping strategy** to further mitigate the computational waste caused by load imbalances. The method is as follows:\n\n1. Calculate the average computation budget for each device so that the capacity factor for each device is set to 1.0.\n2. Drop the tokens with the lowest affinity scores on each device until the computation budget is reached.\n3. Protect all tokens belonging to about 10% of training sequences; the paper selects sequences, not a random 10% sample of individual tokens.\n\nThe paper uses token dropping for training speed, while protecting every token in about 10% of training sequences to retain a no-drop path. Its evaluation does not drop tokens.\n\n### Training Strategy\n\nThe paper maintains the same data processing pipeline as DeepSeek 67B, but with the following enhancements:\n\n- **Expanded Data Volume**: The cleaning process was optimized to recover a large amount of previously deleted data.\n- **Improved Data Quality**: More high-quality data was added, especially Chinese data; in the resulting 8.1T-token corpus, the **number of Chinese tokens** is about 12% higher than the number of English tokens, rather than a claim about tokenization length per sentence. Additionally, quality-based filtering algorithms were improved to remove a large amount of useless information while retaining valuable content.\n- **Filtered Controversial Content**: This strategy aims to reduce biases from specific regional cultures.\n\nThe tokenizer uses the same Byte-level Byte-Pair Encoding (BBPE) algorithm as DeepSeek 67B, with a vocabulary size set to 100K, resulting in a total pre-training corpus of 8.1T tokens.\n\nModel hyperparameters are as follows:\n\n- Number of Transformer layers: 60 layers\n- Hidden layer dimension: 5120\n- Standard deviation of randomly initialized parameters: 0.006\n- **MLA-related:**\n    - Number of attention heads $n_h$: 128\n    - Dimension of each head $d_h$: 128\n    - KV compression dimension $d_c$: 512\n    - Query compression dimension $d'_c$: 1536\n    - Decoupled query and key head dimension $d^R_h$: 64\n\nMoE layer configuration is as follows: except for the first layer, all other FFN layers are replaced with MoE layers.\n\n- Each MoE layer contains 2 shared experts and 160 routed experts\n- The hidden dimension of each expert is 1536\n- Each token activates 6 routed experts\n- To address the impact of low-rank compression and fine-grained expert segmentation on layer output size, additional RMS Norm layers and scaling factors were introduced to ensure training stability.\n\nFinally, DeepSeek-V2 has a total of 236B parameters, but only 21B parameters are activated per token.\n\nTraining hyperparameters are as follows:\n\n- Optimizer: AdamW, hyperparameters $\\beta_1=0.9$, $\\beta_2=0.95$, weight decay = 0.1\n- Learning rate scheduling: Linear warmup for the first 2000 steps, then scaled by 0.316 at approximately 60% and 90% of the token count, with a maximum learning rate of 2.4×10⁻⁴\n- Gradient clipping set to 1.0\n- Batch size uses a progressive adjustment strategy, from 2304 to 9216, then remains at 9216\n- Maximum sequence length set to 4K, trained on 8.1T tokens\n- Other parallelization setups:\n    - Pipeline parallelism is used to deploy different layers across different devices\n    - Routed experts are evenly distributed across 8 devices ($D=8$)\n    - Device-limited routing is set to send each token to a maximum of 3 devices ($M=3$)\n    - Hyperparameters for the auxiliary balance losses are set to $\\alpha_1=0.003$, $\\alpha_2=0.05$, $\\alpha_3=0.02$\n    - Token-dropping strategy used during training for acceleration, but tokens are not dropped during evaluation\n\n---\n\nAfter the preliminary pre-training, the research team used the YaRN method to expand the model's default context window from 4K to 128K.\n\nParticular attention was given to expanding the decoupled shared key $k^R_t$ responsible for carrying RoPE, with parameters set as: scale $s=40$, $\\alpha=1$, $\\beta=32$, and a target maximum context length of 160K.\n\nTo accommodate the unique attention mechanism, the length scaling factor was adjusted, making the formula for $\\sqrt{t}$ as follows:\n\n$$\n\\sqrt{t} = 0.0707 \\ln s + 1\n$$\n\nThis aims to minimize perplexity.\n\nDuring the long-context expansion phase, the model was trained for another 1000 steps at a sequence length of 32K and a batch size of 576 sequences. Although training used 32K sequences, it performed well in the paper’s \"Needle In A Haystack\" (NIAH) test at the evaluated context lengths up to 128K. That test does not cover every long-context task.\n\n## Model Alignment\n\nTo improve the alignment of the model with human preferences and further enhance the accuracy and satisfaction of responses, the authors performed reinforcement learning adjustments. The Group Relative Policy Optimization (GRPO) algorithm was used, which is particularly advantageous as it saves training costs by eliminating the need for a critic model of the same scale as the policy model. Instead, group scores are used to estimate the baseline.\n\nThe reinforcement learning training strategy is divided into two stages:\n\n- **Stage 1: Reasoning Alignment**\n\n    In this stage, the authors trained a dedicated reward model $R_{\\text{Mreasoning}}$ for reasoning tasks, such as programming and mathematics:\n\n    $$\n    r_i = R_{\\text{Mreasoning}}(o_i)\n    $$\n\n    This helps the model continuously improve its problem-solving abilities for such tasks.\n\n- **Stage 2: Human Preference Alignment**\n\n    In this stage, a multi-reward framework is used, with rewards obtained from three aspects:\n    - A helpful reward model $R_{\\text{Mhelpful}}$\n    - A safety reward model $R_{\\text{Msafety}}$\n    - A rule-based reward model $R_{\\text{Mrule}}$\n\n    Ultimately, for a given response $o_i$, the reward value is calculated as:\n\n    $$\n    r_i = c_1 \\cdot R_{\\text{Mhelpful}}(o_i) + c_2 \\cdot R_{\\text{Msafety}}(o_i) + c_3 \\cdot R_{\\text{Mrule}}(o_i)\n    $$\n\n    Where $c_1, c_2, c_3$ are the respective coefficients. This multi-reward design helps the model consider multiple quality metrics when generating responses.\n\nTo obtain reliable reward signals, the research team collected large amounts of preference data:\n- Preference data for programming tasks were based on compiler feedback,\n- Preference data for mathematics tasks were based on real labels.\n\nThe reward model was initialized using DeepSeek-V2 Chat (SFT) results and trained with point-to-point or pairwise loss.\n\n## Discussion\n\nDue to space limitations, let's look at the results from AlignBench. If you are interested in other experimental results, you can refer to the original paper.\n\n\n\n![result](/content/papers/assets/6a9bf1816018b7728901582b367e9be4b23d9f66459fbfe65e16133ccb17915e.jpg)\n\n*Paper Table 5: AlignBench Chinese leaderboard judged by GPT-4-0613.*\n\n\n\nThe table ranks the models based on their overall performance scores on AlignBench, with higher-scoring models ranked higher. These are GPT-4-0613-judged Chinese open-ended scores, subject to that judge’s rubric and preferences; rankings should be read within the stated benchmark and model versions.\n\nIn this table, DeepSeek-V2 Chat (RL) scores 7.91 overall, above SFT at 7.74 and the other listed open models, including Qwen1.5 72B Chat at 7.19. The reasoning average rises from 7.30 to 7.45 and the language average from 8.17 to 8.36, but logical reasoning falls from 7.26 to 7.14.\n\nFor Chinese comprehension, RL has 8.28 versus GPT-4-1106-Preview’s 7.33, but below ERNIEBot-4.0-202404 at 8.53. Its 7.45 reasoning average is also below ERNIEBot’s 7.61 and GPT-4-1106-Preview’s 7.73.\n\nThis AlignBench table covers Chinese tasks. The separate English conversation results in paper Table 4 show RL above SFT on MT-Bench (8.97 versus 8.62) and AlpacaEval 2.0 length-controlled win rate (38.9 versus 30.0). The two tables show benefits and trade-offs for their respective tasks; English conversation performance cannot be inferred directly from AlignBench.\n\n## Conclusion\n\n\n\n![conclusion](/content/papers/assets/4ba6ca46c0c172d7eec26264e691c301389cb842b88649f4d92add8c6b0e7a37.jpg)\n\n*Paper Figure 1: capability, training cost, KV cache, and generation throughput comparisons.*\n\n\n\nDeepSeek-V2 is a large language model based on the MoE architecture, supporting up to 128K context length.\n\nThe model leverages two innovative techniques:\n\n  - **Multi-head Latent Attention**: By using low-rank key-value joint compression, it greatly reduces the need for KV cache during inference, thus improving inference efficiency.\n  - **DeepSeekMoE**: Through fine-grained expert segmentation and shared expert designs, it achieves the goal of training powerful models at lower costs.\n\nCompared with DeepSeek LLM 67B under the paper’s training and deployment setup, DeepSeek-V2 reports:\n  - A **42.5% reduction** in training costs;\n  - A **93.3% reduction** in KV cache usage;\n  - A **5.76x improvement** in generation throughput.\n\nDespite having a total of 236B parameters, each token only activates 21B parameters, which strikes a good balance between economy and performance, making it competitive among the open MoE comparisons at the paper’s publication date. The reported throughput depends on the paper’s deployment setup.\n","imageSizes":{"/content/papers/assets/0c5c924a685f79d8a0037fb9862aa1358d05058a19ab295c1b1983dae491355d.jpg":{"width":1224,"height":984},"/content/papers/assets/38c080e5bcc397475b724702ee13917131d3d5891c53ed47c552cfa0451e883b.jpg":{"width":758,"height":554},"/content/papers/assets/70017d5a2b8b5523e53a34db643a17adc6d522e2933fbdd43d45aebe3eab5fae.jpg":{"width":756,"height":426},"/content/papers/assets/6a9bf1816018b7728901582b367e9be4b23d9f66459fbfe65e16133ccb17915e.jpg":{"width":1408,"height":984},"/content/papers/assets/4ba6ca46c0c172d7eec26264e691c301389cb842b88649f4d92add8c6b0e7a37.jpg":{"width":1224,"height":592}}}
