Skip to content
Open
38 changes: 38 additions & 0 deletions docs/user-tutorial/benchmarks/model-benchmarks.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,3 +163,41 @@ Run GPT pretrain tasks with float32, float16, bfloat16 precisions with [Megatron
| megatron-gpt/${precision}_train_mem_allocated | GB | The average GPU memory allocated per iteration. |
| megatron-gpt/${precision}_train_max_mem_allocated | GB | The average maximum GPU memory allocated per iteration. |

## DeepSeek-V2-Lite Training

### `deepseek-v2-lite-training`

#### Introduction

Run full-parameter BF16 training of the official
[DeepSeek-V2-Lite](https://huggingface.co/deepseek-ai/DeepSeek-V2-Lite) checkpoint (15.7B parameters)
with FSDP and AdamW on `num_gpus` local GPUs. Each run downloads and verifies the 31.4GB checkpoint,
checks the loss and sampled gradients against an unsharded official-code reference, then trains on fixed
text; it measures training performance, not convergence. `batch_size` is the microbatch per GPU.
`moe_dispatch=stable_sorted` replaces the official expert dispatch with a stable sort that keeps the
same routing.

Validated on four H100 80GB GPUs in the SuperBench CUDA 13.0 image with `batch_size=36`, `num_steps=128`,
`moe_dispatch=stable_sorted` and `PYTORCH_CUDA_ALLOC_CONF=backend:native`; the supplied profile is a
Comment thread
gusui-msft marked this conversation as resolved.
Resolved
smaller example. The reference needs an 80GB GPU. Each GPU's process first loads the full model in FP32
on the host, about 63GB, before FSDP shards it; the validated four-GPU run used about 275GB of host
memory at its peak.

#### Usage

Run the [training profile](../../../superbench/config/deepseek-v2-lite-training.yaml) as its own entry
with one local process in the SuperBench CUDA 13.0 image. The worker uses the SuperBench Python
(`runtime_python`), whose transformers 4.x runs the official model code. `cache_root` is required: each
run downloads into a new directory under it and deletes the checkpoint at the end. `duration` must be
below 3600 seconds and covers the whole job.

#### Metrics

| Name | Unit | Description |
|---|---|---|
| deepseek-v2-lite-training/bf16_train_step_time | time (ms) | The average training step time of the slowest GPU, including forward, backward, gradient clipping and the optimizer update. |
| deepseek-v2-lite-training/bf16_train_tokens_per_second | throughput (tokens/s) | Next-token targets trained per second across all GPUs. |
| deepseek-v2-lite-training/bf16_train_loss | loss | The average global causal-LM loss. |
| deepseek-v2-lite-training/bf16_train_gradient_norm | norm | The average global gradient norm before clipping. |
| deepseek-v2-lite-training/end_to_end_seconds | time (s) | The complete job time, including checkpoint download and cache deletion. |
| deepseek-v2-lite-training/checkpoint_bytes | size (bytes) | The total size of the checkpoint weight files. |
3 changes: 2 additions & 1 deletion superbench/benchmarks/model_benchmarks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@
from superbench.benchmarks.model_benchmarks.megatron_gpt3 import MegatronGPT
from superbench.benchmarks.model_benchmarks.pytorch_llama import PytorchLlama
from superbench.benchmarks.model_benchmarks.pytorch_mixtral import PytorchMixtral
from superbench.benchmarks.model_benchmarks.pytorch_deepseek_v2_lite import DeepSeekV2LiteTraining

__all__ = [
'ModelBenchmark', 'PytorchBERT', 'PytorchGPT2', 'PytorchCNN', 'PytorchLSTM', 'MegatronGPT', 'PytorchLlama',
'PytorchMixtral'
'PytorchMixtral', 'DeepSeekV2LiteTraining'
]

if PytorchMixtral is not None:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

"""DeepSeek-V2-Lite workers and helpers.

Workers run as ``python -m deepseek_v2_lite.<module>``, the inference ones in interpreters without SuperBench,
so every module except ``cache`` imports only the standard library and this package at load time.
"""
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

"""Bounded removal of one V2-Lite run's downloaded model cache."""

import subprocess
import sys
import time
from pathlib import Path

from superbench.common.utils import logger

FAILURE_CLEANUP_GRACE_SECONDS = 60
_REMOVE_TREE = 'import os, shutil, sys\nif os.path.exists(sys.argv[1]):\n shutil.rmtree(sys.argv[1])'


def remove_model_cache(cache: Path, deadline: float) -> None:
"""Delete one run's model cache before a monotonic deadline, keeping reports and logs.

A missing budget, an expired deletion or a SuperBench SIGTERM raises TimeoutError. Other
filesystem errors are logged so that a validated measurement is not discarded.
"""
start = time.monotonic()
remaining = deadline - start
if remaining <= 0:
raise TimeoutError('No time remains to remove the V2-Lite model cache at {}.'.format(cache))
try:
# A child process can be stopped and reaped at the deadline; an in-process rmtree cannot.
subprocess.run(
[sys.executable, '-c', _REMOVE_TREE, str(cache)],
timeout=remaining,
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
)
except subprocess.TimeoutExpired as error:
raise TimeoutError('V2-Lite model cache cleanup exceeded the deadline at {}.'.format(cache)) from error
except TimeoutError:
# The SuperBench SIGTERM handler raises TimeoutError, an OSError subclass; keep it fatal.
raise
except subprocess.CalledProcessError as error:
logger.error('Failed to remove the V2-Lite model cache %s: %s', cache, error.output or error)
return
except OSError as error:
logger.error('Failed to remove the V2-Lite model cache %s: %s', cache, error)
return
logger.info('V2-Lite model cache cleanup completed for %s in %.1f seconds.', cache, time.monotonic() - start)


def remove_model_cache_after_failure(cache: Path, deadline: float) -> None:
"""Remove the cache of a failed run without replacing the run's original error.

Cleanup may run until the job deadline or for FAILURE_CLEANUP_GRACE_SECONDS, whichever ends later,
so a timed-out worker does not leave its checkpoint behind only because the budget is spent.
"""
try:
remove_model_cache(cache, max(deadline, time.monotonic() + FAILURE_CLEANUP_GRACE_SECONDS))
except TimeoutError as error:
logger.error('V2-Lite model cache cleanup did not finish after a failed run: %s', error)
52 changes: 52 additions & 0 deletions superbench/benchmarks/model_benchmarks/deepseek_v2_lite/moe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

"""Stable expert dispatch for the pinned full-parameter V2-Lite training model."""

import sys
from types import MethodType

MOE_DISPATCHES = ('official', 'stable_sorted')


def sorted_training_forward(module, hidden_states, auxiliary_apply):
"""Preserve route order and every expert while avoiding repeated Boolean-index synchronizations."""
import torch

original_shape = hidden_states.shape
indices, weights, auxiliary = module.gate(hidden_states)
routed = hidden_states.reshape(-1, original_shape[-1]).repeat_interleave(module.num_experts_per_tok, dim=0)
expert_ids = indices.reshape(-1)
order = torch.argsort(expert_ids, stable=True)
counts = torch.bincount(expert_ids, minlength=len(module.experts)).tolist()
segments = torch.split(routed.index_select(0, order), counts, dim=0)
outputs = torch.cat([expert(segment) for expert, segment in zip(module.experts, segments)], dim=0)
inverse = torch.empty_like(order)
inverse.scatter_(0, order, torch.arange(order.numel(), device=order.device))
routed_output = outputs.index_select(0, inverse)
combined = (routed_output.view(*weights.shape, -1) * weights.unsqueeze(-1)).sum(dim=1)
combined = combined.to(hidden_states.dtype).view(original_shape)
combined = auxiliary_apply(combined, auxiliary)
if module.config.n_shared_experts is not None:
combined = combined + module.shared_experts(hidden_states)
return combined


def install_sorted_dispatch(model):
"""Replace only the 26 pinned MoE training forwards, leaving evaluation and parameters intact."""
modules = [module for module in model.modules() if type(module).__name__ == 'DeepseekV2MoE']
if len(modules) != 26:
raise ValueError('Expected all 26 official MoE layers, found {}.'.format(len(modules)))
if any(module.ep_size != 1 for module in modules):
raise ValueError('Stable expert dispatch does not implement expert parallelism.')
for module in modules:
original = module.forward
auxiliary_apply = sys.modules[type(module).__module__].AddAuxiliaryLoss.apply

def forward(self, hidden_states, original=original, auxiliary_apply=auxiliary_apply):
if not self.training:
return original(hidden_states)
return sorted_training_forward(self, hidden_states, auxiliary_apply)

module.forward = MethodType(forward, module)
return len(modules)
Loading
Loading