Multimodal MoE Training Troubleshooting: Four Checks to Validate the Training Pipeline

    This article targets engineers training multimodal Mixture-of-Experts (MoE) models on multi-GPU clusters. It is not tied to any specific framework or product version. It explains the three core challenges of multimodal MoE training—scale, structure, and modality—then walks through the technical path: fully sharded data parallelism, expert parallelism with load balancing, chunked loss computation, and custom kernel validation. Finally, it provides a four-part verification checklist with runnable code: stability checks, convergence trend monitoring, module gradient inspection (to confirm the vision branch actually participates in training), and expert load monitoring. All thresholds given are starting values that should be calibrated against a known-good baseline run before being used in production. Multimodal MoE Training Troubleshooting: Four Checks to Validate the Training Pipeline

    1. Scope

    This article is for engineers training multimodal Mixture-of-Experts (MoE) models on multiple GPUs. The content is not bound to any specific framework or product version. All thresholds in this article are starting values only: measure them on a known-good baseline run first, calibrate accordingly, and do not apply them directly to production workloads.

    The difficulty of multimodal MoE training comes from three sources.

    Scale: Once the parameter count reaches hundreds of billions, a single GPU cannot hold the full parameters, gradients, and optimizer states. Sharding is mandatory.

    Structure: Each token activates only a small number of experts, and routing results vary with the data. Under imbalanced load, some GPUs sit idle while others queue up.

    Modality: The vision encoder and the language backbone have different compute densities and sequence shapes. If the two do not go through the same forward, backward, and parameter update pipeline, the vision branch only participates in inference, not training. This class of problem is subtle because the loss still appears to decrease.

    2. Decompose Modules First, Then Decide the Parallel Strategy

    The first step of adaptation is to list all modules and confirm the compute characteristics and communication requirements of each one. There are four common dimensions along which to decompose the model.

    • Attention modules: Standard attention, linear attention, and sparse attention may be mixed. They differ significantly in kernel implementation, peak memory, and numerical stability.
    • Routing and expert modules: Pay attention to the numerical precision of routing scores, the Top-K selection method, and load distribution across experts.
    • Vision encoder module: The embedding sequence produced after image patching must align with the text sequence, and gradients must flow back to every layer of the vision tower.
    • Cross-modal projection module: Maps visual features into the language space. It is the key node for determining whether the vision branch participates in training.

    Only after the module list is settled can you decide which parts fit into the same sharding strategy and which parts need separate optimization.

    3. Core Technical Path

    3.1 Fully Sharded Data Parallelism

    Fully sharded data parallelism splits parameters, gradients, and optimizer states across devices. Taking bf16 mixed precision with an Adam-family optimizer as an example, the static footprint per parameter is about 16 bytes: 2 bytes for the bf16 parameter, 2 bytes for the bf16 gradient, 4 bytes for the fp32 master weight, and 4 bytes each for the first and second moments. With P parameters on N GPUs, the static memory per GPU is roughly 16P/N bytes.

    This estimate only holds under specific assumptions: bf16 mixed precision, an Adam-family optimizer, no offloading of optimizer states to CPU, and no activation recomputation. It does not include activations, communication buffers, memory fragmentation, or temporary tensors. Actual peak memory is usually significantly higher than the estimate—use the measurement method in Section 4.5 as the ground truth.

    The benefit of sharding depends on whether communication can be hidden by computation. A common practice is parameter prefetching: while the current layer is computing, fetch the parameters needed by the next layer in advance.

    3.2 Expert Parallelism and Load Balancing

    Expert parallelism places different experts on different devices. It can be combined with data parallelism: non-expert parts are sharded along the data dimension, while expert parts are sharded along the expert dimension.

    Load balancing requires continuously counting how many tokens each expert receives. The statistics window is 100 steps, and the observed values are cumulative within the window. The load ratio is defined as the maximum expert load divided by the average expert load; perfect balance yields 1. If the load ratio stays above 1.5 for 3 consecutive windows, check the router loss weight and the capacity factor. Experts that receive zero tokens within a window are recorded as idle experts. Section 4.4 provides the statistics code.

    3.3 Chunked Loss Computation

    The language model output layer produces a logits tensor covering the entire vocabulary. With a per-GPU batch size of 1, a sequence length of 1024, and a vocabulary of 150K, a single bf16 logits tensor is about 150000×1024×2 bytes, i.e., 0.307 GB (decimal), or roughly 0.286 GiB. Converting to fp32 for cross-entropy doubles that. After adding the gradient tensor, peak memory rises noticeably.

    Chunked loss computation splits the sequence into segments, computing and accumulating the loss segment by segment. Combined with per-segment recomputation (checkpointing), only one chunk’s full logits need to reside in memory at a time. The chunk size does not need to divide the sequence length evenly; the last segment is automatically shorter. The code requires PyTorch 1.11 or later, since the use_reentrant parameter is available starting from that version.

    1. import torch
    2. import torch.nn.functional as F
    3. from torch.utils.checkpoint import checkpoint
    4. def chunked_ce_loss(hidden, lm_head, labels, chunk=1024):
    5. """
    6. hidden: [B, T, H], labels: [B, T], -100 marks positions to ignore.
    7. Returns the loss averaged over all valid positions.
    8. """
    9. def _chunk_loss(h, y):
    10. logits = lm_head(h).float()
    11. return F.cross_entropy(
    12. logits.flatten(0, 1),
    13. y.flatten(),
    14. ignore_index=-100,
    15. reduction="sum",
    16. )
    17. loss_sum = hidden.new_zeros((), dtype=torch.float32)
    18. valid = (labels != -100).sum().clamp(min=1)
    19. for s in range(0, hidden.size(1), chunk):
    20. loss_sum = loss_sum + checkpoint(
    21. _chunk_loss,
    22. hidden[:, s:s + chunk],
    23. labels[:, s:s + chunk],
    24. use_reentrant=False,
    25. )
    26. return loss_sum / valid

    The cost is one forward recomputation per chunk, which increases both compute and scheduling overhead. Whether to adopt it should be decided by comparing peak memory using the method in Section 4.5, not by theoretical values alone.

    3.4 Custom Kernels

    Modules such as linear attention and sparse retrieval often use custom kernels. The validation focus is numerical consistency with a reference implementation. Fix the reference implementation, random seed, batch size, and sequence length, then compare output error and gradient error. Common acceptance criteria are a relative error below 1e-2 (bf16) or 1e-5 (fp32), with no NaN in gradients. Adjust the thresholds according to the kernel’s precision requirements, and note the statistical method used in the report.

    4. Verification Checklist for the Training Pipeline

    After adaptation, systematic checks are needed to prove the training pipeline actually works. The table below lists the metrics, sampling methods, and decision thresholds for the four categories of checks.

    Check Metric Sampling Threshold (starting value)
    Stability Whether loss and gradient norm are finite Every step Alert on any non-finite value
    Convergence trend Change in sliding-window mean Window of 200 steps, compared every 1000 steps Alert if the relative drop between adjacent windows is under 1% for 3 consecutive comparisons
    Module gradients Gradient norm and missing-gradient count per module Sampled every 100 steps Missing-gradient count must be 0; a norm below 1e-8 is treated as near-zero
    Peak memory Peak allocated and reserved memory Reset once per statistics window Alert if reserved peak exceeds 90% of device capacity; warn if fragmentation exceeds 20%

    4.1 Stability Check

    The following code runs as-is to check loss and gradient norm step by step. In multi-GPU training, the loss passed in should be averaged across GPUs. The gradient norm uses the return value of clip_grad_norm_, which is the total norm before clipping.

    1. import math
    2. from dataclasses import dataclass
    3. @dataclass
    4. class StepHealthConfig:
    5. max_grad_norm: float = 1e4 # above this, treat as gradient explosion
    6. max_loss: float = 1e3 # above this, treat as abnormal loss
    7. def check_step_health(step, loss_value, grad_norm, cfg=None):
    8. """Check whether a single step's values are abnormal; return a list of issues."""
    9. cfg = cfg or StepHealthConfig()
    10. issues = []
    11. if not math.isfinite(loss_value):
    12. issues.append(f"step {step}: loss is non-finite {loss_value}")
    13. elif loss_value > cfg.max_loss:
    14. issues.append(f"step {step}: loss too large {loss_value:.3e}")
    15. if not math.isfinite(grad_norm):
    16. issues.append(f"step {step}: gradient norm is non-finite {grad_norm}")
    17. elif grad_norm > cfg.max_grad_norm:
    18. issues.append(f"step {step}: gradient norm too large {grad_norm:.3e}")
    19. return issues
    20. if __name__ == "__main__":
    21. history = [
    22. (1, 2.31, 0.80),
    23. (2, float("nan"), 1.20),
    24. (3, 2.10, 5e4),
    25. ]
    26. problems = []
    27. for step, loss, gnorm in history:
    28. problems.extend(check_step_health(step, loss, gnorm))
    29. for msg in problems:
    30. print(msg)

    Running it prints two lines:

    1. step 2: loss is non-finite nan
    2. step 3: gradient norm too large 5.000e+04

    4.2 Convergence Trend Check

    Convergence is judged not by single-step loss but by the mean over a sliding window. Every 1000 steps, take the mean of the most recent 200 loss values and compare it with the previous mean. If the relative drop is below 1% for 3 consecutive comparisons, check the learning rate, data ordering, and router loss weight.

    1. import math
    2. from collections import deque
    3. class ConvergenceMonitor:
    4. def __init__(self, window=200, interval=1000, min_rel_drop=0.01, patience=3):
    5. self.window = window
    6. self.interval = interval
    7. self.min_rel_drop = min_rel_drop
    8. self.patience = patience
    9. self.buf = deque(maxlen=window)
    10. self.prev_mean = None
    11. self.stall_count = 0
    12. self.step = 0
    13. def update(self, loss):
    14. self.step += 1
    15. self.buf.append(float(loss))
    16. if self.step % self.interval != 0:
    17. return None
    18. mean = sum(self.buf) / len(self.buf)
    19. if not math.isfinite(mean):
    20. return "window mean is non-finite; check the stability monitor first"
    21. if self.prev_mean is None:
    22. self.prev_mean = mean
    23. return None
    24. rel_drop = (self.prev_mean - mean) / max(abs(self.prev_mean), 1e-12)
    25. self.prev_mean = mean
    26. if rel_drop < self.min_rel_drop:
    27. self.stall_count += 1
    28. else:
    29. self.stall_count = 0
    30. if self.stall_count >= self.patience:
    31. return (f"convergence stalled: drop below "
    32. f"{self.min_rel_drop:.0%} for {self.patience} consecutive comparisons")
    33. return None

    Call monitor.update(loss) every step. An alert is emitted only when a non-empty string is returned. The count is in units of comparisons, with each comparison 1000 steps apart. Since windows do not overlap, no data is reused between two comparisons.

    4.3 Module Gradient Check: Is the Vision Branch Actually Training?

    The key to determining whether the vision branch participates in training is the gradients of the vision tower and the cross-modal projection layers. After backpropagation, every trainable parameter should have a gradient. If a module’s parameter gradients are None, contain non-finite values, or have a near-zero norm, that branch is not in the training pipeline.

    1. import math
    2. import torch
    3. NEAR_ZERO = 1e-8
    4. def module_grad_report(model, groups, near_zero=NEAR_ZERO):
    5. """
    6. groups: {module_name: [parameter_name_prefix, ...]}, with prefixes
    7. matching the model's actual parameter names.
    8. Returns {module_name: stats_dict}.
    9. """
    10. report = {}
    11. for name, prefixes in groups.items():
    12. n_params = n_missing = n_nonfinite = 0
    13. sq_sum = 0.0
    14. for pname, p in model.named_parameters():
    15. if not p.requires_grad:
    16. continue
    17. if not any(pname.startswith(x) for x in prefixes):
    18. continue
    19. n_params += 1
    20. if p.grad is None:
    21. n_missing += 1
    22. continue
    23. g = p.grad.detach().float()
    24. if not torch.isfinite(g).all():
    25. n_nonfinite += 1
    26. continue
    27. sq_sum += g.pow(2).sum().item()
    28. grad_norm = math.sqrt(sq_sum)
    29. report[name] = {
    30. "n_params": n_params,
    31. "n_missing": n_missing,
    32. "n_nonfinite": n_nonfinite,
    33. "grad_norm": grad_norm,
    34. "near_zero": grad_norm < near_zero,
    35. }
    36. return report
    37. def grad_alarms(report):
    38. msgs = []
    39. for name, r in report.items():
    40. if r["n_params"] == 0:
    41. msgs.append(f"{name}: no parameters matched; check the prefixes")
    42. continue
    43. if r["n_missing"] > 0:
    44. msgs.append(f"{name}: {r['n_missing']}/{r['n_params']} parameters have no gradient")
    45. if r["n_nonfinite"] > 0:
    46. msgs.append(f"{name}: {r['n_nonfinite']} parameters have non-finite gradients")
    47. if r["near_zero"]:
    48. msgs.append(f"{name}: gradient norm {r['grad_norm']:.2e} is near zero")
    49. return msgs
    50. GROUPS = {
    51. "vision_tower": ["vision_tower."],
    52. "mm_projector": ["mm_projector."],
    53. }
    54. # In the training loop, call after backward()
    55. # if step % 100 == 0:
    56. # for msg in grad_alarms(module_grad_report(model, GROUPS)):
    57. # print(f"step {step} {msg}")

    This code works directly under non-FSDP data parallelism, because gradients are identical across GPUs after all-reduce. With FSDP, parameters and gradients are sharded views; you first need to obtain the full parameters through the interface provided by your version (for example, summon_full_params). Interface parameters vary by version, so refer to the official documentation for your version.

    4.4 Expert Load Ratio and Idle Experts

    The monitor below receives the local GPU’s routing results each step and accumulates per-expert token counts within a window. At the end of the window, counts from all GPUs are summed via all-reduce, and the load ratio and idle experts are computed. Expert IDs in the routing results should use global numbering.

    ```python
    import torch
    import torch.distributed as dist

    class ExpertLoadMonitor:
    def init(self, num_experts, window=100, ratio_threshold=1.5,
    consecutive=3, device=”cuda”):
    self.num_experts = num_experts
    self.window = window
    self.ratio_threshold = ratio_threshold
    self.consecutive = consecutive
    self.counts = torch.zeros(num_experts, dtype=torch.float64, device=device)
    self.steps = 0
    self.over_windows = 0

    1. def step(self, expert_ids):
    2. """Call every step. expert_ids: [num_tokens, top_k], global expert IDs.
    3. Returns None before the window ends; returns a list of alerts at window end."""
    4. ids = expert_ids.reshape(-1).long()
    5. self.counts += torch.bincount(ids, minlength=self.num_experts).double()
    6. self.steps += 1
    7. if self.steps < self.window:
    8. return None
    9. return self._close_window()
    10. def _close_window(self):
    11. if dist.is_available() and dist.is_initialized():
    12. dist.all_reduce(self.counts, op=dist.ReduceOp.SUM)
    13. counts = self.counts.clone().cpu()
    14. self.counts.zero_()
    15. self.steps = 0
    16. total = counts.sum().item()
    17. if total == 0:
    18. return []
    19. mean = total / self.num_experts
    20. ratio = counts.max().item() / mean
    21. idle = (counts == 0).nonzero(as_tuple=True)[0].tolist()
    22. if ratio > self.ratio_threshold:
    23. self.over_windows += 1
    24. else:
    25. self.over_windows = 0
    26. msgs = []
    27. if self.over_windows >= self.consecutive:
    28. msgs.append(f"load ratio {ratio:.2f} above {self.ratio_threshold} "
    29. f"for {self.over_windows} consecutive windows")