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:
pip install torch
Save the following code as moe_demo.py, then run python moe_demo.py.
# Environment: Python 3.10+, PyTorch 2.x# Educational implementation; not for production trainingimport torchimport torch.nn as nnimport torch.nn.functional as Fclass Expert(nn.Module):def __init__(self, d_model, d_ff):super().__init__()self.net = nn.Sequential(nn.Linear(d_model, d_ff),nn.SiLU(),nn.Linear(d_ff, d_model),)def forward(self, x):return self.net(x)class MoELayer(nn.Module):def __init__(self, num_experts, d_model, d_ff, top_k=2):super().__init__()self.num_experts = num_expertsself.top_k = top_kself.gate = nn.Linear(d_model, num_experts, bias=False)self.experts = nn.ModuleList([Expert(d_model, d_ff) for _ in range(num_experts)])def forward(self, x):# x shape: [tokens, d_model]logits = self.gate(x) # [tokens, E]probs = F.softmax(logits, dim=-1)topk_w, topk_idx = torch.topk(probs, self.top_k, dim=-1) # [tokens, k]# Renormalize top-k weights so each token's weights sum to 1topk_w = topk_w / topk_w.sum(dim=-1, keepdim=True)out = torch.zeros_like(x)for e in range(self.num_experts):# Find token positions that selected expert e and their slot in top-ktoken_pos, slot = (topk_idx == e).nonzero(as_tuple=True)if token_pos.numel() == 0:continueexpert_out = self.experts[e](x[token_pos])weights = topk_w[token_pos, slot].unsqueeze(-1)out.index_add_(0, token_pos, expert_out * weights)return outif __name__ == "__main__":torch.manual_seed(0)layer = MoELayer(num_experts=8, d_model=64, d_ff=256, top_k=2)x = torch.randn(10, 64)y = layer(x)print(y.shape)
Expected output:
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.
import reimport statisticsdef format_reward(text: str) -> float:# Require the answer to contain <answer>...</answer> tagsreturn 0.2 if re.search(r"<answer>.*?</answer>", text, re.S) else 0.0def normalize(s: str) -> str:# Strip leading/trailing whitespace and lowercase to reduce format-related false mismatchesreturn s.strip().lower()def accuracy_reward(text: str, gold: str) -> float:m = re.search(r"<answer>(.*?)</answer>", text, re.S)if not m:return 0.0return 1.0 if normalize(m.group(1)) == normalize(gold) else 0.0def total_reward(text: str, gold
