LLM Training Essentials: Pretraining Data, MoE Architecture, and GRPO in Practice

    This article covers three core aspects of large language model training: pretraining data quality and mixture ratios, Mixture-of-Experts (MoE) design with fine-grained and shared experts, and Group Relative Policy Optimization (GRPO) as a critic-free alternative to PPO. It includes a structural MoE code example, a PPO-versus-GRPO comparison, a parameter checklist, and a list of common mistakes to help practitioners plan and debug their training pipelines.

    1. Pretraining Data and Mixture Ratios

    LLM pretraining typically involves models ranging from a few billion to tens of billions of parameters, trained on token counts in the trillions. For example, the DeepSeek LLM report describes a 67B-parameter model pretrained on roughly 2 trillion tokens. Refer to the original reports for exact figures.

    Data quality work generally falls into three categories:

    1. Cleaning and deduplication: Filter out low-quality web pages, garbled text, and duplicate documents. Duplicated data causes the model to over-memorize certain passages and wastes effective training budget.
    2. Toxicity and privacy filtering: Identify harmful content and personal information. Filtering rules should be spot-checked regularly to avoid removing legitimate text by mistake.
    3. Data mixture ratios: The proportions of code, math, and general text directly affect downstream capabilities. Ratios should be validated with small-scale experiments before locking in the production configuration.

    Learning rate scheduling is equally important. A common approach is a warmup phase followed by cosine or step decay. A learning rate that is too high causes loss oscillation, while one that is too low wastes training steps. The peak learning rate should be tuned together with batch size and model scale, and the proportion of warmup steps should also be determined experimentally.

    During training, monitor downstream metrics such as code generation and logical reasoning alongside perplexity. A drop in perplexity does not necessarily translate into better reasoning—the relationship between the two shifts with the data mixture.

    2. MoE Architecture: Controlling Cost with Conditional Computation

    In a dense model, every token passes through all parameters, so inference cost grows with model size. Mixture of Experts (MoE) splits the feed-forward layer into multiple experts, and a router selects only a few of them for each token. The total parameter count can be very large while each token only activates a fraction of the parameters.

    Traditional MoE designs have two common problems. First, with few, large experts, it is hard for experts to develop clear specialization. Second, routing can be unstable: some experts get selected constantly while others sit idle. The following two mechanisms address these problems respectively.

    Fine-grained expert segmentation: Split a small number of large experts into more, smaller experts, reducing the hidden dimension of each. With total parameters held constant, the router has more combinations to choose from and experts specialize more easily. This idea was proposed in the DeepSeekMoE paper.

    Shared experts: After fine-grained segmentation, general knowledge such as basic syntax and common formats tends to be redundantly learned across multiple routed experts, wasting parameters. Shared experts are a small set of experts that process every token and capture general knowledge, while routed experts focus on specific features.

    The code below implements this data flow. It omits the load-balancing loss and distributed implementation, and is intended only as a structural illustration—not for production use.

    1. import torch
    2. import torch.nn as nn
    3. import torch.nn.functional as F
    4. class FFN(nn.Module):
    5. def __init__(self, d_model, d_hidden):
    6. super().__init__()
    7. self.w1 = nn.Linear(d_model, d_hidden, bias=False)
    8. self.w2 = nn.Linear(d_hidden, d_model, bias=False)
    9. def forward(self, x):
    10. return self.w2(F.silu(self.w1(x)))
    11. class FineGrainedMoELayer(nn.Module):
    12. def __init__(self, d_model, d_expert, num_routed, num_shared, top_k):
    13. super().__init__()
    14. if not 1 <= top_k <= num_routed:
    15. raise ValueError("top_k must be in [1, num_routed]")
    16. self.top_k = top_k
    17. self.router = nn.Linear(d_model, num_routed, bias=False)
    18. self.routed_experts = nn.ModuleList(
    19. FFN(d_model, d_expert) for _ in range(num_routed)
    20. )
    21. self.shared_experts = nn.ModuleList(
    22. FFN(d_model, d_expert) for _ in range(num_shared)
    23. )
    24. def forward(self, x): # x: [num_tokens, d_model]
    25. if x.dim() != 2 or x.size(-1) != self.router.in_features:
    26. raise ValueError("x must have shape [num_tokens, d_model]")
    27. probs = torch.softmax(self.router(x), dim=-1) # [T, E]
    28. weights, indices = torch.topk(probs, self.top_k, dim=-1) # [T, K]
    29. # Renormalize top-k weights so each token's routing weights sum to 1
    30. weights = weights / weights.sum(dim=-1, keepdim=True)
    31. routed_out = torch.zeros_like(x)
    32. for e, expert in enumerate(self.routed_experts):
    33. mask = indices == e # [T, K]
    34. if not mask.any():
    35. continue
    36. token_idx, slot_idx = mask.nonzero(as_tuple=True)
    37. w = weights[token_idx, slot_idx].unsqueeze(-1)
    38. routed_out.index_add_(0, token_idx, expert(x[token_idx]) * w)
    39. shared_out = torch.zeros_like(x)
    40. for expert in self.shared_experts:
    41. shared_out = shared_out + expert(x)
    42. return routed_out + shared_out
    43. if __name__ == "__main__":
    44. layer = FineGrainedMoELayer(d_model=64, d_expert=32, num_routed=8,
    45. num_shared=1, top_k=2)
    46. y = layer(torch.randn(10, 64))
    47. print(y.shape) # torch.Size([10, 64])

    There is no universal answer on whether to normalize top-k weights. With normalization, each token’s output scale is independent of the probability magnitudes of the selected experts, and training is usually more stable. Models such as Mixtral apply a softmax over the top-k weights, which is equivalent to normalization. If the model design requires preserving the relative magnitudes of the global probabilities, normalization can be skipped. A reasonable default is to normalize first, then decide via ablation whether to change it.

    3. GRPO: Reinforcement Learning Without a Critic

    PPO relies on a critic (value model) to estimate state values, then computes advantages with GAE (Generalized Advantage Estimation). The critic is typically close in size to the policy model, consuming substantial GPU memory and requiring its own stability tuning.

    GRPO (Group Relative Policy Optimization), proposed in the DeepSeekMath paper, takes a different approach: for each prompt q, sample a group of G responses from the old policy, obtain rewards r_1 through r_G, and estimate the advantage using group statistics:

    A_i = (r_i - mean(r)) / std(r)

    All tokens in the same response share this sequence-level advantage. The objective keeps PPO’s clipped ratio and adds a KL penalty against a reference model. Implementations differ on whether to divide by the standard deviation—this can be treated as an ablation item.

    Key differences between PPO and GRPO:

    Dimension PPO GRPO
    Value model Requires a critic, usually close in size to the policy model Not needed; advantages estimated from group rewards
    Advantage estimation GAE, dependent on critic quality Relative reward within the group, sequence-level, broadcast to all tokens
    Group comparison None Sample G responses per prompt; G is a hyperparameter
    Main memory footprint Policy, critic, reference model Policy, reference model
    Reward requirements Handles dense or sparse rewards Needs reward variance within the group; suited to automatically verifiable tasks
    Main risks Critic training instability No gradient when group rewards are identical; high sampling cost

    GRPO’s applicability boundaries are clear. Rewards must be verifiable—for example, unit test pass rates or answer matching. If all rewards within a group are identical, the advantage is zero and that group produces no gradient. Each prompt requires G samples, so inference cost is significantly higher than single-sample methods. And if the reward function has loopholes, the policy will learn to exploit them—reward hacking.

    4. Parameter Checklist

    • Number of experts and top_k: Confirm top_k does not exceed the total number of experts, and record the fraction of parameters actually activated per token.
    • Number of shared experts: Start with a small number, compare downstream metrics before and after adding them, and observe whether routed experts develop specialization.
    • Expert granularity: After fine-grained segmentation, confirm the total parameter count matches the control group before comparing results.
    • Load balancing: Monitor how often each expert is selected. If a few experts dominate traffic over time, add a load-balancing loss.
    • Learning rate and batch size: Tune the peak learning rate together with batch size, and check the loss curve for oscillation.
    • Data mixture: Keep small-scale experiment records for every mixture change, including the proportions of code, math, and general text.
    • GRPO group size G: Larger G yields more stable group statistics, but sampling cost increases accordingly.
    • KL coefficient: Monitor how far the policy drifts from the reference model. A coefficient that is too large constrains learning; one that is too small allows excessive drift.
    • Clip range: 0.2 is a common starting point in PPO; when carried over to GRPO, validate it against the actual reward distribution.
    • Reward design: Check that rewards have sufficient variance within groups, and spot-check high-scoring samples for loopholes.

    5. Common Mistakes

    1. Watching only perplexity: After perplexity drops, downstream reasoning metrics may show no improvement—or even regress.
    2. Too many shared experts: When shared experts take up too large a share, routed experts are weakened and the model approaches a dense architecture.
    3. Ignoring load balancing: Without balancing constraints, some experts may remain idle long-term, wasting parameters.
    4. Mismatch between top_k and expert count: An overly large top_k negates the cost advantage of sparse computation; one that is too small limits routing flexibility.
    5. Homogeneous GRPO rewards: When all rewards in a group are identical, the training signal vanishes while sampling compute is still being consumed.
    6. Reward exploitation: Checking only reward scores without sampling the outputs makes it easy to mistake a loophole for a capability gain.
    7. Using illustrative code directly: The example code omits the load-balancing loss, numerical stability handling, and distributed communication—using it for actual training will produce incorrect results.

    6. Conclusion

    The effectiveness of LLM training depends primarily on three pillars: data quality, model architecture, and the reinforcement learning method.