MoE Cost Reduction and Verifiable RL Rewards: Code and Checklist

    This article explains how mixture-of-experts (MoE) routing lowers per-token compute, reviews DeepSeek-V3's published parameter and training-cost figures with their measurement caveats, provides a runnable PyTorch routing example, and describes rule-based verifiable rewards and GRPO-style group advantage calculation for reinforcement learning. It also highlights what the demo omits and what to check before comparing training costs.

    Background and Data Scope

    This article organizes technical paths based on public reports, official technical reports, and papers. It is not a technology-selection recommendation. Numbers come from public materials; verify them against the original sources before use.

    Liang Wenfeng graduated from Zhejiang University in Electronic Information Engineering. He co-founded High-Flyer, described in public reports as a quantitative private fund manager with more than RMB 100 billion in assets under management. Quantitative trading requires fast processing of large volumes of market data, so the team gained early experience in compute-cluster management, data cleaning, and model optimization. In 2023, he founded DeepSeek to focus on large language model R&D. These dates and scale figures come from media reports; confirm specific numbers against the original disclosures.

    How MoE Reduces Per-Computation Cost

    A mixture-of-experts (MoE) model splits a large network into multiple expert subnetworks. A router (gate) selects a small number of experts for each token. The model can have a large total parameter count, but each token activates only a subset of parameters, so the compute for a single forward pass is significantly lower than that of a dense model with the same total parameter count.

    Readers should distinguish two concepts. Total parameters determine model capacity and the GPU memory occupied by weights. Activated parameters determine the compute for a single token. The two cannot be mixed, or training and inference costs may be overestimated or underestimated.

    DeepSeek-V3 Public Numbers and Definitions

    The DeepSeek-V3 technical report discloses the following numbers.

    Metric Reported value Definition
    Total parameters About 671 billion Includes all experts and shared parts
    Activated parameters per token About 37 billion Determines per-token compute
    Pretraining data About 14.8 trillion tokens Pretraining stage
    Training cost About 2.788 million H800 GPU hours Only the training portion described in the report
    Original source DeepSeek-V3 Technical Report (arXiv:2412.19437) Check the version number and release date

    The report explicitly states that this cost does not include prior research, architecture ablation experiments, and similar investments. Multiplying GPU hours directly by a unit price does not produce the true R&D cost. Before comparing with other models, confirm four things: whether the GPU model is the same, whether data processing is included, whether failed training attempts are included, and whether prior research is included.

    Runnable MoE Routing Layer Code

    Environment: Python 3.10 or later, PyTorch 2.x.

    Install dependencies:

    1. pip install torch

    Save the following code as moe_demo.py, then run python moe_demo.py.

    1. # Environment: Python 3.10+, PyTorch 2.x
    2. # Educational implementation; not for production training
    3. import torch
    4. import torch.nn as nn
    5. import torch.nn.functional as F
    6. class Expert(nn.Module):
    7. def __init__(self, d_model, d_ff):
    8. super().__init__()
    9. self.net = nn.Sequential(
    10. nn.Linear(d_model, d_ff),
    11. nn.SiLU(),
    12. nn.Linear(d_ff, d_model),
    13. )
    14. def forward(self, x):
    15. return self.net(x)
    16. class MoELayer(nn.Module):
    17. def __init__(self, num_experts, d_model, d_ff, top_k=2):
    18. super().__init__()
    19. self.num_experts = num_experts
    20. self.top_k = top_k
    21. self.gate = nn.Linear(d_model, num_experts, bias=False)
    22. self.experts = nn.ModuleList(
    23. [Expert(d_model, d_ff) for _ in range(num_experts)]
    24. )
    25. def forward(self, x):
    26. # x shape: [tokens, d_model]
    27. logits = self.gate(x) # [tokens, E]
    28. probs = F.softmax(logits, dim=-1)
    29. topk_w, topk_idx = torch.topk(probs, self.top_k, dim=-1) # [tokens, k]
    30. # Renormalize top-k weights so each token's weights sum to 1
    31. topk_w = topk_w / topk_w.sum(dim=-1, keepdim=True)
    32. out = torch.zeros_like(x)
    33. for e in range(self.num_experts):
    34. # Find token positions that selected expert e and their slot in top-k
    35. token_pos, slot = (topk_idx == e).nonzero(as_tuple=True)
    36. if token_pos.numel() == 0:
    37. continue
    38. expert_out = self.experts[e](x[token_pos])
    39. weights = topk_w[token_pos, slot].unsqueeze(-1)
    40. out.index_add_(0, token_pos, expert_out * weights)
    41. return out
    42. if __name__ == "__main__":
    43. torch.manual_seed(0)
    44. layer = MoELayer(num_experts=8, d_model=64, d_ff=256, top_k=2)
    45. x = torch.randn(10, 64)
    46. y = layer(x)
    47. print(y.shape)

    Expected output:

    1. torch.Size([10, 64])

    The key steps are three. First, the gate computes a score for each expert for each token. Second, it keeps only the top-k experts and normalizes their weights. Third, it groups tokens by expert, sends tokens belonging to the same expert through that expert in a batch, and adds the results back to the output according to the weights.

    This code omits parts required in production: capacity factor (limiting the number of tokens each expert receives), load-balancing loss, expert parallelism, and communication optimization. The per-expert loop also slows down GPU training. It is only for understanding the routing mechanism and cannot be used directly for training.

    Verifiable Rewards in Reinforcement Learning

    The effectiveness of reinforcement learning depends on how rewards are defined. When an answer can be judged by a program, such as the final numerical value of a math problem or the unit-test result of code, the reward can be computed directly with rules without training an additional reward model. This type of reward is called a verifiable reward.

    The rule rewards used in the DeepSeek-R1 paper mainly include two types: answer-correctness reward and output-format reward. The training algorithm uses Group Relative Policy Optimization (GRPO). For the same question, the model samples a group of responses, computes the reward for each response, and normalizes within the group to obtain the advantage value for each response. This approach does not require training a separate value network (critic).

    The following code demonstrates reward calculation and group advantage calculation to illustrate the principle; it does not include a full training loop. The supplied source text ends at the partial total_reward signature, so that incomplete part is reproduced only as given.

    1. import re
    2. import statistics
    3. def format_reward(text: str) -> float:
    4. # Require the answer to contain <answer>...</answer> tags
    5. return 0.2 if re.search(r"<answer>.*?</answer>", text, re.S) else 0.0
    6. def normalize(s: str) -> str:
    7. # Strip leading/trailing whitespace and lowercase to reduce format-related false mismatches
    8. return s.strip().lower()
    9. def accuracy_reward(text: str, gold: str) -> float:
    10. m = re.search(r"<answer>(.*?)</answer>", text, re.S)
    11. if not m:
    12. return 0.0
    13. return 1.0 if normalize(m.group(1)) == normalize(gold) else 0.0
    14. def total_reward(text: str, gold