From 038a72dd08524e71c1e934da1e428110e464bd4f Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Wed, 28 Oct 2026 18:03:55 +0000 Subject: [PATCH 1/9] Benchmarks - Add official-checkpoint V2-Lite FSDP training Add deepseek-v2-lite-training, an opt-in benchmark that downloads the official DeepSeek-V2-Lite checkpoint and runs full-parameter BF16 FSDP training with real AdamW updates. - Loss and sampled-gradient checks against an unsharded official-code reference. - Optional stable-sorted expert dispatch; official dispatch remains the default. - Download-inclusive deadline and supervised worker cleanup. - Runtime image recipe, configuration, CPU tests and documentation. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../deepseek-v2-lite-training.dockerfile | 18 + .../deepseek-v2-lite-controller.in | 15 + .../deepseek-v2-lite-controller.txt | 81 ++++ .../deepseek-v2-lite-reference.txt | 5 + .../benchmarks/model-benchmarks.md | 148 +++++++ .../benchmarks/model_benchmarks/__init__.py | 3 +- .../model_benchmarks/deepseek_v2_lite_moe.py | 52 +++ .../deepseek_v2_lite_reference.py | 266 ++++++++++++ .../deepseek_v2_lite_training_worker.py | 299 ++++++++++++++ .../deepseek_v2_lite_utils.py | 364 +++++++++++++++++ .../pytorch_deepseek_v2_lite.py | 148 +++++++ .../config/deepseek-v2-lite-training.yaml | 25 ++ .../test_deepseek_v2_lite_moe.py | 144 +++++++ .../test_deepseek_v2_lite_reference.py | 377 ++++++++++++++++++ .../test_deepseek_v2_lite_training_worker.py | 285 +++++++++++++ .../test_deepseek_v2_lite_utils.py | 345 ++++++++++++++++ .../test_pytorch_deepseek_v2_lite.py | 146 +++++++ 17 files changed, 2720 insertions(+), 1 deletion(-) create mode 100644 dockerfile/deepseek-v2-lite-training.dockerfile create mode 100644 dockerfile/requirements/deepseek-v2-lite-controller.in create mode 100644 dockerfile/requirements/deepseek-v2-lite-controller.txt create mode 100644 dockerfile/requirements/deepseek-v2-lite-reference.txt create mode 100644 superbench/benchmarks/model_benchmarks/deepseek_v2_lite_moe.py create mode 100644 superbench/benchmarks/model_benchmarks/deepseek_v2_lite_reference.py create mode 100644 superbench/benchmarks/model_benchmarks/deepseek_v2_lite_training_worker.py create mode 100644 superbench/benchmarks/model_benchmarks/deepseek_v2_lite_utils.py create mode 100644 superbench/benchmarks/model_benchmarks/pytorch_deepseek_v2_lite.py create mode 100644 superbench/config/deepseek-v2-lite-training.yaml create mode 100644 tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_moe.py create mode 100644 tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_reference.py create mode 100644 tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_training_worker.py create mode 100644 tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_utils.py create mode 100644 tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py diff --git a/dockerfile/deepseek-v2-lite-training.dockerfile b/dockerfile/deepseek-v2-lite-training.dockerfile new file mode 100644 index 000000000..3780340f2 --- /dev/null +++ b/dockerfile/deepseek-v2-lite-training.dockerfile @@ -0,0 +1,18 @@ +FROM nvcr.io/nvidia/pytorch:25.08-py3@sha256:b70bc3ff73fae58e7ec326849b4726eac04200d9ec1da2b385f94c9f7775971f + +COPY dockerfile/requirements/deepseek-v2-lite-controller.txt /tmp/deepseek-v2-lite-controller.txt +RUN python3 -m venv --system-site-packages /opt/deepseek-reference && \ + /opt/deepseek-reference/bin/pip install --no-cache-dir --no-deps -r /tmp/deepseek-v2-lite-controller.txt + +WORKDIR /opt/superbench +COPY setup.py MANIFEST.in LICENSE README.md ./ +COPY superbench ./superbench +RUN /opt/deepseek-reference/bin/pip install --no-cache-dir --no-deps --no-build-isolation . && \ + /opt/deepseek-reference/bin/python -c "import numpy, torch, transformers; assert transformers.__version__ == '4.46.3'; assert torch.from_numpy(numpy.ones(1, dtype=numpy.float32)).numpy()[0] == 1" && \ + /opt/deepseek-reference/bin/sb run --help > /dev/null && \ + /opt/deepseek-reference/bin/sb result diagnosis --help > /dev/null + +RUN apt-get update && apt-get install -y --no-install-recommends rsync && apt-get clean + +ENV PATH="/opt/deepseek-reference/bin:${PATH}" +ENTRYPOINT ["sb"] diff --git a/dockerfile/requirements/deepseek-v2-lite-controller.in b/dockerfile/requirements/deepseek-v2-lite-controller.in new file mode 100644 index 000000000..cef428772 --- /dev/null +++ b/dockerfile/requirements/deepseek-v2-lite-controller.in @@ -0,0 +1,15 @@ +# Additional constraints for the dedicated Python 3.12 controller/reference runtime. +# Torch and torchvision are provided by the digest-pinned GPU base image. +# The NGC Torch build uses the NumPy 1.x ABI; keep its array bridge functional. +# Regenerate from the repository root with bash: +# uv pip compile setup.py dockerfile/requirements/deepseek-v2-lite-reference.txt \ +# dockerfile/requirements/deepseek-v2-lite-controller.in --python-version 3.12 \ +# --python-platform x86_64-unknown-linux-gnu --excludes <(printf 'torch\ntorchvision\n') \ +# --no-header --no-annotate -o dockerfile/requirements/deepseek-v2-lite-controller.txt +numpy==1.26.4 +pandas==2.2.3 +py3nvml==0.2.7 +setuptools==80.10.2 +setuptools-scm==10.3.4 +vcs-versioning==2.5.0 +wheel diff --git a/dockerfile/requirements/deepseek-v2-lite-controller.txt b/dockerfile/requirements/deepseek-v2-lite-controller.txt new file mode 100644 index 000000000..905fbf218 --- /dev/null +++ b/dockerfile/requirements/deepseek-v2-lite-controller.txt @@ -0,0 +1,81 @@ +# Generated for Python 3.12 / Linux x86_64 from setup.py, the reference pins, +# and deepseek-v2-lite-controller.in. The GPU base supplies torch/torchvision. +accelerate==1.2.1 +ansible==14.5.0 +ansible-core==2.21.5 +ansible-runner==2.4.3 +antlr4-python3-runtime==4.9.3 +argcomplete==3.7.2 +attrs==26.1.0 +certifi==2026.10.19 +cffi==2.1.1 +charset-normalizer==3.5.2 +click==8.5.0 +cloudpickle==3.1.2 +colorlog==6.12.0 +contourpy==1.3.3 +cryptography==50.0.2 +cycler==0.12.1 +et-xmlfile==2.0.0 +filelock==4.2.4 +fonttools==4.67.0 +fsspec==2026.9.0 +huggingface-hub==0.26.5 +idna==3.20 +importlib-metadata==9.0.1 +jinja2==3.1.6 +jmespath==1.1.0 +joblib==1.6.0 +jsonlines==4.0.0 +kiwisolver==1.5.1 +knack==0.14.0 +lockfile==0.12.2 +markdown==3.11.2 +markupsafe==3.0.4 +matplotlib==3.11.2 +natsort==8.4.0 +networkx==3.7 +numpy==1.26.4 +omegaconf==2.3.0 +openpyxl==3.1.5 +packaging==26.3 +pandas==2.2.3 +pexpect==4.9.0 +pillow==13.0.0 +prettytable==3.18.0 +protobuf==7.36.2 +pssh @ git+https://github.com/lilydjwg/pssh.git@2dce3d8e45a492985fa1ae0207b6d55afac97c16 +psutil==7.2.2 +ptyprocess==0.7.0 +py3nvml==0.2.7 +pycparser==3.11 +pygments==2.21.0 +pyparsing==3.3.3 +python-daemon==3.1.2 +python-dateutil==2.9.0.post0 +pytz==2026.5 +pyyaml==6.0.3 +regex==2026.9.29 +requests==2.34.2 +resolvelib==1.2.1 +safetensors==0.5.3 +seaborn==0.13.2 +setuptools==80.10.2 +setuptools-scm==10.3.4 +six==1.17.0 +tabulate==0.10.0 +tcping==0.1.1rc1 +tokenizers==0.20.3 +tqdm==4.70.1 +transformers==4.46.3 +types-requests==2.33.0.20261006 +typing-extensions==4.16.0 +tzdata==2026.5 +urllib3==2.8.0 +vcs-versioning==2.5.0 +wcwidth==0.9.3 +wheel==0.48.0 +xlrd==2.0.2 +xlsxwriter==3.2.9 +xmltodict==1.0.4 +zipp==4.1.2 diff --git a/dockerfile/requirements/deepseek-v2-lite-reference.txt b/dockerfile/requirements/deepseek-v2-lite-reference.txt new file mode 100644 index 000000000..e5ab4c95a --- /dev/null +++ b/dockerfile/requirements/deepseek-v2-lite-reference.txt @@ -0,0 +1,5 @@ +# Separate worker environment; do not replace SuperBench's framework dependencies. +transformers==4.46.3 +huggingface-hub==0.26.5 +accelerate==1.2.1 +safetensors==0.5.3 diff --git a/docs/user-tutorial/benchmarks/model-benchmarks.md b/docs/user-tutorial/benchmarks/model-benchmarks.md index c782abbcc..def2ed4aa 100644 --- a/docs/user-tutorial/benchmarks/model-benchmarks.md +++ b/docs/user-tutorial/benchmarks/model-benchmarks.md @@ -163,3 +163,151 @@ 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. | +## Official-checkpoint V2-Lite Training + +### `deepseek-v2-lite-training` + +This opt-in, standalone MODEL benchmark downloads and hash-verifies the complete +`deepseek-ai/DeepSeek-V2-Lite` checkpoint at +`604d5664dddd88a0433dbae533b7fe9472482de0`, then performs full-parameter causal-LM +training. It is not the Megatron benchmark, a classifier-head workload, LoRA, or +the reduced hidden-size configuration from PR #765. + +The model has 15,706,484,224 parameters, hidden size 2048, 27 layers, MLA and MoE. +The four BF16 weight files total 31,413,626,576 bytes. Initial optimizer state is +new: this is short training from pretrained weights, not a resume of DeepSeek's +original optimizer or an attempt to train a converged model within an hour. +The small `fixed-text-v1` fixture uses the official tokenizer and packed token +sequences without padding. It is reproducible, not a production-data accuracy +or representativeness evaluation. Mock data and mocked subprocesses are used +only in auxiliary unit tests. + +#### Validation Status + +This remains a draft implementation. Local H100 acceptance applies only to the +recorded four-GPU stable-sorted/native-allocator profile, its exact runtime and +the corresponding source/configuration identities. It does not qualify the +default official-dispatch example, every H100 configuration or other SKUs. +Publication and acceptance into delivery branches are separate from local +hardware validation. + +#### Runtime And Execution + +Use a separate worker environment; do not replace the legacy SuperBench +framework dependencies. The worker requires Python 3.10+, a GPU-compatible +PyTorch 2.5+ build, and the pinned packages in +[`deepseek-v2-lite-reference.txt`](../../../dockerfile/requirements/deepseek-v2-lite-reference.txt). +The supplied +[`model runtime Dockerfile`](../../../dockerfile/deepseek-v2-lite-training.dockerfile) +pins the CUDA PyTorch base by digest and installs the Python SuperBench +controller, runner and diagnosis entrypoints together with the worker/reference +environment. The +[`controller lock`](../../../dockerfile/requirements/deepseek-v2-lite-controller.txt) +is specific to Python 3.12/Linux x86_64 and retains the base image's GPU +Torch/torchvision builds. Its regeneration command is in the +[`lock inputs`](../../../dockerfile/requirements/deepseek-v2-lite-controller.in). +This opt-in model runtime does not replace the standard images or provide the +complete compiled microbenchmark suite. +The build checks the Torch/NumPy array bridge and the real runner/diagnosis CLI, +not just successful package installation. + +```bash +docker build -f dockerfile/deepseek-v2-lite-training.dockerfile -t sb-v2lite-training . +docker run --rm --gpus '"device=0,1,2,3"' --shm-size 32g \ + -v "$PWD/v2lite-results:/results" sb-v2lite-training exec \ + --config-file superbench/config/deepseek-v2-lite-training.yaml \ + --output-dir /results/sb-output \ + -C superbench.benchmarks.deepseek-v2-lite-training.parameters.cache_root=/results/model-cache +``` + +For a separately prepared native installation: +```bash +python3 -m venv --system-site-packages /opt/deepseek-reference +/opt/deepseek-reference/bin/pip install -r dockerfile/requirements/deepseek-v2-lite-reference.txt +sb exec --config-file superbench/config/deepseek-v2-lite-training.yaml +``` + +The native command assumes SuperBench is already installed in the controller's +environment. Change `runtime_python` if the prepared worker environment lives +elsewhere. Install a compatible CUDA/ROCm PyTorch build before preparing the +worker, rather than letting a generic package install choose the GPU backend. + +Select the +[`training profile`](../../../superbench/config/deepseek-v2-lite-training.yaml) +as its own benchmark entry, with one local launcher. The worker launches +`torchrun --standalone` across `num_gpus` local GPUs. Do not launch this entry +once per GPU or combine it with other models, precisions or actions under the +same deadline. `batch_size` is the microbatch per GPU. + +`moe_dispatch` defaults to `official`. The opt-in `stable_sorted` implementation +groups routed tokens with a stable sort instead of repeated Boolean indexing. +It preserves route order, every expert, router weights, shared experts and +auxiliary-loss gradients; it does not add expert parallelism or remove model +parameters. Only the 26 pinned MoE training forwards change. Evaluation and the +independent unsharded reference retain the official implementation. +The worker records the selected dispatch and rewritten-layer count, and the +adapter rejects missing or mismatched dispatch evidence. Choosing this option +does not by itself qualify a hardware profile or its one-hour budget. + +FSDP shards the full model, gradients and FP32 AdamW master/optimizer state. +Activation checkpointing is enabled for the measured workload. This is not +expert parallelism and does not qualify a Megatron or all-to-all dispatch path. +The default example uses four GPUs and microbatch two, retaining a global batch +of eight sequences. The complete profile also runs an unsharded BF16 loss and +gradient reference on one GPU; use 80GB-class GPUs for this initial example. +This is not a minimum-card proof or a recommendation to replicate the full +model with DDP: FP32 AdamW training state must fit across the selected shards. +Registration for CUDA/ROCm denotes an implementation route, not certification +of every GPU, runtime or memory configuration. + +#### Correctness, Timing And Results + +Before optimization, an unsharded official-code BF16 reference checks the +complete model's loss and sampled embedding, dense, MLA, router and active-expert +gradients against FSDP. Gradient probes include nonzero and distributed positions; +they are not an exhaustive comparison of every parameter. Every training step +requires finite loss and a finite nonzero global gradient norm. The first update +must change model parameters. No checkpoint missing-key or shape mismatch is +accepted. +The reference preserves every sequence of the actual global batch, full context +length and exact per-rank microbatch shape. It evaluates rank batches sequentially +with the complete model and activation checkpointing, requesting gradients only +for the existing probe parameter families. Other reference parameter-gradient +buffers are not materialized; no weights are removed or frozen. The measured +training worker still computes and updates the complete model. +Unused returned vocabulary logits are released before backward. Per-rank losses, +global loss and FP32-averaged gradient probes are checked separately. Replicating +one identical short input or regrouping BF16 rank batches would not establish +this distributed-reduction contract. +The one-time pre-update parameter snapshot is stored in host memory and checked +after the update. Model parameters, gradients and optimizer state remain on the +GPUs; this is validation storage, not training-state CPU offload. + +Every invocation creates its own empty HF/Hub/Xet/module cache and keeps its +report and logs under a new directory in `cache_root`. Shared caches are not +deleted. `duration` covers download, SHA256 verification, loading, correctness, +warmup, measured training and worker/rank teardown. It must be below 3600 seconds; +the controller reserves 20 seconds for cleanup. A watchdog exit is a failure. +Image pulling, dependency preparation and SuperBench installation are separate +runtime-preparation steps, not certified by the model-cold timer. + +A dedicated Linux child supervisor reaps the complete worker tree, including +torchrun ranks that start separate sessions. A launcher exit with surviving +descendants is a failure; timeout cleanup escalates from termination to forced +exit and verifies that owned children were reaped without targeting other jobs. +The worker records Unix timestamps bounding the measured phase for external +GPU telemetry; the step durations continue to use the monotonic clock. + +| Metric | Unit | Scope | +| --- | --- | --- | +| `bf16_train_step_time` | ms | Mean of the slowest synchronized rank per measured step | +| `bf16_train_tokens_per_second` | loss tokens/s | Global next-token targets, excluding each sequence's first position | +| `bf16_train_loss` | loss | Global mean causal-LM loss | +| `bf16_train_gradient_norm` | norm | Global gradient norm before clipping | +| `end_to_end_seconds` | s | Complete worker launch through exit and report validation | +| `checkpoint_bytes` | bytes | Complete weight files, not measured network traffic or GPU memory | + +Step timing includes forward, backward, clipping and the optimizer update. +Input preparation/copy and reference/update checks are excluded from the +steady step metric but included in the complete-job time. Keep model-cold +acceptance, per-GPU utilization and model quality as separate conclusions. diff --git a/superbench/benchmarks/model_benchmarks/__init__.py b/superbench/benchmarks/model_benchmarks/__init__.py index 818469822..c02c8e4ca 100644 --- a/superbench/benchmarks/model_benchmarks/__init__.py +++ b/superbench/benchmarks/model_benchmarks/__init__.py @@ -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: diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_moe.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_moe.py new file mode 100644 index 000000000..530f16b6c --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_moe.py @@ -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) diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_reference.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_reference.py new file mode 100644 index 000000000..1d6e05a6b --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_reference.py @@ -0,0 +1,266 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Unsharded official-code reference, executed in a separate pinned environment.""" + +import argparse +import gc +import os +from pathlib import Path + +from deepseek_v2_lite_utils import ( + FIXED_TEXTS, PARAMETER_COUNT, packed_tokens, read_json, uniform_indices, validate_config, write_json +) + +TRAINING_GRADIENT_PARAMETERS = { + 'model.embed_tokens.weight', + 'model.layers.0.self_attn.q_proj.weight', + 'model.layers.0.self_attn.kv_a_proj_with_mqa.weight', + 'model.layers.0.mlp.down_proj.weight', + 'model.layers.1.mlp.gate.weight', +} + + +def load_model(checkpoint, dtype): + """Load official causal-LM weights with no quantization or model reduction.""" + from importlib.metadata import version + + import torch + from transformers import AutoModelForCausalLM + + if version('transformers') != '4.46.3': + raise RuntimeError('The official-code reference requires transformers==4.46.3.') + validate_config(read_json(Path(checkpoint) / 'config.json')) + model, loading = AutoModelForCausalLM.from_pretrained( + checkpoint, + torch_dtype=dtype, + trust_remote_code=True, + local_files_only=True, + use_safetensors=True, + attn_implementation='eager', + output_loading_info=True, + ) + for key in ('missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs'): + if key not in loading or loading[key]: + raise RuntimeError('Official checkpoint loading failed: {}={!r}.'.format(key, loading.get(key))) + if sum(parameter.numel() for parameter in model.parameters()) != PARAMETER_COUNT: + raise RuntimeError('Loaded parameter count differs from the complete official V2-Lite.') + if not all(parameter.requires_grad for parameter in model.parameters()): + raise RuntimeError('The full-parameter profile must not freeze model parameters.') + if not torch.cuda.is_available(): + raise RuntimeError('CUDA/ROCm GPU unavailable in the reference environment.') + return model + + +def fixed_documents(checkpoint): + """Tokenize the small, versioned natural-text input with the official tokenizer.""" + from transformers import AutoTokenizer + + tokenizer = AutoTokenizer.from_pretrained(checkpoint, local_files_only=True, trust_remote_code=True) + return [tokenizer.encode(text, add_special_tokens=False) for text in FIXED_TEXTS], tokenizer.eos_token_id + + +def _training_gradient_probes(model, gradients): + """Select fixed dense/MLA/router/active-expert positions from the first rank batch.""" + import torch + + required = TRAINING_GRADIENT_PARAMETERS + probes = {} + expert_probe = False + for name, parameter in model.named_parameters(): + gradient = gradients.get(name) + if gradient is None: + continue + selected_expert = ( + not expert_probe and name.startswith('model.layers.1.mlp.experts.') and name.endswith('down_proj.weight') + and torch.count_nonzero(gradient).item() > 0 + ) + if name in required or selected_expert: + flat = gradient.detach().flatten() + nonzero = torch.nonzero(flat, as_tuple=False).flatten()[:512] + spread = torch.tensor(uniform_indices(flat.numel()), device=flat.device, dtype=torch.long) + indices = torch.unique(torch.cat((nonzero, spread))) + values = flat[indices].float().cpu() + if not torch.isfinite(values).all().item(): + raise RuntimeError('Nonfinite reference gradient: {}'.format(name)) + probes[name] = { + 'shape': list(parameter.shape), + 'indices': indices.cpu().tolist(), + 'values': torch.zeros_like(values) + } + if selected_expert: + expert_probe = True + if not required.issubset(probes) or not expert_probe: + raise RuntimeError('Required dense/MLA/router/expert reference gradients are missing.') + return probes + + +def training_reference(model, checkpoint, batch_size=1, seq_len=32, world_size=1): + """Reference exact rank batches without storing unrequested parameter gradients.""" + import torch + + if batch_size < 1 or seq_len < 32 or world_size < 1: + raise ValueError('Invalid training reference profile.') + documents, eos = fixed_documents(checkpoint) + model.train() + model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={'use_reentrant': False}) + tokens = packed_tokens(documents, eos, seq_len, batch_size * world_size) + losses, probes = [], {} + targets = { + name: parameter + for name, parameter in model.named_parameters() if name in TRAINING_GRADIENT_PARAMETERS or + (name.startswith('model.layers.1.mlp.experts.') and name.endswith('down_proj.weight')) + } + for rank in range(world_size): + batch = tokens[rank * batch_size:(rank + 1) * batch_size] + inputs = torch.tensor(batch, device='cuda', dtype=torch.long) + model.zero_grad(set_to_none=True) + output = model(input_ids=inputs, labels=inputs, use_cache=False) + loss = output.loss + del output + if loss is None or not torch.isfinite(loss).item(): + raise RuntimeError('Nonfinite or missing reference causal-LM loss.') + losses.append(loss.item()) + gradients = dict(zip(targets, torch.autograd.grad(loss, tuple(targets.values()), allow_unused=True))) + if not probes: + probes = _training_gradient_probes(model, gradients) + for name, probe in probes.items(): + gradient = gradients[name] + if gradient is None: + if '.experts.' not in name: + raise RuntimeError('Missing reference gradient: {}'.format(name)) + continue + indices = torch.tensor(probe['indices'], device=gradient.device, dtype=torch.long) + values = gradient.detach().flatten()[indices].float().cpu() + if not torch.isfinite(values).all().item(): + raise RuntimeError('Nonfinite reference gradient: {}'.format(name)) + probe['values'] += values / world_size + del gradients, loss, inputs + model.zero_grad(set_to_none=True) + for probe in probes.values(): + probe['values'] = probe['values'].tolist() + return { + 'tokens': tokens, + 'loss': sum(losses) / world_size, + 'loss_per_rank': losses, + 'gradients': probes, + 'batch_size': batch_size, + 'seq_len': seq_len, + 'world_size': world_size, + 'reference_microbatch_size': batch_size, + } + + +def inference_reference(model, requests): + """Compare cached decode to full-prefix logits and engine-selected logprobs.""" + import torch + + if not isinstance(requests, list) or not requests: + raise ValueError('Inference reference requests must be nonempty.') + model.eval() + comparisons = [] + with torch.no_grad(): + for request_index, request in enumerate(requests): + prompt = request['prompt_token_ids'] + completion = request['token_ids'] + logprobs = request['logprobs'] + if not prompt or not completion or len(completion) != len(logprobs): + raise ValueError('Incomplete inference reference request.') + full_prefix_steps = request.get('full_prefix_steps', list(range(len(completion)))) + if ( + not isinstance(full_prefix_steps, list) or not full_prefix_steps + or any(type(step) is not int + for step in full_prefix_steps) or full_prefix_steps != sorted(set(full_prefix_steps)) + or full_prefix_steps[0] != 0 or full_prefix_steps[-1] != len(completion) - 1 + ): + raise ValueError('Full-prefix reference positions must include ordered first and final steps.') + prefix = torch.tensor([prompt], device='cuda', dtype=torch.long) + cache = None + for step, token in enumerate(completion): + attention_mask = torch.ones_like(prefix) + output = model( + input_ids=prefix if step == 0 else prefix[:, -1:], + attention_mask=attention_mask, + past_key_values=cache, + use_cache=True + ) + cache = output.past_key_values + cached = output.logits[:, -1, :].float() + check_full_prefix = step in full_prefix_steps + full = ( + model(input_ids=prefix, attention_mask=attention_mask, use_cache=False).logits[:, -1, :].float() + if check_full_prefix else cached + ) + if not torch.isfinite(cached).all().item() or not torch.isfinite(full).all().item(): + raise RuntimeError('Nonfinite reference logits.') + if check_full_prefix: + torch.testing.assert_close(cached, full, rtol=0.02, atol=0.05) + if full[0].argmax().item() != token: + raise RuntimeError('Engine greedy token differs at request {} step {}.'.format(request_index, step)) + expected = torch.log_softmax(full[0], dim=-1) + ids = [int(value) for value in logprobs[step]] + if token not in ids or not ids: + raise ValueError('Missing selected-token engine log probability.') + actual = torch.tensor([logprobs[step][str(value)] for value in ids], device='cuda') + target = expected[ids] + torch.testing.assert_close( + actual, + target, + rtol=0.02, + atol=0.05, + msg=lambda message: 'Engine/reference request {} step {}:\n{}'.format(request_index, step, message), + ) + comparisons.append( + { + 'request': request_index, + 'step': step, + 'logprob_positions': len(ids), + 'full_prefix_checked': check_full_prefix, + 'cache_max_abs_error': (cached - full).abs().max().item() if check_full_prefix else None, + 'engine_logprob_max_abs_error': (actual - target).abs().max().item(), + } + ) + prefix = torch.cat((prefix, torch.tensor([[token]], device='cuda')), dim=1) + return {'comparisons': comparisons, 'logprob_rtol': 0.02, 'logprob_atol': 0.05} + + +def main(): + """Run a bounded reference and write only numeric/token-ID evidence.""" + import torch + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--checkpoint', required=True) + parser.add_argument('--mode', choices=['training', 'inference'], required=True) + parser.add_argument('--requests') + parser.add_argument('--output', required=True) + parser.add_argument('--batch_size', type=int, default=1) + parser.add_argument('--seq_len', type=int, default=32) + parser.add_argument('--world_size', type=int, default=1) + args = parser.parse_args() + torch.cuda.set_device(0) + os.environ['TORCH_ALLOW_TF32_CUBLAS_OVERRIDE'] = '0' + torch.backends.cuda.matmul.allow_tf32 = False + dtype = torch.bfloat16 if args.mode == 'training' else torch.float32 + model = load_model(args.checkpoint, dtype).cuda() + try: + if args.mode == 'training': + result = training_reference(model, args.checkpoint, args.batch_size, args.seq_len, args.world_size) + else: + if not args.requests: + raise ValueError('--requests is required for inference reference.') + result = inference_reference(model, read_json(Path(args.requests))) + torch.cuda.synchronize() + finally: + del model + gc.collect() + torch.cuda.empty_cache() + torch.cuda.synchronize() + result['correctness_passed'] = True + result['teardown_complete'] = True + result['reference_dtype'] = str(dtype) + result['tf32_allowed'] = False + write_json(Path(args.output), result) + + +if __name__ == '__main__': + main() diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_training_worker.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_training_worker.py new file mode 100644 index 000000000..8e61e5d36 --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_training_worker.py @@ -0,0 +1,299 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Full-parameter BF16 V2-Lite training, launched once through torchrun.""" + +import argparse +import gc +import os +import signal +import time +from datetime import timedelta +from functools import partial +from pathlib import Path + +from deepseek_v2_lite_moe import MOE_DISPATCHES, install_sorted_dispatch +from deepseek_v2_lite_reference import fixed_documents, load_model, training_reference +from deepseek_v2_lite_utils import ( + configure_cache, download_checkpoint, identity_report, interrupt_worker, packed_tokens, read_json, + set_cache_environment, write_json +) + + +def compare_gradients(model, reference): + """Unshard one layer at a time to check sampled dense, MLA and MoE gradients.""" + import torch + from torch.distributed.fsdp import FullyShardedDataParallel as FSDP + + groups = {} + for name, probe in reference['gradients'].items(): + if name.startswith('model.layers.'): + layer = int(name.split('.')[2]) + unit = model.module.model.layers[layer] + relative_name = '.'.join(name.split('.')[3:]) + key = layer + else: + unit = model + relative_name = name + key = -1 + groups.setdefault(key, (unit, []))[1].append((relative_name, probe)) + errors = [] + for unit, probes in groups.values(): + with FSDP.summon_full_params(unit, recurse=False, writeback=False, with_grads=True): + for name, probe in probes: + parameter = unit.module.get_parameter(name) + if list(parameter.shape) != probe['shape'] or parameter.grad is None: + raise RuntimeError('Missing or incorrectly shaped full gradient: {}'.format(name)) + indices = torch.tensor(probe['indices'], device='cuda', dtype=torch.long) + actual = parameter.grad.detach().flatten()[indices].float() + expected = torch.tensor(probe['values'], device='cuda', dtype=torch.float32) + torch.testing.assert_close( + actual, + expected, + rtol=0.025, + atol=1e-5, + msg=lambda message: 'Gradient reference {}:\n{}'.format(name, message), + ) + errors.append((actual - expected).abs().max().item()) + return max(errors) + + +def training_step(model, optimizer, inputs, verify_update=False): + """Run real loss, backward, gradient clipping and an AdamW parameter update.""" + import torch + import torch.distributed as dist + + optimizer.zero_grad(set_to_none=True) + before = [parameter.detach().to('cpu', copy=True) for parameter in model.parameters()] if verify_update else [] + torch.cuda.synchronize() + start = time.monotonic() + output = model(input_ids=inputs, labels=inputs, use_cache=False) + loss = output.loss + del output + if loss is None or not torch.isfinite(loss).item(): + raise RuntimeError('Missing or nonfinite causal-LM loss.') + loss.backward() + gradient_norm = model.clip_grad_norm_(1.0) + if not torch.isfinite(gradient_norm).item() or gradient_norm.item() <= 0: + raise RuntimeError('Missing, zero or nonfinite full-model gradient norm.') + optimizer.step() + torch.cuda.synchronize() + elapsed_ms = (time.monotonic() - start) * 1000 + changed = 0 + if verify_update: + for previous, parameter in zip(before, model.parameters()): + difference = parameter.detach().cpu() - previous + if not torch.isfinite(difference).all().item(): + raise RuntimeError('Optimizer produced nonfinite model parameters.') + changed += torch.count_nonzero(difference).item() + count = torch.tensor(changed, device='cuda', dtype=torch.int64) + dist.all_reduce(count) + changed = count.item() + if changed <= 0: + raise RuntimeError('AdamW did not update model parameters.') + average_loss = loss.detach().float() + dist.all_reduce(average_loss) + average_loss /= dist.get_world_size() + return elapsed_ms, average_loss.item(), gradient_norm.item(), changed + + +def run_training(args, reference, checkpoint): + """Train the complete checkpoint with per-layer FSDP and FP32 optimizer state.""" + import torch + import torch.distributed as dist + from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( + CheckpointImpl, apply_activation_checkpointing, checkpoint_wrapper + ) + from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy + from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy + + world_size = dist.get_world_size() + if ( + reference.get('batch_size') != args.batch_size or reference.get('seq_len') != args.seq_len + or reference.get('world_size') != world_size or reference.get('reference_microbatch_size') != args.batch_size + ): + raise ValueError('Training reference does not match the actual global profile.') + rank = dist.get_rank() + rank_tokens = reference['tokens'][rank * args.batch_size:(rank + 1) * args.batch_size] + if len(reference['tokens']) != world_size * args.batch_size or len(rank_tokens) != args.batch_size: + raise ValueError('Training reference has an incomplete global batch.') + if args.moe_dispatch not in MOE_DISPATCHES: + raise ValueError('Unsupported MoE training dispatch.') + model = load_model(str(checkpoint), torch.float32) + rewritten_layers = install_sorted_dispatch(model) if args.moe_dispatch == 'stable_sorted' else 0 + decoder_type = type(model.model.layers[0]) + model = FSDP( + model, + auto_wrap_policy=partial(transformer_auto_wrap_policy, transformer_layer_cls={decoder_type}), + mixed_precision=MixedPrecision(param_dtype=torch.bfloat16, reduce_dtype=torch.float32), + sharding_strategy=ShardingStrategy.FULL_SHARD, + device_id=torch.cuda.current_device(), + use_orig_params=True, + limit_all_gathers=True, + ) + model.train() + apply_activation_checkpointing( + model, + checkpoint_wrapper_fn=partial(checkpoint_wrapper, checkpoint_impl=CheckpointImpl.NO_REENTRANT), + check_fn=lambda module: isinstance(module, decoder_type), + ) + correctness_inputs = torch.tensor(rank_tokens, device='cuda', dtype=torch.long) + output = model(input_ids=correctness_inputs, labels=correctness_inputs, use_cache=False) + loss = output.loss + del output + torch.testing.assert_close( + loss.float(), torch.tensor(reference['loss_per_rank'][rank], device='cuda'), rtol=0.005, atol=0.01 + ) + global_loss = loss.detach().float().clone() + dist.all_reduce(global_loss) + global_loss /= world_size + torch.testing.assert_close(global_loss, torch.tensor(reference['loss'], device='cuda'), rtol=0.005, atol=0.01) + loss.backward() + gradient_error = compare_gradients(model, reference) + model.zero_grad(set_to_none=True) + del loss, correctness_inputs, global_loss + gc.collect() + torch.cuda.empty_cache() + optimizer = torch.optim.AdamW( + model.parameters(), lr=args.learning_rate, betas=(0.9, 0.95), weight_decay=0.1, foreach=False + ) + documents, eos = fixed_documents(str(checkpoint)) + local_rank = int(os.environ['LOCAL_RANK']) + step_times, losses, norms = [], [], [] + updated_parameters = 0 + measurement_start = None + measurement_end = None + torch.cuda.reset_peak_memory_stats() + try: + for step in range(args.num_warmup + args.num_steps): + offset = (step * dist.get_world_size() + dist.get_rank()) * args.batch_size * args.seq_len + tokens = packed_tokens(documents, eos, args.seq_len, args.batch_size, offset) + inputs = torch.tensor(tokens, device='cuda', dtype=torch.long) + if step == args.num_warmup: + torch.cuda.synchronize() + measurement_start = time.time() + elapsed, loss, norm, changed = training_step(model, optimizer, inputs, verify_update=step == 0) + updated_parameters += changed + maximum_time = torch.tensor(elapsed, device='cuda', dtype=torch.float64) + dist.all_reduce(maximum_time, op=dist.ReduceOp.MAX) + if step >= args.num_warmup: + step_times.append(maximum_time.item()) + losses.append(loss) + norms.append(norm) + measurement_end = time.time() + if dist.get_rank() == 0: + print( + 'step={} global_loss={:.6f} max_rank_ms={:.3f}'.format(step, loss, maximum_time.item()), flush=True + ) + memory = torch.tensor(torch.cuda.max_memory_allocated(), device='cuda', dtype=torch.int64) + all_memory = [torch.zeros_like(memory) for _ in range(dist.get_world_size())] + dist.all_gather(all_memory, memory) + return { + 'step_ms': step_times, + 'loss': losses, + 'gradient_norm': norms, + 'updated_parameter_elements': updated_parameters, + 'gradient_probe_max_abs_error': gradient_error, + 'gradient_probe_rtol': 0.025, + 'gradient_probe_atol': 1e-5, + 'loss_token_count': args.num_steps * args.batch_size * dist.get_world_size() * (args.seq_len - 1), + 'peak_memory_bytes_per_gpu': [value.item() for value in all_memory], + 'world_size': dist.get_world_size(), + 'local_rank': local_rank, + 'optimizer': 'AdamW, FP32 master parameters and moments', + 'optimizer_resumed': False, + 'training_parallelism': 'FSDP full shard; no expert parallelism', + 'moe_dispatch': args.moe_dispatch, + 'moe_layers_rewritten': rewritten_layers, + 'measurement_start_unix_seconds': measurement_start, + 'measurement_end_unix_seconds': measurement_end, + } + finally: + del optimizer, model + gc.collect() + torch.cuda.empty_cache() + torch.cuda.synchronize() + + +def main(): + """Include download, identity, reference, warmup and teardown in one job.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--cache_dir', type=Path, required=True) + parser.add_argument('--output', type=Path, required=True) + parser.add_argument('--num_gpus', type=int, required=True) + parser.add_argument('--batch_size', type=int, default=1) + parser.add_argument('--seq_len', type=int, default=512) + parser.add_argument('--num_warmup', type=int, default=2) + parser.add_argument('--num_steps', type=int, default=8) + parser.add_argument('--learning_rate', type=float, default=1e-5) + parser.add_argument('--moe_dispatch', choices=MOE_DISPATCHES, default='official') + parser.add_argument('--duration', type=int, default=3300) + args = parser.parse_args() + start = time.monotonic() + signal.signal(signal.SIGTERM, interrupt_worker) + os.environ['TORCH_ALLOW_TF32_CUBLAS_OVERRIDE'] = '0' + set_cache_environment(args.cache_dir) + import torch + import torch.distributed as dist + + rank = int(os.environ['RANK']) + local_rank = int(os.environ['LOCAL_RANK']) + if int(os.environ['WORLD_SIZE']) != args.num_gpus or torch.cuda.device_count() < args.num_gpus: + raise ValueError('torchrun world size and visible GPU count must match num_gpus.') + if args.num_gpus < 2 or args.batch_size < 1 or args.seq_len < 32 or args.num_warmup < 0 or args.num_steps < 1: + raise ValueError('Invalid full-model training dimensions.') + if not 0 < args.learning_rate < 1 or not 30 < args.duration < 3600: + raise ValueError('Invalid learning rate or download-inclusive duration.') + torch.cuda.set_device(local_rank) + torch.backends.cuda.matmul.allow_tf32 = False + torch.manual_seed(20261015) + dist.init_process_group( + backend='nccl', timeout=timedelta(seconds=args.duration), device_id=torch.device('cuda', local_rank) + ) + control_group = dist.new_group(backend='gloo', timeout=timedelta(seconds=args.duration)) + report = identity_report() + checkpoint = args.cache_dir / 'checkpoint' + reference_path = args.output.parent / 'training-reference.json' + try: + download_start = time.monotonic() + if rank == 0: + configure_cache(args.cache_dir) + checkpoint = download_checkpoint(args.cache_dir) + dist.barrier(group=control_group) + report['download_verify_seconds'] = time.monotonic() - download_start + reference_start = time.monotonic() + if rank == 0: + reference_model = load_model(str(checkpoint), torch.bfloat16).cuda() + try: + write_json( + reference_path, + training_reference(reference_model, str(checkpoint), args.batch_size, args.seq_len, args.num_gpus) + ) + finally: + del reference_model + gc.collect() + torch.cuda.empty_cache() + torch.cuda.synchronize() + dist.barrier(group=control_group) + reference = read_json(reference_path) + report['reference_seconds'] = time.monotonic() - reference_start + training_start = time.monotonic() + report.update(run_training(args, reference, checkpoint)) + report['training_seconds'] = time.monotonic() - training_start + report['correctness_passed'] = True + report['torch_version'] = torch.__version__ + report['gpu_names'] = [torch.cuda.get_device_name(index) for index in range(args.num_gpus)] + finally: + dist.destroy_process_group(control_group) + dist.destroy_process_group() + if rank == 0: + report['teardown_complete'] = True + report['total_seconds'] = time.monotonic() - start + if report['total_seconds'] >= args.duration: + raise TimeoutError('Training exceeded the download-inclusive duration.') + report['status'] = 'success' + write_json(args.output, report) + + +if __name__ == '__main__': + main() diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_utils.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_utils.py new file mode 100644 index 000000000..ca73360ef --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_utils.py @@ -0,0 +1,364 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Checkpoint, input and subprocess contracts for the fixed V2-Lite workload.""" + +import hashlib +import json +import math +import os +import signal +import subprocess +import sys +import time +from pathlib import Path +from typing import Dict, List, Sequence + +MODEL_ID = 'deepseek-ai/DeepSeek-V2-Lite' +REVISION = '604d5664dddd88a0433dbae533b7fe9472482de0' +PARAMETER_COUNT = 15706484224 +WEIGHT_FILES = { + 'model-00001-of-000004.safetensors': + (8594887408, '0d7e9f39bde40111a4c0f390b87497dce4565cf578d916395e6b2c7851f1e8da'), + 'model-00002-of-000004.safetensors': + (8591757448, 'e0656832b0d594b4a64cad40ff8465231de6ed44c854f74f6b217797660aa4bb'), + 'model-00003-of-000004.safetensors': + (8590718520, '843ec689624f3a520526e040f0326c4dc9865e8172942ca98a084fe136fdb21a'), + 'model-00004-of-000004.safetensors': + (5636263200, 'cfb51658f67cedfbbc4d62ad14187830ceec8ee82c788c5f718feea98905ef31'), +} +WEIGHT_BYTES = sum(size for size, _ in WEIGHT_FILES.values()) +EXPECTED_CONFIG = { + 'hidden_size': 2048, + 'num_hidden_layers': 27, + 'num_attention_heads': 16, + 'intermediate_size': 10944, + 'moe_intermediate_size': 1408, + 'n_routed_experts': 64, + 'n_shared_experts': 2, + 'num_experts_per_tok': 6, + 'first_k_dense_replace': 1, + 'kv_lora_rank': 512, + 'q_lora_rank': None, + 'qk_nope_head_dim': 128, + 'qk_rope_head_dim': 64, + 'v_head_dim': 128, + 'vocab_size': 102400, + 'seq_aux': True, + 'aux_loss_alpha': 0.001, + 'attention_dropout': 0.0, +} +FIXED_TEXTS = ( + 'The engineering team measures a system before changing its configuration. ' + 'Each measurement records the input, the software version, and the observation time.', + 'A warehouse receives several shipments each morning. Workers check the labels, ' + 'sort the packages by destination, and keep a record of damaged items.', + 'A weather station samples temperature and wind speed at regular intervals. ' + 'Missing readings are reported explicitly instead of being replaced with zero.', + 'The library contains books about science, history, and music. Readers can search ' + 'the catalog, reserve an available book, and return it at the front desk.', + 'A numerical experiment compares two implementations on the same input. ' + 'The result includes the error tolerance and every failed comparison.', + 'A small garden has three rows of vegetables and a rainwater tank. ' + 'The gardener checks soil moisture before deciding how much water to use.', + 'The train arrives at the northern platform at eight in the morning. ' + 'Passengers check their tickets and leave space for people getting off.', + 'A computer processes a sequence of tokens using a language model. ' + 'Training computes a loss and gradients, while generation reuses attention state.', +) +INPUT_SHA256 = hashlib.sha256('\n'.join(FIXED_TEXTS).encode('utf-8')).hexdigest() + + +def read_json(path: Path): + """Read a JSON document without accepting nonfinite JSON constants.""" + def reject_constant(value): + raise ValueError('Nonfinite JSON constant: {}'.format(value)) + + with path.open() as stream: + return json.load(stream, parse_constant=reject_constant) + + +def write_json(path: Path, document) -> None: + """Write a complete report atomically, rejecting nonfinite numbers.""" + temporary = path.with_suffix(path.suffix + '.tmp') + with temporary.open('w') as stream: + json.dump(document, stream, indent=2, allow_nan=False) + stream.write('\n') + temporary.replace(path) + + +def validate_config(config) -> None: + """Reject a reduced, quantized or different model configuration.""" + if not isinstance(config, dict) or config.get('model_type') != 'deepseek_v2': + raise ValueError('Expected the official DeepSeek-V2 configuration.') + for key, expected in EXPECTED_CONFIG.items(): + if key not in config or config[key] != expected: + raise ValueError('Official V2-Lite {} must be {!r}, got {!r}.'.format(key, expected, config.get(key))) + if config.get('quantization_config') is not None: + raise ValueError('This profile does not accept quantized checkpoints.') + + +def configure_cache(cache: Path) -> None: + """Isolate all model caches without reading or removing shared caches.""" + cache.mkdir(parents=True, exist_ok=True) + if any(cache.iterdir()): + raise ValueError('Cold-start cache must be empty: {}'.format(cache)) + set_cache_environment(cache) + + +def set_cache_environment(cache: Path) -> None: + """Select the same isolated cache in each distributed worker.""" + for variable, directory in { + 'HF_HOME': 'hf', + 'HF_HUB_CACHE': 'hub', + 'HF_XET_CACHE': 'xet', + 'HF_MODULES_CACHE': 'modules', + 'TRANSFORMERS_CACHE': 'transformers', + }.items(): + os.environ[variable] = str(cache / directory) + os.environ['HF_HUB_DISABLE_IMPLICIT_TOKEN'] = '1' + os.environ['HF_HUB_DISABLE_TELEMETRY'] = '1' + + +def verify_checkpoint(checkpoint: Path) -> None: + """Verify the complete fixed checkpoint, its index and every weight hash.""" + validate_config(read_json(checkpoint / 'config.json')) + index = read_json(checkpoint / 'model.safetensors.index.json') + if not isinstance(index, dict) or not isinstance(index.get('weight_map'), dict): + raise ValueError('Missing checkpoint weight map.') + if set(index['weight_map'].values()) != set(WEIGHT_FILES): + raise ValueError('Checkpoint index does not describe the four official weight shards.') + for filename, (size, expected_hash) in WEIGHT_FILES.items(): + path = checkpoint / filename + if not path.is_file() or path.stat().st_size != size: + raise ValueError('Missing or incorrectly sized checkpoint shard: {}'.format(filename)) + digest = hashlib.sha256() + with path.open('rb') as stream: + for block in iter(lambda: stream.read(8 * 1024 * 1024), b''): + digest.update(block) + if digest.hexdigest() != expected_hash: + raise ValueError('Checkpoint SHA256 mismatch: {}'.format(filename)) + + +def download_checkpoint(cache: Path) -> Path: + """Download and verify official weights before any GPU model construction.""" + from huggingface_hub import snapshot_download + + checkpoint = cache / 'checkpoint' + snapshot_download( + repo_id=MODEL_ID, + revision=REVISION, + local_dir=str(checkpoint), + cache_dir=str(cache / 'hub'), + allow_patterns=list(WEIGHT_FILES) + [ + 'config.json', 'generation_config.json', 'model.safetensors.index.json', 'tokenizer*', + 'special_tokens_map.json', '*.py' + ], + token=False, + max_workers=4, + ) + verify_checkpoint(checkpoint) + return checkpoint + + +def packed_tokens(documents: Sequence[Sequence[int]], + eos: int, + length: int, + count: int, + offset: int = 0) -> List[List[int]]: + """Pack deterministic real-text tokens without padding a pressure workload.""" + if length < 2 or count < 1 or offset < 0 or not documents or eos < 0: + raise ValueError('Invalid packed-input dimensions or documents.') + stream: List[int] = [] + for document in documents: + if not document or any(type(token) is not int or token < 0 for token in document): + raise ValueError('Each document must contain nonnegative integer token IDs.') + stream.extend(document) + stream.append(eos) + return [ + [stream[(offset + row * length + column) % len(stream)] for column in range(length)] for row in range(count) + ] + + +def numeric_series(report, name: str, count: int, positive: bool = True) -> List[float]: + """Require a complete finite metric series, never a default or sentinel.""" + values = report.get(name) if isinstance(report, dict) else None + if not isinstance(values, list) or len(values) != count: + raise ValueError('Expected {} {} samples.'.format(count, name)) + if any( + isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or + (positive and value <= 0) for value in values + ): + raise ValueError('Invalid numeric metric: {}'.format(name)) + return [float(value) for value in values] + + +def uniform_indices(length: int, count: int = 256) -> List[int]: + """Sample large tensor offsets with integer arithmetic, never FP32 rounding.""" + if length < 1 or count < 2: + raise ValueError('Invalid tensor length or sample count.') + return [position * (length - 1) // (count - 1) for position in range(count)] + + +def _owned_children() -> List[int]: + """Read the dedicated supervisor's direct and adopted children.""" + path = Path('/proc/self/task/{}/children'.format(os.getpid())) + return [int(pid) for pid in path.read_text().split()] + + +def _reap_children() -> None: + """Reap exited owned children so no stale PID is treated as running.""" + while True: + try: + pid, _ = os.waitpid(-1, os.WNOHANG) + except ChildProcessError: + return + if pid == 0: + return + + +def _stop_children() -> None: + """Reap all job descendants, including ranks that created new sessions.""" + graceful_deadline = time.monotonic() + 10 + deadline = graceful_deadline + 5 + while True: + children = _owned_children() + if not children: + return + current = time.monotonic() + if current >= deadline: + raise RuntimeError('Owned worker descendants did not exit: {}.'.format(children)) + signum = signal.SIGTERM if current < graceful_deadline else signal.SIGKILL + for pid in children: + try: + os.kill(pid, signum) + except ProcessLookupError: + pass + _reap_children() + time.sleep(0.02) + + +def supervise_worker(command: List[str], timeout: float, parent_pid: int) -> int: + """Contain Linux worker descendants in a separate single-threaded supervisor.""" + import ctypes + + if sys.platform != 'linux': + raise RuntimeError('The isolated model worker supervisor requires Linux.') + libc = ctypes.CDLL(None, use_errno=True) + interrupted = False + + def stop(signum, frame): + nonlocal interrupted + interrupted = True + + signal.signal(signal.SIGTERM, stop) + signal.signal(signal.SIGINT, stop) + # Adopt orphaned rank sessions and clean up if the controller itself dies. + for option, value in [(36, 1), (1, signal.SIGTERM)]: # PR_SET_CHILD_SUBREAPER, PR_SET_PDEATHSIG + if libc.prctl(option, ctypes.c_ulong(value), ctypes.c_ulong(0), ctypes.c_ulong(0), ctypes.c_ulong(0)) != 0: + error = ctypes.get_errno() + raise OSError(error, os.strerror(error)) + if os.getppid() != parent_pid: + return 124 + deadline = time.monotonic() + timeout + process = subprocess.Popen(command) + try: + while process.poll() is None: + if interrupted or time.monotonic() >= deadline: + return 124 + time.sleep(0.02) + code = process.wait() + _reap_children() + if code == 0 and _owned_children(): + print('Worker exited with live descendant processes.', file=sys.stderr, flush=True) + return 125 + return code if code >= 0 else 128 - code + finally: + _stop_children() + process.wait() + + +def interrupt_worker(signum, frame) -> None: + """Unwind subprocess waits so nested reference workers are cleaned up.""" + raise TimeoutError('Model worker interrupted by signal {}.'.format(signum)) + + +def run_worker(command: List[str], log: Path, timeout: float) -> None: + """Supervise the whole worker tree under one deadline, preserving failure logs.""" + if not math.isfinite(timeout) or timeout <= 0: + raise TimeoutError('No time remains for the worker.') + if not command: + raise ValueError('The model worker command must not be empty.') + supervisor = [ + sys.executable, + str(Path(__file__).resolve()), + '--worker-timeout', + str(timeout), + '--parent-pid', + str(os.getpid()), + '--', + *command, + ] + with log.open('w') as stream: + process = subprocess.Popen(supervisor, stdout=stream, stderr=subprocess.STDOUT, start_new_session=True) + try: + try: + code = process.wait(timeout=timeout + 20) + except subprocess.TimeoutExpired as error: + raise TimeoutError('Model worker supervisor exceeded its cleanup deadline.') from error + if code == 124: + raise TimeoutError('Model worker exceeded the download-inclusive deadline.') + if code == 125: + raise RuntimeError('Model worker left descendant processes running; see {}.'.format(log)) + if code != 0: + raise RuntimeError('Model worker exited with code {}; see {}.'.format(code, log)) + finally: + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=20) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + raise RuntimeError('Model worker supervisor did not complete descendant cleanup.') + + +def identity_report() -> Dict[str, object]: + """Describe the fixed model and input contract without generated text.""" + return { + 'model_id': MODEL_ID, + 'revision': REVISION, + 'weight_bytes': WEIGHT_BYTES, + 'weight_sha256': {name: digest + for name, (_, digest) in WEIGHT_FILES.items()}, + 'parameter_count': PARAMETER_COUNT, + 'precision': 'bfloat16', + 'input_dataset': 'fixed-text-v1', + 'input_sha256': INPUT_SHA256, + 'cold_cache': True, + } + + +def validate_identity(report) -> None: + """Require a successful official-model report before accepting any metrics.""" + expected = identity_report() + if not isinstance(report, dict) or report.get('status') != 'success': + raise ValueError('Worker did not produce a successful model report.') + if any(report.get(key) != value for key, value in expected.items()): + raise ValueError('Worker report does not match the official checkpoint/input contract.') + if report.get('correctness_passed') is not True or report.get('teardown_complete') is not True: + raise ValueError('Correctness or worker teardown was not completed.') + + +if __name__ == '__main__': + import argparse + + parser = argparse.ArgumentParser(description='Supervise one isolated model worker command.') + parser.add_argument('--worker-timeout', type=float, required=True) + parser.add_argument('--parent-pid', type=int, required=True) + parser.add_argument('command', nargs=argparse.REMAINDER) + arguments = parser.parse_args() + worker_command = arguments.command[1:] if arguments.command[:1] == ['--'] else arguments.command + if not worker_command or not math.isfinite(arguments.worker_timeout) or arguments.worker_timeout <= 0: + parser.error('A worker command and finite positive timeout are required.') + sys.exit(supervise_worker(worker_command, arguments.worker_timeout, arguments.parent_pid)) diff --git a/superbench/benchmarks/model_benchmarks/pytorch_deepseek_v2_lite.py b/superbench/benchmarks/model_benchmarks/pytorch_deepseek_v2_lite.py new file mode 100644 index 000000000..bf290ff60 --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/pytorch_deepseek_v2_lite.py @@ -0,0 +1,148 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""SuperBench adapter for isolated official-checkpoint V2-Lite FSDP training.""" + +import os +import statistics +import sys +import tempfile +import time +from pathlib import Path + +from superbench.benchmarks import BenchmarkRegistry, BenchmarkType, Platform, ReturnCode +from superbench.benchmarks.base import Benchmark +from superbench.common.utils import logger +from superbench.benchmarks.model_benchmarks.deepseek_v2_lite_moe import MOE_DISPATCHES +from superbench.benchmarks.model_benchmarks.deepseek_v2_lite_utils import ( + numeric_series, read_json, run_worker, validate_identity +) + + +class DeepSeekV2LiteTraining(Benchmark): + """Run one official BF16 checkpoint through a separate FSDP worker runtime.""" + def __init__(self, name, parameters=''): + """Initialize the fixed model benchmark without importing its new runtime.""" + super().__init__(name, parameters) + self._benchmark_type = BenchmarkType.MODEL + + def add_parser_arguments(self): + """Configure exactly one download-inclusive training profile.""" + super().add_parser_arguments() + self._parser.set_defaults(duration=3300) + self._parser.add_argument('--runtime_python', type=str, default=sys.executable) + self._parser.add_argument('--cache_root', type=str, default='model-cache') + self._parser.add_argument('--num_gpus', type=int, default=4) + self._parser.add_argument('--batch_size', type=int, default=2, help='Microbatch per GPU.') + self._parser.add_argument('--seq_len', type=int, default=512) + self._parser.add_argument('--num_warmup', type=int, default=2) + self._parser.add_argument('--num_steps', type=int, default=8) + self._parser.add_argument('--learning_rate', type=float, default=1e-5) + self._parser.add_argument('--moe_dispatch', choices=MOE_DISPATCHES, default='official') + + def _preprocess(self): + """Reject unsupported execution modes and invalid shapes explicitly.""" + if not super()._preprocess(): + return False + args = self._args + invalid = ( + args.run_count != 1 or not 30 < args.duration < 3600 or args.num_gpus < 2 or args.batch_size < 1 + or args.seq_len < 32 or args.num_warmup < 0 or args.num_steps < 1 or not 0 < args.learning_rate < 1 + ) + try: + world_size = int(os.environ.get('WORLD_SIZE', os.environ.get('OMPI_COMM_WORLD_SIZE', '1'))) + except ValueError: + logger.error('V2-Lite training launcher world size must be an integer.') + self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) + return False + if invalid or world_size != 1: + logger.error('V2-Lite training requires one local launcher, valid positive dimensions and duration <3600s.') + self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) + return False + return True + + def _worker_command(self, job): + """Launch all local GPUs once, retaining argv boundaries.""" + worker = Path(__file__).with_name('deepseek_v2_lite_training_worker.py') + args = self._args + return [ + args.runtime_python, + '-m', + 'torch.distributed.run', + '--standalone', + '--nproc_per_node={}'.format(args.num_gpus), + str(worker), + '--cache_dir', + str(job / 'cache'), + '--output', + str(job / 'report.json'), + '--num_gpus', + str(args.num_gpus), + '--batch_size', + str(args.batch_size), + '--seq_len', + str(args.seq_len), + '--num_warmup', + str(args.num_warmup), + '--num_steps', + str(args.num_steps), + '--learning_rate', + str(args.learning_rate), + '--moe_dispatch', + args.moe_dispatch, + '--duration', + str(args.duration), + ] + + def _benchmark(self): + """Accept only complete worker metrics and verified full-model training.""" + start = time.monotonic() + try: + root = Path(self._args.cache_root).resolve() + root.mkdir(parents=True, exist_ok=True) + job = Path(tempfile.mkdtemp(prefix='v2lite-training-', dir=str(root))) + logger.info('V2-Lite training evidence and isolated cache: %s', job) + run_worker(self._worker_command(job), job / 'worker.log', self._args.duration - 20) + report = read_json(job / 'report.json') + validate_identity(report) + steps = numeric_series(report, 'step_ms', self._args.num_steps) + losses = numeric_series(report, 'loss', self._args.num_steps) + norms = numeric_series(report, 'gradient_norm', self._args.num_steps) + expected_tokens = ( + self._args.num_steps * self._args.batch_size * self._args.num_gpus * (self._args.seq_len - 1) + ) + updates = report.get('updated_parameter_elements') + if report.get('loss_token_count') != expected_tokens or type(updates) is not int or updates <= 0: + raise ValueError('Training token count or verified optimizer update is invalid.') + if report.get('world_size') != self._args.num_gpus: + raise ValueError('Worker used a different number of GPUs.') + rewritten = report.get('moe_layers_rewritten') + expected_layers = 26 if self._args.moe_dispatch == 'stable_sorted' else 0 + if ( + report.get('moe_dispatch') != self._args.moe_dispatch or type(rewritten) is not int + or rewritten != expected_layers + ): + raise ValueError('Worker MoE dispatch does not match the selected profile.') + total = time.monotonic() - start + if total >= self._args.duration: + raise TimeoutError('Complete worker job exceeded the profile duration.') + for name, values in [('step_time', steps), ('loss', losses), ('gradient_norm', norms)]: + metric = 'bf16_train_' + name + self._result.add_raw_data(metric, values, self._args.log_raw_data) + self._result.add_result(metric, statistics.mean(values)) + self._result.add_result('bf16_train_tokens_per_second', expected_tokens * 1000 / sum(steps)) + self._result.add_result('end_to_end_seconds', total) + self._result.add_result('checkpoint_bytes', report['weight_bytes']) + return True + except TimeoutError as error: + logger.error('V2-Lite training timeout: %s', error) + self._result.set_return_code(ReturnCode.KILLED_BY_TIMEOUT) + return False + except (OSError, ValueError, RuntimeError) as error: + logger.error('V2-Lite training failed: %s', error) + self._result.set_return_code(ReturnCode.RUNTIME_EXCEPTION_ERROR) + return False + + +BenchmarkRegistry.register_benchmark('deepseek-v2-lite-training', DeepSeekV2LiteTraining, platform=Platform.CUDA) +BenchmarkRegistry.register_benchmark('deepseek-v2-lite-training', DeepSeekV2LiteTraining, platform=Platform.ROCM) diff --git a/superbench/config/deepseek-v2-lite-training.yaml b/superbench/config/deepseek-v2-lite-training.yaml new file mode 100644 index 000000000..d27697cb4 --- /dev/null +++ b/superbench/config/deepseek-v2-lite-training.yaml @@ -0,0 +1,25 @@ +version: v0.12 +superbench: + enable: [deepseek-v2-lite-training] + monitor: + enable: true + sample_duration: 1 + sample_interval: 1 + benchmarks: + deepseek-v2-lite-training: + enable: true + modes: + - name: local + proc_num: 1 + parallel: false + timeout: 3600 + parameters: + runtime_python: /opt/deepseek-reference/bin/python + cache_root: /data/deepseek-v2-lite + num_gpus: 4 + batch_size: 2 + seq_len: 512 + moe_dispatch: official + num_warmup: 2 + num_steps: 8 + duration: 3300 diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_moe.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_moe.py new file mode 100644 index 000000000..145e9ea2e --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_moe.py @@ -0,0 +1,144 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""CPU mathematical and gradient controls for stable expert dispatch.""" + +import importlib.util +import sys +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +if sys.version_info < (3, 10): + pytest.skip('The standalone V2-Lite training runtime requires Python 3.10 or later.', allow_module_level=True) +torch = pytest.importorskip('torch') +SPEC = importlib.util.spec_from_file_location( + 'sorted_dispatch', + Path(__file__).resolve().parents[3] / 'superbench/benchmarks/model_benchmarks/deepseek_v2_lite_moe.py' +) +if SPEC is None or SPEC.loader is None: + raise RuntimeError('Cannot load the stable dispatch implementation.') +dispatch = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(dispatch) + + +class Auxiliary(torch.autograd.Function): + """Match the official auxiliary-loss autograd contract.""" + @staticmethod + def forward(ctx, output, loss): + """Return routed activations without changing the forward loss.""" + return output + + @staticmethod + def backward(ctx, gradient): + """Preserve activation gradients and differentiate the auxiliary loss.""" + return gradient, gradient.new_ones(()) + + +AddAuxiliaryLoss = Auxiliary + + +class Gate(torch.nn.Module): + """Provide deterministic routing with an optionally unused expert.""" + def __init__(self, experts, hidden, empty_expert): + """Create trainable router weights for the control.""" + super().__init__() + self.weight = torch.nn.Parameter(torch.randn(experts, hidden)) + self.empty_expert = empty_expert + + def forward(self, values): + """Return top-two routes and a differentiable auxiliary loss.""" + scores = torch.nn.functional.linear(values.reshape(-1, values.shape[-1]), self.weight).softmax(-1) + routed = scores[:, :-1] if self.empty_expert else scores + indices = routed.topk(2, dim=-1).indices + return indices, scores.gather(1, indices), scores.square().mean() + + +class MoE(torch.nn.Module): + """Implement the original Boolean-indexed reference dispatch.""" + def __init__(self, empty_expert, shared): + """Create expert, router and optional shared-expert parameters.""" + super().__init__() + self.num_experts_per_tok = 2 + self.config = SimpleNamespace(n_shared_experts=1 if shared else None) + self.experts = torch.nn.ModuleList( + [torch.nn.Sequential(torch.nn.Linear(4, 6), torch.nn.SiLU(), torch.nn.Linear(6, 4)) for _ in range(4)] + ) + self.gate = Gate(4, 4, empty_expert) + if shared: + self.shared_experts = torch.nn.Linear(4, 4) + + def forward(self, hidden): + """Evaluate every expert in the original route order.""" + shape = hidden.shape + ids, weights, auxiliary = self.gate(hidden) + values = hidden.reshape(-1, shape[-1]).repeat_interleave(2, dim=0) + result = torch.empty_like(values) + for index, expert in enumerate(self.experts): + selected = ids.reshape(-1) == index + result[selected] = expert(values[selected]) + result = (result.view(*weights.shape, -1) * weights.unsqueeze(-1)).sum(1).view(shape) + result = Auxiliary.apply(result, auxiliary) + return result + self.shared_experts(hidden) if self.config.n_shared_experts else result + + +class DeepseekV2MoE(MoE): + """Use the pinned official class contract for installation controls.""" + + ep_size = 1 + + +@pytest.mark.parametrize('empty_expert', [False, True]) +@pytest.mark.parametrize('shared', [False, True]) +def test_sorted_dispatch_preserves_outputs_inputs_parameters_and_auxiliary_gradients(empty_expert, shared): + """Retain outputs and all gradients, including empty and shared experts.""" + torch.manual_seed(1234) + model = MoE(empty_expert, shared).double() + values = torch.randn(2, 3, 4, dtype=torch.float64, requires_grad=True) + original = model(values) + original.square().mean().backward() + expected_input = values.grad.clone() + expected_parameters = {name: parameter.grad.clone() for name, parameter in model.named_parameters()} + expected_output = original.detach().clone() + model.zero_grad(set_to_none=True) + values.grad = None + actual = dispatch.sorted_training_forward(model, values, Auxiliary.apply) + actual.square().mean().backward() + torch.testing.assert_close(actual, expected_output, rtol=1e-12, atol=1e-12) + torch.testing.assert_close(values.grad, expected_input, rtol=1e-12, atol=1e-12) + for name, parameter in model.named_parameters(): + assert parameter.grad is not None + torch.testing.assert_close(parameter.grad, expected_parameters[name], rtol=1e-12, atol=1e-12) + if empty_expert: + assert torch.count_nonzero(model.experts[-1][0].weight.grad).item() == 0 + + +def test_installation_preserves_parameters_and_the_evaluation_path(monkeypatch): + """Only training dispatch changes; evaluation retains the original forward.""" + model = torch.nn.ModuleList([DeepseekV2MoE(False, True).double() for _ in range(26)]) + parameters = [id(parameter) for parameter in model.parameters()] + values = torch.randn(1, 2, 4, dtype=torch.float64) + model.eval() + expected = model[0](values).detach() + assert dispatch.install_sorted_dispatch(model) == 26 + assert [id(parameter) for parameter in model.parameters()] == parameters + replacement = Mock(side_effect=RuntimeError('training dispatch reached')) + monkeypatch.setattr(dispatch, 'sorted_training_forward', replacement) + torch.testing.assert_close(model[0](values), expected) + replacement.assert_not_called() + model.train() + with pytest.raises(RuntimeError, match='training dispatch reached'): + model[0](values) + + +@pytest.mark.parametrize('count,expert_parallelism', [(25, 1), (27, 1), (26, 2)]) +def test_unsupported_layout_is_rejected_before_any_forward_changes(count, expert_parallelism): + """A partial model or expert-parallel layout cannot receive a partial patch.""" + model = torch.nn.ModuleList([DeepseekV2MoE(False, False) for _ in range(count)]) + model[0].ep_size = expert_parallelism + original = [module.forward for module in model] + with pytest.raises(ValueError): + dispatch.install_sorted_dispatch(model) + assert [module.forward for module in model] == original diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_reference.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_reference.py new file mode 100644 index 000000000..50a88fc02 --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_reference.py @@ -0,0 +1,377 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""CPU control-flow checks, not certification of full-model reference numerics.""" + +import importlib.util +import json +import sys +import weakref +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +torch = pytest.importorskip('torch') + + +@pytest.fixture +def reference(monkeypatch): + """Load the standalone oracle and redirect only test tensor creation to CPU.""" + directory = Path(__file__).resolve().parents[3] / 'superbench/benchmarks/model_benchmarks' + monkeypatch.syspath_prepend(str(directory)) + spec = importlib.util.spec_from_file_location('v2lite_reference_test', directory / 'deepseek_v2_lite_reference.py') + if spec is None or spec.loader is None: + raise RuntimeError('Cannot load the standalone reference.') + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + tensor = torch.tensor + + def cpu_tensor(data, *args, **kwargs): + if kwargs.get('device') == 'cuda': + kwargs['device'] = 'cpu' + return tensor(data, *args, **kwargs) + + monkeypatch.setattr(torch, 'tensor', cpu_tensor) + return module + + +class ReferenceFixture: + """Expose token-independent logits while checking cached attention shapes.""" + def __init__(self): + """Track cache and full-prefix calls separately.""" + self.calls = [] + + def eval(self): + """Retain the minimal evaluation interface used by the oracle.""" + return self + + def __call__(self, input_ids, attention_mask, past_key_values=None, use_cache=True): + """Require a mask for all past and current positions, including one-token decode.""" + length = input_ids.shape[1] + total = length + (past_key_values or 0) + assert attention_mask.shape == (1, total) + assert attention_mask.all().item() + self.calls.append((length, total, past_key_values, use_cache)) + logits = torch.tensor([0.0, 1.0, 2.0, 3.0]).reshape(1, 1, 4).repeat(1, length, 1) + return SimpleNamespace(logits=logits, past_key_values=total if use_cache else None) + + +def request_fixture(): + """Provide exact fixture probabilities rather than a model-quality claim.""" + probabilities = torch.tensor([0.0, 1.0, 2.0, 3.0]).log_softmax(-1).tolist() + return { + 'prompt_token_ids': [1, 2], + 'token_ids': [3, 3], + 'logprobs': [{str(index): value + for index, value in enumerate(probabilities)} for _ in range(2)], + } + + +def test_cached_decode_mask_covers_full_prefix(reference): + """The second cache call has one input token but a three-position mask.""" + model = ReferenceFixture() + result = reference.inference_reference(model, [request_fixture()]) + assert model.calls == [(2, 2, None, True), (2, 2, None, False), (1, 3, 2, True), (3, 3, None, False)] + assert len(result['comparisons']) == 2 + assert all(row['cache_max_abs_error'] == 0 for row in result['comparisons']) + + +@pytest.mark.parametrize('requests', [[], [{'prompt_token_ids': [], 'token_ids': [], 'logprobs': []}]]) +def test_incomplete_reference_requests_fail(reference, requests): + """Never accept an empty or truncated numerical workload.""" + with pytest.raises(ValueError, match='nonempty|Incomplete'): + reference.inference_reference(ReferenceFixture(), requests) + + +def test_reference_requires_greedy_token_agreement(reference): + """Finite probabilities alone must not certify an incorrect generated token.""" + request = request_fixture() + request['token_ids'][0] = 1 + with pytest.raises(RuntimeError, match='greedy token'): + reference.inference_reference(ReferenceFixture(), [request]) + + +def test_reference_does_not_ignore_probability_mismatch(reference): + """Keep the numerical gate even when all generated tokens are correct.""" + request = request_fixture() + request['logprobs'][0]['3'] += 1.0 + with pytest.raises(AssertionError, match='request 0 step 0'): + reference.inference_reference(ReferenceFixture(), [request]) + + +def test_long_decode_checks_every_engine_token_with_bounded_full_prefix_calls(reference): + """Only full-prefix recomputation is sampled, never engine probability validation.""" + request = request_fixture() + request['token_ids'] *= 4 + request['logprobs'] *= 4 + request['full_prefix_steps'] = [0, 1, 4, 7] + model = ReferenceFixture() + result = reference.inference_reference(model, [request]) + assert len(result['comparisons']) == 8 + assert len(model.calls) == 12 + assert [row['step'] for row in result['comparisons'] if row['full_prefix_checked']] == [0, 1, 4, 7] + assert all(row['cache_max_abs_error'] is None for row in result['comparisons'] if not row['full_prefix_checked']) + request['logprobs'][2] = dict(request['logprobs'][2], **{'3': 0.0}) + with pytest.raises(AssertionError, match='request 0 step 2'): + reference.inference_reference(ReferenceFixture(), [request]) + + +@pytest.mark.parametrize('positions', [[], [0], [1], [0, 0, 1], [1, 0], [0, 2], [False, 1]]) +def test_invalid_full_prefix_sampling_fails(reference, positions): + """Do not accept malformed or first/final-step-incomplete numerical evidence.""" + request = request_fixture() + request['full_prefix_steps'] = positions + with pytest.raises(ValueError, match='reference positions'): + reference.inference_reference(ReferenceFixture(), [request]) + + +class TrainingReferenceFixture: + """Small autograd fixture for global-batch partitioning, not GPU model validation.""" + def __init__(self): + """Create the named parameters required by reference sampling.""" + names = [ + 'model.embed_tokens.weight', + 'model.layers.0.self_attn.q_proj.weight', + 'model.layers.0.self_attn.kv_a_proj_with_mqa.weight', + 'model.layers.0.mlp.down_proj.weight', + 'model.layers.1.mlp.gate.weight', + 'model.layers.1.mlp.experts.0.down_proj.weight', + ] + self.parameters = {name: torch.nn.Parameter(torch.ones(2, 2)) for name in names} + self.batches = [] + self.checkpointing = False + + def train(self): + """Expose the reference model's training-mode interface.""" + return self + + def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs): + """Require the memory-bounded nonreentrant reference policy.""" + assert gradient_checkpointing_kwargs == {'use_reentrant': False} + self.checkpointing = True + + def named_parameters(self): + """Expose stable names for independently selected gradient probes.""" + return self.parameters.items() + + def get_parameter(self, name): + """Look up the same parameter on each logical rank batch.""" + return self.parameters[name] + + def zero_grad(self, set_to_none): + """Discard local gradients before the next reference batch.""" + assert set_to_none + for parameter in self.parameters.values(): + parameter.grad = None + + def __call__(self, input_ids, labels, use_cache): + """Produce input-dependent gradients that differ between rank batches.""" + assert not use_cache and torch.equal(input_ids, labels) + self.batches.append(input_ids.clone()) + loss = sum(parameter.sum() for parameter in self.parameters.values()) * input_ids.float().mean() + return SimpleNamespace(loss=loss) + + +def test_training_reference_averages_distinct_real_profile_rank_batches(reference, monkeypatch): + """Check different rank inputs and float32 gradient averaging rather than replicated tokens.""" + monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: ([[1, 2, 4, 8]], 16)) + model = TrainingReferenceFixture() + result = reference.training_reference(model, 'unused', batch_size=2, seq_len=32, world_size=3) + expected = torch.tensor(result['tokens']).float().mean().item() + assert model.checkpointing + assert len(result['tokens']) == 6 and all(len(row) == 32 for row in result['tokens']) + assert len(model.batches) == 3 and not torch.equal(model.batches[0], model.batches[1]) + assert result['world_size'] == 3 and result['batch_size'] == 2 and result['seq_len'] == 32 + assert result['loss'] == pytest.approx(sum(result['loss_per_rank']) / 3) + for probe in result['gradients'].values(): + assert probe['values'] == pytest.approx([expected] * len(probe['indices'])) + assert all(parameter.grad is None for parameter in model.parameters.values()) + + +def test_reference_preserves_exact_rank_microbatch_shape(reference, monkeypatch): + """Do not introduce BF16 batch-regrouping differences while checking distributed gradients.""" + monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: ([[1, 2, 4, 8]], 16)) + model = TrainingReferenceFixture() + result = reference.training_reference(model, 'unused', batch_size=3, seq_len=32, world_size=2) + assert [batch.shape[0] for batch in model.batches] == [3, 3] + assert all(batch.shape[1] == 32 for batch in model.batches) + assert torch.equal(torch.cat(model.batches), torch.tensor(result['tokens'])) + expected = torch.tensor(result['tokens']).float().mean().item() + assert result['reference_microbatch_size'] == 3 + assert result['loss'] == pytest.approx(expected * 24) + for probe in result['gradients'].values(): + assert probe['values'] == pytest.approx([expected] * len(probe['indices'])) + + +def test_targeted_reference_matches_full_backward_without_unneeded_gradients(reference, monkeypatch): + """Preserve full-model derivatives while avoiding storage for unsampled parameter gradients.""" + documents = [[1, 2, 4, 8]] + monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: (documents, 16)) + model = TrainingReferenceFixture() + ignored = torch.nn.Parameter(torch.tensor([2.0])) + model.parameters['model.layers.2.unprobed.weight'] = ignored + tokens = reference.packed_tokens(documents, 16, 32, 6) + expected = {} + for rank in range(2): + model.zero_grad(set_to_none=True) + inputs = torch.tensor(tokens[rank * 3:(rank + 1) * 3]) + model(input_ids=inputs, labels=inputs, use_cache=False).loss.backward() + for name, parameter in model.parameters.items(): + expected[name] = expected.get(name, torch.zeros_like(parameter)) + parameter.grad.detach() / 2 + model.zero_grad(set_to_none=True) + grad = Mock(wraps=torch.autograd.grad) + monkeypatch.setattr(torch.autograd, 'grad', grad) + result = reference.training_reference(model, 'unused', batch_size=3, seq_len=32, world_size=2) + assert grad.call_count == 2 + for call in grad.call_args_list: + assert all(parameter is not ignored for parameter in call[0][1]) + for name, probe in result['gradients'].items(): + assert probe['values'] == pytest.approx(expected[name].flatten()[probe['indices']].tolist()) + assert all(parameter.requires_grad and parameter.grad is None for parameter in model.parameters.values()) + + +def test_reference_does_not_retain_unused_model_outputs(reference, monkeypatch): + """Release returned vocabulary tensors before accumulating full-model gradients.""" + monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: ([[1, 2, 4, 8]], 16)) + + class OutputFixture(TrainingReferenceFixture): + def __call__(self, input_ids, labels, use_cache): + output = super().__call__(input_ids, labels, use_cache) + logits = torch.ones(8, 8) + self.logits_reference = weakref.ref(logits) + return SimpleNamespace(loss=output.loss, logits=logits) + + model = OutputFixture() + + def check_released(gradient): + assert model.logits_reference() is None + return gradient + + next(iter(model.parameters.values())).register_hook(check_released) + reference.training_reference(model, 'unused', batch_size=2, seq_len=32, world_size=2) + + +@pytest.mark.parametrize('batch_size,seq_len,world_size', [(0, 32, 1), (1, 16, 1), (1, 32, 0)]) +def test_training_reference_rejects_invalid_profile(reference, batch_size, seq_len, world_size): + """Invalid global-batch definitions must fail before any model work.""" + with pytest.raises(ValueError, match='reference profile'): + reference.training_reference(TrainingReferenceFixture(), 'unused', batch_size, seq_len, world_size) + + +@pytest.fixture +def loading_contract(reference, tmp_path, monkeypatch): + """Mock library boundaries while exercising all loader identity checks.""" + if sys.version_info < (3, 10): + pytest.skip('The standalone model runtime requires Python 3.10 or later.') + import importlib.metadata + from deepseek_v2_lite_utils import EXPECTED_CONFIG + + (tmp_path / 'config.json').write_text(json.dumps(dict(EXPECTED_CONFIG, model_type='deepseek_v2'))) + parameter = SimpleNamespace(numel=lambda: reference.PARAMETER_COUNT, requires_grad=True) + model = SimpleNamespace(parameters=lambda: [parameter]) + loading = {key: [] for key in ['missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs']} + loader = Mock(return_value=(model, loading)) + tokenizer = SimpleNamespace(encode=Mock(return_value=[1, 2]), eos_token_id=9) + tokenizer_loader = Mock(return_value=tokenizer) + monkeypatch.setitem( + sys.modules, 'transformers', + SimpleNamespace( + AutoModelForCausalLM=SimpleNamespace(from_pretrained=loader), + AutoTokenizer=SimpleNamespace(from_pretrained=tokenizer_loader), + ) + ) + version = importlib.metadata.version + monkeypatch.setattr( + importlib.metadata, 'version', lambda name: '4.46.3' if name == 'transformers' else version(name) + ) + monkeypatch.setattr(torch.cuda, 'is_available', lambda: True) + return SimpleNamespace( + path=tmp_path, + model=model, + parameter=parameter, + loading=loading, + loader=loader, + tokenizer=tokenizer, + tokenizer_loader=tokenizer_loader, + ) + + +def test_official_loader_contract(reference, loading_contract): + """Require local official-code loading and complete loading diagnostics.""" + item = loading_contract + assert reference.load_model(str(item.path), torch.bfloat16) is item.model + options = item.loader.call_args[1] + assert options['torch_dtype'] == torch.bfloat16 + assert options['local_files_only'] and options['trust_remote_code'] and options['use_safetensors'] + assert options['attn_implementation'] == 'eager' and options['output_loading_info'] + documents, eos = reference.fixed_documents(str(item.path)) + assert len(documents) == len(reference.FIXED_TEXTS) and eos == 9 + assert item.tokenizer_loader.call_args[1]['local_files_only'] + assert item.tokenizer.encode.call_count == len(reference.FIXED_TEXTS) + + +@pytest.mark.parametrize('field', ['missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs']) +def test_loader_diagnostics_cannot_be_ignored(reference, loading_contract, field): + """Partial or incompatible loading must fail before reference execution.""" + loading_contract.loading[field] = ['invalid checkpoint'] + with pytest.raises(RuntimeError, match='checkpoint loading'): + reference.load_model(str(loading_contract.path), torch.bfloat16) + + +@pytest.mark.parametrize('failure', ['count', 'frozen', 'gpu', 'version']) +def test_loader_rejects_wrong_model_or_runtime(reference, loading_contract, monkeypatch, failure): + """Do not replace full-model GPU verification with a smaller or unsupported runtime.""" + item = loading_contract + if failure == 'count': + item.parameter.numel = lambda: 1 + elif failure == 'frozen': + item.parameter.requires_grad = False + elif failure == 'gpu': + monkeypatch.setattr(torch.cuda, 'is_available', lambda: False) + else: + import importlib.metadata + monkeypatch.setattr(importlib.metadata, 'version', lambda name: '0.0') + with pytest.raises(RuntimeError): + reference.load_model(str(item.path), torch.bfloat16) + + +@pytest.mark.parametrize('mode', ['training', 'inference']) +def test_reference_entrypoint_uses_expected_dtype_and_teardown(reference, tmp_path, monkeypatch, mode): + """Exercise orchestration with fake model work, not GPU numerical acceptance.""" + model = Mock() + model.cuda.return_value = model + loader = Mock(return_value=model) + monkeypatch.setattr(reference, 'load_model', loader) + monkeypatch.setattr(reference, 'training_reference', Mock(return_value={'loss': 1.0})) + monkeypatch.setattr(reference, 'inference_reference', Mock(return_value={'comparisons': []})) + monkeypatch.setattr(torch.cuda, 'set_device', Mock()) + monkeypatch.setattr(torch.cuda, 'synchronize', Mock()) + cleanup = Mock() + monkeypatch.setattr(torch.cuda, 'empty_cache', cleanup) + monkeypatch.setattr(torch.backends.cuda.matmul, 'allow_tf32', False) + monkeypatch.setenv('TORCH_ALLOW_TF32_CUBLAS_OVERRIDE', '0') + requests = tmp_path / 'requests.json' + requests.write_text('[]') + output = tmp_path / 'report.json' + monkeypatch.setattr( + sys, 'argv', [ + 'reference', + '--checkpoint', + str(tmp_path), + '--mode', + mode, + '--requests', + str(requests), + '--output', + str(output), + ] + ) + reference.main() + report = json.loads(output.read_text()) + expected = torch.bfloat16 if mode == 'training' else torch.float32 + assert loader.call_args[0][1] == expected + assert report['reference_dtype'] == str(expected) + assert report['correctness_passed'] and report['teardown_complete'] and not report['tf32_allowed'] + cleanup.assert_called_once() diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_training_worker.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_training_worker.py new file mode 100644 index 000000000..711acf9a4 --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_training_worker.py @@ -0,0 +1,285 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""CPU update-verification checks; full-model capacity needs real GPU calibration.""" + +import importlib.util +import json +import sys +import weakref +from contextlib import nullcontext +from pathlib import Path +from types import SimpleNamespace +from typing import TYPE_CHECKING +from unittest.mock import Mock + +import pytest + +if TYPE_CHECKING: + import torch +else: + torch = pytest.importorskip('torch') + + +@pytest.fixture +def worker(monkeypatch): + """Load the worker and replace only GPU/distributed synchronization in CPU tests.""" + directory = Path(__file__).resolve().parents[3] / 'superbench/benchmarks/model_benchmarks' + monkeypatch.syspath_prepend(str(directory)) + spec = importlib.util.spec_from_file_location( + 'v2lite_training_test', directory / 'deepseek_v2_lite_training_worker.py' + ) + if spec is None or spec.loader is None: + raise RuntimeError('Cannot load the standalone training worker.') + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + monkeypatch.setattr(torch.cuda, 'synchronize', lambda: None) + monkeypatch.setattr(torch.distributed, 'all_reduce', lambda tensor: None) + monkeypatch.setattr(torch.distributed, 'get_world_size', lambda: 1) + tensor = torch.tensor + + def cpu_tensor(data, *args, **kwargs): + if kwargs.get('device') == 'cuda': + kwargs['device'] = 'cpu' + return tensor(data, *args, **kwargs) + + monkeypatch.setattr(torch, 'tensor', cpu_tensor) + return module + + +class UpdateFixture(torch.nn.Module): + """Use a small real autograd/optimizer update, not a full-model proxy result.""" + def __init__(self): + """Initialize a nonzero parameter and loss.""" + super().__init__() + self.weight = torch.nn.Parameter(torch.ones(4)) + + def forward(self, input_ids, labels, use_cache): + """Return a scalar differentiable loss without external model dependencies.""" + return SimpleNamespace(loss=self.weight.sum().square()) + + def clip_grad_norm_(self, maximum): + """Expose the FSDP clipping interface using the CPU parameters.""" + return torch.nn.utils.clip_grad_norm_(self.parameters(), maximum) + + +def test_host_snapshot_still_detects_real_update(worker): + """Host snapshots must be independent copies even for the CPU test model.""" + model = UpdateFixture() + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + elapsed, loss, norm, changed = worker.training_step(model, optimizer, torch.tensor([[1, 2]]), True) + assert elapsed > 0 and loss > 0 and norm > 0 + assert changed == 4 + assert torch.all(model.weight < 1).item() + + +def test_optimizer_noop_is_not_success(worker, monkeypatch): + """Moving validation storage to host must not weaken the actual-update gate.""" + model = UpdateFixture() + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + monkeypatch.setattr(optimizer, 'step', lambda: None) + with pytest.raises(RuntimeError, match='did not update'): + worker.training_step(model, optimizer, torch.tensor([[1, 2]]), True) + + +def test_unused_returned_logits_are_released_before_backward(worker): + """Do not retain the full vocabulary output while building gradients and optimizer state.""" + class LogitFixture(UpdateFixture): + def forward(self, input_ids, labels, use_cache): + logits = self.weight.repeat(input_ids.shape[0], 1) + self.logits_reference = weakref.ref(logits) + target = torch.zeros(input_ids.shape[0], dtype=torch.long) + return SimpleNamespace(loss=torch.nn.functional.cross_entropy(logits, target), logits=logits) + + model = LogitFixture() + + def check_released(gradient): + assert model.logits_reference() is None + return gradient + + model.weight.register_hook(check_released) + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + worker.training_step(model, optimizer, torch.tensor([[1, 2]]), True) + + +@pytest.mark.parametrize('invalid', ['missing_loss', 'nonfinite_loss', 'zero_gradient']) +def test_training_step_rejects_invalid_numerics(worker, monkeypatch, invalid): + """Never publish timing for a missing loss, NaN or zero-gradient workload.""" + model = UpdateFixture() + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + if invalid == 'missing_loss': + monkeypatch.setattr(model, 'forward', lambda **kwargs: SimpleNamespace(loss=None)) + elif invalid == 'nonfinite_loss': + monkeypatch.setattr(model, 'forward', lambda **kwargs: SimpleNamespace(loss=model.weight.sum() * float('nan'))) + else: + monkeypatch.setattr(model, 'clip_grad_norm_', lambda maximum: torch.tensor(0.0)) + with pytest.raises(RuntimeError): + worker.training_step(model, optimizer, torch.tensor([[1, 2]])) + + +@pytest.fixture +def main_driver(worker, tmp_path, monkeypatch): + """Exercise worker orchestration with explicit fake GPU/model boundaries.""" + monkeypatch.setenv('RANK', '0') + monkeypatch.setenv('LOCAL_RANK', '0') + monkeypatch.setenv('WORLD_SIZE', '2') + monkeypatch.setenv('TORCH_ALLOW_TF32_CUBLAS_OVERRIDE', '0') + monkeypatch.setattr(worker.signal, 'signal', Mock()) + monkeypatch.setattr(worker, 'set_cache_environment', Mock()) + monkeypatch.setattr(worker, 'configure_cache', Mock()) + download = Mock(return_value=tmp_path / 'checkpoint') + monkeypatch.setattr(worker, 'download_checkpoint', download) + model = Mock() + model.cuda.return_value = model + loader = Mock(return_value=model) + reference = Mock(return_value={'world_size': 2, 'batch_size': 2, 'seq_len': 64, 'reference_microbatch_size': 2}) + training = Mock(return_value={'world_size': 2, 'step_ms': [1.0, 2.0]}) + monkeypatch.setattr(worker, 'load_model', loader) + monkeypatch.setattr(worker, 'training_reference', reference) + monkeypatch.setattr(worker, 'run_training', training) + monkeypatch.setattr(torch.cuda, 'device_count', lambda: 2) + monkeypatch.setattr(torch.cuda, 'set_device', Mock()) + monkeypatch.setattr(torch.cuda, 'empty_cache', Mock()) + monkeypatch.setattr(torch.cuda, 'get_device_name', lambda index: 'CPU orchestration fixture') + monkeypatch.setattr(torch, 'manual_seed', Mock()) + monkeypatch.setattr(torch.backends.cuda.matmul, 'allow_tf32', False) + initialize = Mock() + control = object() + destroy = Mock() + monkeypatch.setattr(torch.distributed, 'init_process_group', initialize) + monkeypatch.setattr(torch.distributed, 'new_group', Mock(return_value=control)) + monkeypatch.setattr(torch.distributed, 'barrier', Mock()) + monkeypatch.setattr(torch.distributed, 'destroy_process_group', destroy) + output = tmp_path / 'report.json' + argv = [ + 'worker', + '--cache_dir', + str(tmp_path / 'cache'), + '--output', + str(output), + '--num_gpus', + '2', + '--batch_size', + '2', + '--seq_len', + '64', + '--num_steps', + '2', + '--duration', + '60', + ] + monkeypatch.setattr(sys, 'argv', argv) + return SimpleNamespace( + output=output, + argv=argv, + download=download, + loader=loader, + reference=reference, + training=training, + initialize=initialize, + destroy=destroy, + control=control, + ) + + +def test_worker_main_preserves_profile_and_reaps_groups(worker, main_driver): + """A success report follows reference/training completion and both group teardowns.""" + state = main_driver + worker.main() + report = json.loads(state.output.read_text()) + assert report['status'] == 'success' and report['correctness_passed'] and report['teardown_complete'] + assert state.loader.call_args[0][1] == torch.bfloat16 + assert state.reference.call_args[0][2:] == (2, 64, 2) + assert [call[0] for call in state.destroy.call_args_list] == [(state.control, ), ()] + assert state.training.call_args[0][0].seq_len == 64 + assert state.training.call_args[0][0].moe_dispatch == 'official' + assert 0 < report['total_seconds'] < 60 + + +def test_worker_main_forwards_the_explicit_dispatch_selection(worker, main_driver, monkeypatch): + """Select stable dispatch only for measured training, retaining the official reference loader.""" + monkeypatch.setattr(sys, 'argv', main_driver.argv + ['--moe_dispatch', 'stable_sorted']) + worker.main() + assert main_driver.training.call_args[0][0].moe_dispatch == 'stable_sorted' + assert main_driver.loader.call_args[0][1] == torch.bfloat16 + + +def test_nonzero_rank_does_not_download_or_publish(worker, main_driver, monkeypatch): + """Only rank zero owns checkpoint/reference creation and the final report.""" + state = main_driver + monkeypatch.setenv('RANK', '1') + monkeypatch.setenv('LOCAL_RANK', '1') + state.output.with_name('training-reference.json').write_text(json.dumps({'world_size': 2})) + worker.main() + state.download.assert_not_called() + state.loader.assert_not_called() + assert not state.output.exists() + assert state.destroy.call_count == 2 + + +def test_worker_failure_still_destroys_groups(worker, main_driver): + """A failed numerical/training dependency cannot produce success or leak groups.""" + main_driver.training.side_effect = RuntimeError('numerical mismatch') + with pytest.raises(RuntimeError, match='numerical mismatch'): + worker.main() + assert not main_driver.output.exists() + assert main_driver.destroy.call_count == 2 + + +@pytest.mark.parametrize( + 'override', [ + ['--num_gpus', '1'], + ['--batch_size', '0'], + ['--seq_len', '16'], + ['--num_warmup', '-1'], + ['--num_steps', '0'], + ['--duration', '3600'], + ['--learning_rate', 'nan'], + ] +) +def test_worker_rejects_invalid_profile_before_initializing(worker, main_driver, monkeypatch, override): + """Bad profiles must not start collective groups or download weights.""" + monkeypatch.setattr(sys, 'argv', main_driver.argv + override) + with pytest.raises(ValueError): + worker.main() + main_driver.initialize.assert_not_called() + main_driver.download.assert_not_called() + + +@pytest.mark.parametrize('checkpointed', [False, True]) +def test_gradient_probe_mapping_covers_root_and_checkpointed_layers(worker, monkeypatch, checkpointed): + """Exercise actual parameter lookup while replacing only FSDP's collective context.""" + fsdp = pytest.importorskip('torch.distributed.fsdp').FullyShardedDataParallel + from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper + + root = torch.nn.Module() + root.model = torch.nn.Module() + root.model.embed_tokens = torch.nn.Embedding(2, 2) + layer = torch.nn.Linear(2, 2, bias=False) + for parameter in [root.model.embed_tokens.weight, layer.weight]: + parameter.grad = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + module = checkpoint_wrapper(layer) if checkpointed else layer + root.model.layers = [SimpleNamespace(module=module)] + model = SimpleNamespace(module=root) + monkeypatch.setattr(fsdp, 'summon_full_params', lambda *args, **kwargs: nullcontext()) + reference = { + 'gradients': { + 'model.embed_tokens.weight': { + 'shape': [2, 2], + 'indices': [0, 3], + 'values': [1.0, 4.0] + }, + 'model.layers.0.weight': { + 'shape': [2, 2], + 'indices': [0, 3], + 'values': [1.0, 4.0] + }, + } + } + assert worker.compare_gradients(model, reference) == 0 + reference['gradients']['model.layers.0.weight']['values'][0] = 10.0 + with pytest.raises(AssertionError): + worker.compare_gradients(model, reference) + layer.weight.grad = None + with pytest.raises(RuntimeError, match='gradient'): + worker.compare_gradients(model, reference) diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_utils.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_utils.py new file mode 100644 index 000000000..f6ff3756f --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_utils.py @@ -0,0 +1,345 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""CPU-only tests for the standalone worker contract, without framework imports.""" + +import copy +import ctypes +import hashlib +import importlib.util +import math +import os +import signal +import sys +import time +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +WORKER_PATH = Path(__file__).resolve().parents[3] / 'superbench/benchmarks/model_benchmarks/deepseek_v2_lite_utils.py' +SPEC = importlib.util.spec_from_file_location('deepseek_v2_lite_utils_test', WORKER_PATH) +if SPEC is None or SPEC.loader is None: + raise RuntimeError('Cannot load the standalone worker utilities.') +utils = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(utils) + + +def test_checkpoint_identity(): + """Reject architecture proxies and quantization.""" + config = dict(utils.EXPECTED_CONFIG, model_type='deepseek_v2') + utils.validate_config(config) + config['hidden_size'] = 1024 + with pytest.raises(ValueError, match='hidden_size'): + utils.validate_config(config) + config['hidden_size'] = 2048 + config['quantization_config'] = {'quant_method': 'fp8'} + with pytest.raises(ValueError, match='quantized'): + utils.validate_config(config) + assert utils.WEIGHT_BYTES == 31413626576 + + +@pytest.mark.parametrize('field,value', [('seq_aux', False), ('aux_loss_alpha', 0.1), ('attention_dropout', 0.1)]) +def test_fixed_training_semantics_are_part_of_model_identity(field, value): + """Do not silently change the official auxiliary-loss or dropout configuration.""" + config = dict(utils.EXPECTED_CONFIG, model_type='deepseek_v2') + config[field] = value + with pytest.raises(ValueError, match=field): + utils.validate_config(config) + + +def test_packed_text_is_reproducible(): + """Pack actual token inputs with EOS separators, not padding or mock execution.""" + documents = [[1, 2], [3, 4, 5]] + expected = [[1, 2, 9, 3], [4, 5, 9, 1]] + assert utils.packed_tokens(documents, 9, 4, 2) == expected + assert utils.packed_tokens(documents, 9, 4, 2) == expected + assert utils.packed_tokens(documents, 9, 4, 2, offset=1) != expected + + +@pytest.mark.parametrize('documents,length,count', [([], 4, 1), ([[]], 4, 1), ([[True]], 4, 1), ([[1]], 1, 1)]) +def test_invalid_text_inputs(documents, length, count): + """Surface malformed inputs instead of returning an empty batch.""" + with pytest.raises(ValueError): + utils.packed_tokens(documents, 9, length, count) + + +def test_cold_cache_isolated(tmp_path, monkeypatch): + """Reject cache reuse without deleting shared contents.""" + shared = tmp_path / 'shared' + shared.mkdir() + sentinel = shared / 'keep' + sentinel.write_text('unrelated data') + monkeypatch.setenv('HF_HOME', str(shared)) + cache = tmp_path / 'cold' + utils.configure_cache(cache) + assert sentinel.read_text() == 'unrelated data' + assert utils.os.environ['HF_HOME'] == str(cache / 'hf') + assert utils.os.environ['HF_XET_CACHE'] == str(cache / 'xet') + (cache / 'present').touch() + with pytest.raises(ValueError, match='empty'): + utils.configure_cache(cache) + + +@pytest.mark.parametrize('values', [[math.nan], [math.inf], [-1], [0], [True], [], ['1']]) +def test_invalid_metric_series(values): + """Never accept NaNs, sentinels, incomplete samples or success-shaped defaults.""" + with pytest.raises(ValueError): + utils.numeric_series({'step_ms': values}, 'step_ms', 1) + + +def test_report_requires_correctness_and_teardown(): + """Require model identity, not just a successful process exit.""" + report = dict(utils.identity_report(), status='success', correctness_passed=True, teardown_complete=True) + utils.validate_identity(report) + incorrect = copy.deepcopy(report) + incorrect['parameter_count'] = 100 + with pytest.raises(ValueError, match='contract'): + utils.validate_identity(incorrect) + report['correctness_passed'] = False + with pytest.raises(ValueError, match='Correctness'): + utils.validate_identity(report) + + +@pytest.mark.parametrize('length', [1, 512, 209715200, 15706484224]) +def test_large_tensor_probe_indices(length): + """FP32-rounded endpoints must never index beyond a real full-model tensor.""" + indices = utils.uniform_indices(length) + assert len(indices) == 256 + assert indices[0] == 0 and indices[-1] == length - 1 + assert all(0 <= index < length for index in indices) + + +def test_atomic_json_rejects_nonfinite_values(tmp_path): + """A malformed report must not replace a complete report.""" + path = tmp_path / 'report.json' + utils.write_json(path, {'value': 1}) + with pytest.raises(ValueError): + utils.write_json(path, {'value': math.nan}) + assert utils.read_json(path) == {'value': 1} + path.write_text('{"value": NaN}') + with pytest.raises(ValueError, match='Nonfinite'): + utils.read_json(path) + + +def test_worker_failure_is_explicit(tmp_path): + """Reject nonzero exit codes even if the worker writes a result-like message.""" + with pytest.raises(RuntimeError, match='code 7'): + utils.run_worker([sys.executable, '-c', 'print("success"); raise SystemExit(7)'], tmp_path / 'worker.log', 5) + assert 'success' in (tmp_path / 'worker.log').read_text() + + +def test_timeout_reaps_worker(tmp_path): + """A timeout must terminate the created process rather than leave a worker.""" + pid_file = tmp_path / 'pid' + command = [ + sys.executable, + '-c', + 'import os,time; from pathlib import Path; Path({!r}).write_text(str(os.getpid())); time.sleep(60)'.format( + str(pid_file) + ), + ] + with pytest.raises(TimeoutError, match='deadline'): + utils.run_worker(command, tmp_path / 'worker.log', 1) + pid = int(pid_file.read_text()) + with pytest.raises(ProcessLookupError): + utils.os.kill(pid, 0) + + +def test_worker_argv_is_not_a_shell(tmp_path): + """Preserve argument boundaries rather than reinterpret shell metacharacters.""" + output = tmp_path / 'argv' + value = 'a=b; this is one value' + utils.run_worker( + [ + sys.executable, '-c', 'import sys; from pathlib import Path; Path(sys.argv[1]).write_text(sys.argv[2])', + str(output), value + ], tmp_path / 'worker.log', 5 + ) + assert output.read_text() == value + + +def test_success_with_live_child_is_rejected(tmp_path): + """A leader's exit code zero is insufficient when its child remains alive.""" + command = [ + sys.executable, + '-c', + 'import subprocess,sys; subprocess.Popen([sys.executable,"-c","import time; time.sleep(60)"])', + ] + with pytest.raises(RuntimeError, match='descendant processes'): + utils.run_worker(command, tmp_path / 'worker.log', 5) + + +@pytest.mark.parametrize('launcher_exits', [False, True]) +def test_separate_session_child_is_reaped(tmp_path, launcher_exits): + """Own escaped rank sessions even when their launcher exits or ignores termination.""" + pid_file = tmp_path / 'rank.pid' + rank = ( + 'import os,signal,time; from pathlib import Path; ' + 'signal.signal(signal.SIGTERM, signal.SIG_IGN); ' + 'Path({!r}).write_text(str(os.getpid())); time.sleep(60)' + ).format(str(pid_file)) + launcher = ( + 'import signal,subprocess,sys,time; from pathlib import Path; ' + 'signal.signal(signal.SIGTERM, signal.SIG_IGN); ' + 'subprocess.Popen([sys.executable, "-c", {!r}], start_new_session=True); ' + 'ready=Path({!r})\n' + 'while not ready.exists(): time.sleep(0.01)\n' + '{}' + ).format(rank, str(pid_file), 'sys.exit(0)' if launcher_exits else 'time.sleep(60)') + try: + expected = RuntimeError if launcher_exits else TimeoutError + with pytest.raises(expected): + utils.run_worker([sys.executable, '-c', launcher], tmp_path / 'worker.log', 5 if launcher_exits else 1) + pid = int(pid_file.read_text()) + with pytest.raises(ProcessLookupError): + os.kill(pid, 0) + finally: + if pid_file.exists(): + pid = int(pid_file.read_text()) + try: + os.kill(pid, signal.SIGKILL) + except ProcessLookupError: + pass + + +def test_worker_signal_does_not_kill_unrelated_process(tmp_path): + """Timeout cleanup must be scoped to the supervised job, not the controller's children.""" + unrelated = utils.subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)']) + try: + with pytest.raises(TimeoutError): + utils.run_worker([sys.executable, '-c', 'import time; time.sleep(60)'], tmp_path / 'worker.log', 0.2) + assert unrelated.poll() is None + finally: + unrelated.terminate() + unrelated.wait(timeout=5) + + +def test_controller_death_reaps_owned_worker(tmp_path): + """A killed controller must not leave its independently supervised job alive.""" + pid_file = tmp_path / 'worker.pid' + worker = ('import os,time; from pathlib import Path; ' + 'Path({!r}).write_text(str(os.getpid())); time.sleep(60)').format(str(pid_file)) + controller = ( + 'import sys; from pathlib import Path; sys.path.insert(0, {!r}); ' + 'from deepseek_v2_lite_utils import run_worker; ' + 'run_worker([sys.executable, "-c", {!r}], Path({!r}), 60)' + ).format(str(WORKER_PATH.parent), worker, str(tmp_path / 'worker.log')) + process = utils.subprocess.Popen([sys.executable, '-c', controller]) + try: + deadline = time.monotonic() + 5 + while not pid_file.exists() and time.monotonic() < deadline: + time.sleep(0.02) + assert pid_file.exists() + pid = int(pid_file.read_text()) + process.kill() + process.wait(timeout=5) + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + try: + os.kill(pid, 0) + except ProcessLookupError: + break + time.sleep(0.02) + else: + pytest.fail('The worker survived its controller.') + finally: + if process.poll() is None: + process.kill() + process.wait(timeout=5) + if pid_file.exists(): + try: + os.kill(int(pid_file.read_text()), signal.SIGKILL) + except ProcessLookupError: + pass + + +@pytest.fixture +def checkpoint_files(tmp_path, monkeypatch): + """Create small real files to test the checkpoint integrity contract.""" + root = tmp_path / 'checkpoint' + root.mkdir() + contents = b'CPU checkpoint integrity fixture' + shard = root / 'weights.safetensors' + shard.write_bytes(contents) + monkeypatch.setattr(utils, 'WEIGHT_FILES', { + shard.name: (len(contents), hashlib.sha256(contents).hexdigest()), + }) + utils.write_json(root / 'config.json', dict(utils.EXPECTED_CONFIG, model_type='deepseek_v2')) + utils.write_json(root / 'model.safetensors.index.json', {'weight_map': {'fixture.weight': shard.name}}) + return root, shard + + +def test_checkpoint_files_are_verified(checkpoint_files): + """Check file sizes, index membership and SHA256 without claiming model execution.""" + root, _ = checkpoint_files + utils.verify_checkpoint(root) + + +@pytest.mark.parametrize('failure', ['missing', 'size', 'hash', 'index']) +def test_invalid_checkpoint_files_fail(checkpoint_files, failure): + """Corrupted, missing or misindexed shards must never become a valid checkpoint.""" + root, shard = checkpoint_files + if failure == 'missing': + shard.unlink() + elif failure == 'size': + shard.write_bytes(b'short') + elif failure == 'hash': + shard.write_bytes(b'x' * shard.stat().st_size) + else: + utils.write_json(root / 'model.safetensors.index.json', {'weight_map': {'fixture.weight': 'other'}}) + with pytest.raises(ValueError): + utils.verify_checkpoint(root) + + +def test_download_uses_pinned_public_identity_and_then_verifies(checkpoint_files, monkeypatch): + """Disable implicit credentials and require the downloaded shard contract.""" + root, shard = checkpoint_files + download = Mock() + monkeypatch.setitem(sys.modules, 'huggingface_hub', SimpleNamespace(snapshot_download=download)) + assert utils.download_checkpoint(root.parent) == root + arguments = download.call_args[1] + assert arguments['repo_id'] == utils.MODEL_ID + assert arguments['revision'] == utils.REVISION + assert arguments['token'] is False + assert arguments['local_dir'] == str(root) + assert shard.name in arguments['allow_patterns'] + + +@pytest.mark.parametrize('length,count', [(0, 2), (1, 1)]) +def test_invalid_probe_dimensions_fail(length, count): + """Reject undefined probe endpoints instead of silently selecting positions.""" + with pytest.raises(ValueError, match='tensor length'): + utils.uniform_indices(length, count) + + +@pytest.mark.parametrize('timeout', [0, -1, float('nan')]) +def test_invalid_worker_deadline_fails_before_launch(tmp_path, timeout): + """A nonfinite or expired budget must not start a worker.""" + with pytest.raises(TimeoutError): + utils.run_worker([sys.executable, '-c', 'pass'], tmp_path / 'worker.log', timeout) + + +def test_empty_worker_command_fails(tmp_path): + """Do not launch a supervisor with no defined workload.""" + with pytest.raises(ValueError, match='command'): + utils.run_worker([], tmp_path / 'worker.log', 1) + + +def test_worker_interrupt_is_failure(): + """A termination request must unwind the worker's normal success path.""" + with pytest.raises(TimeoutError, match='interrupted'): + utils.interrupt_worker(signal.SIGTERM, None) + + +def test_supervisor_requires_kernel_ownership_support(monkeypatch): + """Fail before spawning when kernel ownership setup is unavailable.""" + monkeypatch.setattr(utils.signal, 'signal', Mock()) + monkeypatch.setattr(ctypes, 'CDLL', lambda *args, **kwargs: SimpleNamespace(prctl=lambda *args: -1)) + monkeypatch.setattr(ctypes, 'get_errno', lambda: 13) + spawn = Mock() + monkeypatch.setattr(utils.subprocess, 'Popen', spawn) + with pytest.raises(OSError): + utils.supervise_worker([sys.executable, '-c', 'pass'], 1, os.getppid()) + spawn.assert_not_called() diff --git a/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py b/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py new file mode 100644 index 000000000..0fd452779 --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py @@ -0,0 +1,146 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""CPU adapter tests; complete model correctness is checked by the GPU worker.""" + +from pathlib import Path + +import pytest + +from superbench.benchmarks import BenchmarkType, ReturnCode +from superbench.benchmarks.model_benchmarks import pytorch_deepseek_v2_lite as adapter +from superbench.benchmarks.model_benchmarks.deepseek_v2_lite_utils import identity_report, write_json + + +@pytest.fixture +def benchmark(tmp_path, monkeypatch): + """Use an isolated cache root and a single local launcher.""" + monkeypatch.delenv('WORLD_SIZE', raising=False) + monkeypatch.delenv('OMPI_COMM_WORLD_SIZE', raising=False) + return adapter.DeepSeekV2LiteTraining( + 'deepseek-v2-lite-training', + '--cache_root "{}" --num_steps 2 --seq_len 64 --duration 60'.format(tmp_path), + ) + + +def successful_worker(command, log, timeout): + """Supply a worker-contract fixture, not a claim of model execution.""" + output = Path(command[command.index('--output') + 1]) + dispatch = command[command.index('--moe_dispatch') + 1] + report = dict( + identity_report(), + status='success', + correctness_passed=True, + teardown_complete=True, + step_ms=[10.0, 20.0], + loss=[2.0, 1.9], + gradient_norm=[1.0, 0.9], + loss_token_count=2 * 8 * 63, + updated_parameter_elements=100, + world_size=4, + moe_dispatch=dispatch, + moe_layers_rewritten=26 if dispatch == 'stable_sorted' else 0, + ) + write_json(output, report) + + +def test_successful_adapter_metrics(benchmark, monkeypatch): + """Preserve the MODEL result shape and count predicted loss tokens correctly.""" + monkeypatch.setattr(adapter, 'run_worker', successful_worker) + assert benchmark.run() + assert benchmark.type == BenchmarkType.MODEL + assert benchmark.return_code == ReturnCode.SUCCESS + assert benchmark.result['bf16_train_step_time'] == [15.0] + assert benchmark.raw_data['bf16_train_step_time'] == [[10.0, 20.0]] + assert benchmark.result['bf16_train_tokens_per_second'] == [2 * 8 * 63 * 1000 / 30] + + +@pytest.mark.parametrize( + 'parameters', [ + '--seq_len 0', '--num_gpus 1', '--batch_size 0', '--num_steps 0', '--num_warmup -1', '--learning_rate nan', + '--duration 3600', '--run_count 2', '--hidden_size 1024', '--moe_dispatch unknown' + ] +) +def test_invalid_profiles(parameters): + """Reject invalid shapes, architecture overrides and combined timing profiles.""" + benchmark = adapter.DeepSeekV2LiteTraining('deepseek-v2-lite-training', parameters) + assert not benchmark.run() + assert benchmark.return_code == ReturnCode.INVALID_ARGUMENT + + +@pytest.mark.parametrize('world_size', ['8', 'not-an-integer']) +def test_duplicate_launcher_is_rejected(benchmark, monkeypatch, world_size): + """An MPI worker group must not launch eight independent full-model jobs.""" + monkeypatch.setenv('WORLD_SIZE', world_size) + assert not benchmark.run() + assert benchmark.return_code == ReturnCode.INVALID_ARGUMENT + + +def test_download_or_worker_failure_is_not_success(benchmark, monkeypatch): + """Reject a failed subprocess rather than inventing throughput.""" + def failed_worker(command, log, timeout): + raise RuntimeError('download failed') + + monkeypatch.setattr(adapter, 'run_worker', failed_worker) + assert not benchmark.run() + assert benchmark.return_code == ReturnCode.RUNTIME_EXCEPTION_ERROR + assert 'bf16_train_step_time' not in benchmark.result + + +def test_timeout_is_failure(benchmark, monkeypatch): + """Finishing through watchdog termination does not meet the time limit.""" + def timed_out_worker(command, log, timeout): + raise TimeoutError('whole job deadline') + + monkeypatch.setattr(adapter, 'run_worker', timed_out_worker) + assert not benchmark.run() + assert benchmark.return_code == ReturnCode.KILLED_BY_TIMEOUT + + +@pytest.mark.parametrize( + 'field,value', [ + ('step_ms', [-1, 20]), ('step_ms', [10]), ('correctness_passed', False), ('teardown_complete', False), + ('updated_parameter_elements', True), ('loss_token_count', 1024), ('moe_dispatch', None), + ('moe_dispatch', 'stable_sorted'), ('moe_layers_rewritten', False), ('moe_layers_rewritten', 26) + ] +) +def test_invalid_worker_report(benchmark, monkeypatch, field, value): + """Check required metric thresholds and shapes, not only process exit zero.""" + def invalid_worker(command, log, timeout): + successful_worker(command, log, timeout) + output = Path(command[command.index('--output') + 1]) + report = adapter.read_json(output) + report[field] = value + write_json(output, report) + + monkeypatch.setattr(adapter, 'run_worker', invalid_worker) + assert not benchmark.run() + assert benchmark.return_code == ReturnCode.RUNTIME_EXCEPTION_ERROR + + +def test_python_and_path_remain_separate_arguments(benchmark): + """Never concatenate runtime paths or forward unchecked model flags.""" + assert benchmark._preprocess() + benchmark._args.runtime_python = '/path with spaces/python' + command = benchmark._worker_command(Path('/cache with spaces/job')) + assert command[0] == '/path with spaces/python' + assert command[command.index('--cache_dir') + 1] == '/cache with spaces/job/cache' + assert '--nproc_per_node=4' in command + assert command[command.index('--moe_dispatch') + 1] == 'official' + + +def test_opt_in_dispatch_reaches_the_worker_and_requires_matching_evidence(benchmark, tmp_path, monkeypatch): + """Thread the explicit dispatch selection through the real adapter contract.""" + selected = adapter.DeepSeekV2LiteTraining( + 'deepseek-v2-lite-training', + '--cache_root "{}" --num_steps 2 --seq_len 64 --duration 60 --moe_dispatch stable_sorted'.format(tmp_path), + ) + commands = [] + + def worker(command, log, timeout): + commands.append(command) + successful_worker(command, log, timeout) + + monkeypatch.setattr(adapter, 'run_worker', worker) + assert selected.run() + assert commands[0][commands[0].index('--moe_dispatch') + 1] == 'stable_sorted' From d3346772997db36f8f60d25c8c4f4468fd797f6c Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Wed, 28 Oct 2026 18:17:50 +0000 Subject: [PATCH 2/9] Benchmarks - Remove the per-run V2-Lite training model cache Delete each run's downloaded checkpoint cache after the worker exits, on success, failure or timeout, while keeping its report and logs. A cleanup error is logged without discarding a validated measurement; a runner timeout during cleanup is still reported as a timeout. Require cache_root instead of defaulting to a relative directory inside the SuperBench output tree. Declare moe_dispatch as a string so `sb benchmark list-parameters` can render it. Document the validated H100 profile parameters, and import torch for type checking in the stable-dispatch test. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../benchmarks/model-benchmarks.md | 16 ++-- .../pytorch_deepseek_v2_lite.py | 34 ++++++++- .../test_deepseek_v2_lite_moe.py | 6 +- .../test_pytorch_deepseek_v2_lite.py | 76 ++++++++++++++++++- 4 files changed, 121 insertions(+), 11 deletions(-) diff --git a/docs/user-tutorial/benchmarks/model-benchmarks.md b/docs/user-tutorial/benchmarks/model-benchmarks.md index def2ed4aa..2614a8327 100644 --- a/docs/user-tutorial/benchmarks/model-benchmarks.md +++ b/docs/user-tutorial/benchmarks/model-benchmarks.md @@ -184,12 +184,13 @@ only in auxiliary unit tests. #### Validation Status -This remains a draft implementation. Local H100 acceptance applies only to the +H100 acceptance applies only to the recorded four-GPU stable-sorted/native-allocator profile, its exact runtime and the corresponding source/configuration identities. It does not qualify the default official-dispatch example, every H100 configuration or other SKUs. -Publication and acceptance into delivery branches are separate from local -hardware validation. +That profile runs on Standard_ND96isrf_H100_v5 with `num_gpus=4`, +`batch_size=36`, `seq_len=512`, `num_warmup=2`, `num_steps=128`, +`moe_dispatch=stable_sorted` and `PYTORCH_CUDA_ALLOC_CONF=backend:native`. #### Runtime And Execution @@ -283,9 +284,12 @@ The one-time pre-update parameter snapshot is stored in host memory and checked after the update. Model parameters, gradients and optimizer state remain on the GPUs; this is validation storage, not training-state CPU offload. -Every invocation creates its own empty HF/Hub/Xet/module cache and keeps its -report and logs under a new directory in `cache_root`. Shared caches are not -deleted. `duration` covers download, SHA256 verification, loading, correctness, +`cache_root` is required. Every invocation creates its own empty +HF/Hub/Xet/module cache and keeps its report and logs under a new directory in +`cache_root`. After the worker exits, the adapter deletes that 31.4GB model +cache and keeps the report and logs; shared caches are not touched. + +`duration` covers download, SHA256 verification, loading, correctness, warmup, measured training and worker/rank teardown. It must be below 3600 seconds; the controller reserves 20 seconds for cleanup. A watchdog exit is a failure. Image pulling, dependency preparation and SuperBench installation are separate diff --git a/superbench/benchmarks/model_benchmarks/pytorch_deepseek_v2_lite.py b/superbench/benchmarks/model_benchmarks/pytorch_deepseek_v2_lite.py index bf290ff60..10d89a92b 100644 --- a/superbench/benchmarks/model_benchmarks/pytorch_deepseek_v2_lite.py +++ b/superbench/benchmarks/model_benchmarks/pytorch_deepseek_v2_lite.py @@ -4,6 +4,7 @@ """SuperBench adapter for isolated official-checkpoint V2-Lite FSDP training.""" import os +import shutil import statistics import sys import tempfile @@ -19,6 +20,22 @@ ) +def _remove_model_cache(cache): + """Delete one run's downloaded model cache after its worker exits, keeping reports and logs.""" + if not cache.exists(): + return + start = time.monotonic() + try: + shutil.rmtree(cache) + except TimeoutError: + # The SuperBench SIGTERM handler raises TimeoutError, an OSError subclass; keep it fatal. + raise + except OSError as error: + logger.error('Failed to remove the V2-Lite model cache %s: %s', cache, error) + return + logger.info('Removed the V2-Lite model cache %s in %.1f seconds.', cache, time.monotonic() - start) + + class DeepSeekV2LiteTraining(Benchmark): """Run one official BF16 checkpoint through a separate FSDP worker runtime.""" def __init__(self, name, parameters=''): @@ -31,20 +48,29 @@ def add_parser_arguments(self): super().add_parser_arguments() self._parser.set_defaults(duration=3300) self._parser.add_argument('--runtime_python', type=str, default=sys.executable) - self._parser.add_argument('--cache_root', type=str, default='model-cache') + self._parser.add_argument( + '--cache_root', + type=str, + default=None, + help='Required directory for per-run reports, logs and the temporary model cache.', + ) self._parser.add_argument('--num_gpus', type=int, default=4) self._parser.add_argument('--batch_size', type=int, default=2, help='Microbatch per GPU.') self._parser.add_argument('--seq_len', type=int, default=512) self._parser.add_argument('--num_warmup', type=int, default=2) self._parser.add_argument('--num_steps', type=int, default=8) self._parser.add_argument('--learning_rate', type=float, default=1e-5) - self._parser.add_argument('--moe_dispatch', choices=MOE_DISPATCHES, default='official') + self._parser.add_argument('--moe_dispatch', type=str, choices=MOE_DISPATCHES, default='official') def _preprocess(self): """Reject unsupported execution modes and invalid shapes explicitly.""" if not super()._preprocess(): return False args = self._args + if not args.cache_root: + logger.error('V2-Lite training requires cache_root for its per-run model cache, reports and logs.') + self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) + return False invalid = ( args.run_count != 1 or not 30 < args.duration < 3600 or args.num_gpus < 2 or args.batch_size < 1 or args.seq_len < 32 or args.num_warmup < 0 or args.num_steps < 1 or not 0 < args.learning_rate < 1 @@ -97,6 +123,7 @@ def _worker_command(self, job): def _benchmark(self): """Accept only complete worker metrics and verified full-model training.""" start = time.monotonic() + job = None try: root = Path(self._args.cache_root).resolve() root.mkdir(parents=True, exist_ok=True) @@ -142,6 +169,9 @@ def _benchmark(self): logger.error('V2-Lite training failed: %s', error) self._result.set_return_code(ReturnCode.RUNTIME_EXCEPTION_ERROR) return False + finally: + if job is not None: + _remove_model_cache(job / 'cache') BenchmarkRegistry.register_benchmark('deepseek-v2-lite-training', DeepSeekV2LiteTraining, platform=Platform.CUDA) diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_moe.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_moe.py index 145e9ea2e..8a94e7506 100644 --- a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_moe.py +++ b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_moe.py @@ -7,13 +7,17 @@ import sys from pathlib import Path from types import SimpleNamespace +from typing import TYPE_CHECKING from unittest.mock import Mock import pytest if sys.version_info < (3, 10): pytest.skip('The standalone V2-Lite training runtime requires Python 3.10 or later.', allow_module_level=True) -torch = pytest.importorskip('torch') +if TYPE_CHECKING: + import torch +else: + torch = pytest.importorskip('torch') SPEC = importlib.util.spec_from_file_location( 'sorted_dispatch', Path(__file__).resolve().parents[3] / 'superbench/benchmarks/model_benchmarks/deepseek_v2_lite_moe.py' diff --git a/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py b/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py index 0fd452779..7195e8aac 100644 --- a/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py +++ b/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py @@ -4,6 +4,7 @@ """CPU adapter tests; complete model correctness is checked by the GPU worker.""" from pathlib import Path +from unittest.mock import Mock import pytest @@ -61,13 +62,31 @@ def test_successful_adapter_metrics(benchmark, monkeypatch): '--duration 3600', '--run_count 2', '--hidden_size 1024', '--moe_dispatch unknown' ] ) -def test_invalid_profiles(parameters): +def test_invalid_profiles(tmp_path, parameters): """Reject invalid shapes, architecture overrides and combined timing profiles.""" - benchmark = adapter.DeepSeekV2LiteTraining('deepseek-v2-lite-training', parameters) + benchmark = adapter.DeepSeekV2LiteTraining( + 'deepseek-v2-lite-training', '--cache_root "{}" {}'.format(tmp_path, parameters) + ) + assert not benchmark.run() + assert benchmark.return_code == ReturnCode.INVALID_ARGUMENT + + +def test_cache_root_is_required(): + """Refuse to choose an implicit location for the per-run model cache.""" + benchmark = adapter.DeepSeekV2LiteTraining('deepseek-v2-lite-training', '--num_steps 2') assert not benchmark.run() assert benchmark.return_code == ReturnCode.INVALID_ARGUMENT +def test_parameters_render_in_help(): + """Keep every option compatible with the typed SuperBench help formatter.""" + benchmark = adapter.DeepSeekV2LiteTraining('deepseek-v2-lite-training') + benchmark.add_parser_arguments() + settings = benchmark.get_configurable_settings() + assert '--moe_dispatch' in settings + assert '--cache_root' in settings + + @pytest.mark.parametrize('world_size', ['8', 'not-an-integer']) def test_duplicate_launcher_is_rejected(benchmark, monkeypatch, world_size): """An MPI worker group must not launch eight independent full-model jobs.""" @@ -97,6 +116,59 @@ def timed_out_worker(command, log, timeout): assert benchmark.return_code == ReturnCode.KILLED_BY_TIMEOUT +@pytest.mark.parametrize('outcome', ['success', 'failure', 'timeout']) +def test_model_cache_is_removed_after_every_run(benchmark, monkeypatch, outcome): + """Delete the per-run checkpoint cache on every exit path while keeping reports and logs.""" + jobs = [] + + def worker(command, log, timeout): + cache = Path(command[command.index('--cache_dir') + 1]) + (cache / 'checkpoint').mkdir(parents=True) + (cache / 'checkpoint' / 'model-00001-of-000004.safetensors').write_bytes(b'weights') + log.write_text('worker log\n') + jobs.append(cache.parent) + if outcome == 'failure': + raise RuntimeError('worker failed') + if outcome == 'timeout': + raise TimeoutError('whole job deadline') + successful_worker(command, log, timeout) + + monkeypatch.setattr(adapter, 'run_worker', worker) + assert benchmark.run() is (outcome == 'success') + assert not (jobs[0] / 'cache').exists() + assert (jobs[0] / 'worker.log').read_text() == 'worker log\n' + assert (jobs[0] / 'report.json').is_file() is (outcome == 'success') + + +def test_cache_removal_failure_keeps_a_valid_measurement(benchmark, monkeypatch): + """Log a cleanup error without discarding metrics that were already validated.""" + caches = [] + + def worker(command, log, timeout): + cache = Path(command[command.index('--cache_dir') + 1]) + cache.mkdir(parents=True) + caches.append(cache) + successful_worker(command, log, timeout) + + monkeypatch.setattr(adapter, 'run_worker', worker) + monkeypatch.setattr(adapter.shutil, 'rmtree', Mock(side_effect=PermissionError('read-only cache'))) + assert benchmark.run() + assert benchmark.return_code == ReturnCode.SUCCESS + assert caches[0].is_dir() + + +def test_sigterm_during_cache_removal_still_reports_timeout(benchmark, monkeypatch): + """A runner timeout during cleanup must not be reported as a completed run.""" + def worker(command, log, timeout): + Path(command[command.index('--cache_dir') + 1]).mkdir(parents=True) + successful_worker(command, log, timeout) + + monkeypatch.setattr(adapter, 'run_worker', worker) + monkeypatch.setattr(adapter.shutil, 'rmtree', Mock(side_effect=TimeoutError('Killed by SIGTERM or timeout!'))) + benchmark.run() + assert benchmark.return_code == ReturnCode.KILLED_BY_TIMEOUT + + @pytest.mark.parametrize( 'field,value', [ ('step_ms', [-1, 20]), ('step_ms', [10]), ('correctness_passed', False), ('teardown_complete', False), From 28ececfcec1ca995f71c7ecc13f29c9996fa8149 Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Thu, 29 Oct 2026 21:42:38 +0000 Subject: [PATCH 3/9] Benchmarks - Bound V2-Lite training cache cleanup Apply the inference benchmark's cache-cleanup contract to training. Model-cache removal now counts toward the download-inclusive deadline and end_to_end_seconds, and the success result is finalized after cleanup. After a failed or timed-out run, cleanup may continue until the job deadline or for 60 seconds, whichever ends later, without replacing the original error. The bounded removal is shared with the inference benchmark. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../benchmarks/model-benchmarks.md | 16 ++- .../deepseek_v2_lite_cache.py | 60 ++++++++++ .../pytorch_deepseek_v2_lite.py | 79 ++++++------- .../test_deepseek_v2_lite_cache.py | 110 +++++++++++++++++ .../test_pytorch_deepseek_v2_lite.py | 111 +++++++++++++++++- 5 files changed, 325 insertions(+), 51 deletions(-) create mode 100644 superbench/benchmarks/model_benchmarks/deepseek_v2_lite_cache.py create mode 100644 tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_cache.py diff --git a/docs/user-tutorial/benchmarks/model-benchmarks.md b/docs/user-tutorial/benchmarks/model-benchmarks.md index 2614a8327..dde10673d 100644 --- a/docs/user-tutorial/benchmarks/model-benchmarks.md +++ b/docs/user-tutorial/benchmarks/model-benchmarks.md @@ -287,11 +287,19 @@ GPUs; this is validation storage, not training-state CPU offload. `cache_root` is required. Every invocation creates its own empty HF/Hub/Xet/module cache and keeps its report and logs under a new directory in `cache_root`. After the worker exits, the adapter deletes that 31.4GB model -cache and keeps the report and logs; shared caches are not touched. +cache and keeps the report and logs; shared caches are not touched. On a +successful run, cleanup must finish within `duration`; otherwise the run fails +as a timeout. After a failed or timed-out run, cleanup may continue until the +job deadline or for 60 seconds, whichever ends later; an unfinished cleanup is +logged without replacing the original error. Other filesystem errors are logged +without discarding validated measurements. Interrupted cleanup can leave a cache +at the logged path. `duration` covers download, SHA256 verification, loading, correctness, -warmup, measured training and worker/rank teardown. It must be below 3600 seconds; -the controller reserves 20 seconds for cleanup. A watchdog exit is a failure. +warmup, measured training, worker/rank teardown and model-cache cleanup. It must +be below 3600 seconds; the worker deadline leaves 20 seconds for teardown and +cleanup, and the controller finalizes the elapsed time and success result after +cleanup. A watchdog exit is a failure. Image pulling, dependency preparation and SuperBench installation are separate runtime-preparation steps, not certified by the model-cold timer. @@ -308,7 +316,7 @@ GPU telemetry; the step durations continue to use the monotonic clock. | `bf16_train_tokens_per_second` | loss tokens/s | Global next-token targets, excluding each sequence's first position | | `bf16_train_loss` | loss | Global mean causal-LM loss | | `bf16_train_gradient_norm` | norm | Global gradient norm before clipping | -| `end_to_end_seconds` | s | Complete worker launch through exit and report validation | +| `end_to_end_seconds` | s | Complete invocation through report validation and model-cache cleanup | | `checkpoint_bytes` | bytes | Complete weight files, not measured network traffic or GPU memory | Step timing includes forward, backward, clipping and the optimizer update. diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_cache.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_cache.py new file mode 100644 index 000000000..a240a7787 --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_cache.py @@ -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) diff --git a/superbench/benchmarks/model_benchmarks/pytorch_deepseek_v2_lite.py b/superbench/benchmarks/model_benchmarks/pytorch_deepseek_v2_lite.py index 10d89a92b..291788870 100644 --- a/superbench/benchmarks/model_benchmarks/pytorch_deepseek_v2_lite.py +++ b/superbench/benchmarks/model_benchmarks/pytorch_deepseek_v2_lite.py @@ -4,7 +4,6 @@ """SuperBench adapter for isolated official-checkpoint V2-Lite FSDP training.""" import os -import shutil import statistics import sys import tempfile @@ -14,28 +13,15 @@ from superbench.benchmarks import BenchmarkRegistry, BenchmarkType, Platform, ReturnCode from superbench.benchmarks.base import Benchmark from superbench.common.utils import logger +from superbench.benchmarks.model_benchmarks.deepseek_v2_lite_cache import ( + remove_model_cache, remove_model_cache_after_failure +) from superbench.benchmarks.model_benchmarks.deepseek_v2_lite_moe import MOE_DISPATCHES from superbench.benchmarks.model_benchmarks.deepseek_v2_lite_utils import ( numeric_series, read_json, run_worker, validate_identity ) -def _remove_model_cache(cache): - """Delete one run's downloaded model cache after its worker exits, keeping reports and logs.""" - if not cache.exists(): - return - start = time.monotonic() - try: - shutil.rmtree(cache) - except TimeoutError: - # The SuperBench SIGTERM handler raises TimeoutError, an OSError subclass; keep it fatal. - raise - except OSError as error: - logger.error('Failed to remove the V2-Lite model cache %s: %s', cache, error) - return - logger.info('Removed the V2-Lite model cache %s in %.1f seconds.', cache, time.monotonic() - start) - - class DeepSeekV2LiteTraining(Benchmark): """Run one official BF16 checkpoint through a separate FSDP worker runtime.""" def __init__(self, name, parameters=''): @@ -120,36 +106,46 @@ def _worker_command(self, job): str(args.duration), ] + def _validate_training_report(self, report): + """Check token accounting, the verified update, GPU count and MoE dispatch evidence.""" + expected_tokens = ( + self._args.num_steps * self._args.batch_size * self._args.num_gpus * (self._args.seq_len - 1) + ) + updates = report.get('updated_parameter_elements') + if report.get('loss_token_count') != expected_tokens or type(updates) is not int or updates <= 0: + raise ValueError('Training token count or verified optimizer update is invalid.') + if report.get('world_size') != self._args.num_gpus: + raise ValueError('Worker used a different number of GPUs.') + rewritten = report.get('moe_layers_rewritten') + expected_layers = 26 if self._args.moe_dispatch == 'stable_sorted' else 0 + if ( + report.get('moe_dispatch') != self._args.moe_dispatch or type(rewritten) is not int + or rewritten != expected_layers + ): + raise ValueError('Worker MoE dispatch does not match the selected profile.') + return expected_tokens + def _benchmark(self): """Accept only complete worker metrics and verified full-model training.""" start = time.monotonic() - job = None + deadline = start + self._args.duration try: root = Path(self._args.cache_root).resolve() root.mkdir(parents=True, exist_ok=True) job = Path(tempfile.mkdtemp(prefix='v2lite-training-', dir=str(root))) - logger.info('V2-Lite training evidence and isolated cache: %s', job) - run_worker(self._worker_command(job), job / 'worker.log', self._args.duration - 20) - report = read_json(job / 'report.json') - validate_identity(report) - steps = numeric_series(report, 'step_ms', self._args.num_steps) - losses = numeric_series(report, 'loss', self._args.num_steps) - norms = numeric_series(report, 'gradient_norm', self._args.num_steps) - expected_tokens = ( - self._args.num_steps * self._args.batch_size * self._args.num_gpus * (self._args.seq_len - 1) - ) - updates = report.get('updated_parameter_elements') - if report.get('loss_token_count') != expected_tokens or type(updates) is not int or updates <= 0: - raise ValueError('Training token count or verified optimizer update is invalid.') - if report.get('world_size') != self._args.num_gpus: - raise ValueError('Worker used a different number of GPUs.') - rewritten = report.get('moe_layers_rewritten') - expected_layers = 26 if self._args.moe_dispatch == 'stable_sorted' else 0 - if ( - report.get('moe_dispatch') != self._args.moe_dispatch or type(rewritten) is not int - or rewritten != expected_layers - ): - raise ValueError('Worker MoE dispatch does not match the selected profile.') + try: + logger.info('V2-Lite training evidence and isolated cache: %s', job) + run_worker(self._worker_command(job), job / 'worker.log', deadline - time.monotonic() - 20) + report = read_json(job / 'report.json') + validate_identity(report) + steps = numeric_series(report, 'step_ms', self._args.num_steps) + losses = numeric_series(report, 'loss', self._args.num_steps) + norms = numeric_series(report, 'gradient_norm', self._args.num_steps) + expected_tokens = self._validate_training_report(report) + remove_model_cache(job / 'cache', deadline) + except BaseException: + remove_model_cache_after_failure(job / 'cache', deadline) + raise total = time.monotonic() - start if total >= self._args.duration: raise TimeoutError('Complete worker job exceeded the profile duration.') @@ -169,9 +165,6 @@ def _benchmark(self): logger.error('V2-Lite training failed: %s', error) self._result.set_return_code(ReturnCode.RUNTIME_EXCEPTION_ERROR) return False - finally: - if job is not None: - _remove_model_cache(job / 'cache') BenchmarkRegistry.register_benchmark('deepseek-v2-lite-training', DeepSeekV2LiteTraining, platform=Platform.CUDA) diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_cache.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_cache.py new file mode 100644 index 000000000..46a2a0b8b --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_cache.py @@ -0,0 +1,110 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""CPU tests for bounded removal of one V2-Lite run's model cache.""" + +import subprocess +import sys +import time +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +from superbench.benchmarks.model_benchmarks import deepseek_v2_lite_cache as cleanup + + +def test_removes_only_the_run_cache(tmp_path): + """Delete the downloaded checkpoint while keeping the run's report and logs.""" + cache = tmp_path / 'cache' + (cache / 'checkpoint').mkdir(parents=True) + (cache / 'checkpoint' / 'model-00001-of-000004.safetensors').write_bytes(b'weights') + (tmp_path / 'report.json').write_text('{}') + cleanup.remove_model_cache(cache, time.monotonic() + 30) + assert not cache.exists() + assert (tmp_path / 'report.json').is_file() + + +def test_missing_cache_is_not_an_error(tmp_path): + """A run that failed before downloading has no cache to remove.""" + cleanup.remove_model_cache(tmp_path / 'cache', time.monotonic() + 30) + assert not (tmp_path / 'cache').exists() + + +def test_cleanup_does_not_start_without_budget(tmp_path, monkeypatch): + """Never start an unbounded deletion after the deadline.""" + run = Mock() + monkeypatch.setattr(cleanup.subprocess, 'run', run) + with pytest.raises(TimeoutError, match='No time remains'): + cleanup.remove_model_cache(tmp_path / 'cache', time.monotonic()) + run.assert_not_called() + + +@pytest.mark.parametrize( + 'failure', + [PermissionError('read-only cache'), + subprocess.CalledProcessError(1, ['cleanup'], output='read-only cache')] +) +def test_filesystem_errors_are_logged(tmp_path, monkeypatch, failure): + """Report a cleanup error without treating it as a failed measurement.""" + log_error = Mock() + monkeypatch.setattr(cleanup.subprocess, 'run', Mock(side_effect=failure)) + monkeypatch.setattr(cleanup.logger, 'error', log_error) + cleanup.remove_model_cache(tmp_path / 'cache', time.monotonic() + 30) + log_error.assert_called_once() + assert 'read-only cache' in str(log_error.call_args[0][-1]) + + +@pytest.mark.parametrize('interrupted', [False, True]) +def test_cleanup_timeout_reaps_its_process(tmp_path, monkeypatch, interrupted): + """Stop and reap a real stalled cleanup child on either its deadline or controller interruption.""" + cache = tmp_path / 'cache' + cache.mkdir() + children = [] + popen = subprocess.Popen + + def stalled_cleanup(command, **kwargs): + child = popen([sys.executable, '-c', 'import time; time.sleep(30)'], **kwargs) + children.append(child) + if interrupted: + monkeypatch.setattr(child, 'communicate', Mock(side_effect=TimeoutError('controller interrupted'))) + return child + + monkeypatch.setattr(cleanup.subprocess, 'Popen', stalled_cleanup) + start = time.monotonic() + try: + with pytest.raises(TimeoutError): + cleanup.remove_model_cache(cache, start + 0.25) + assert time.monotonic() - start < 3 + assert len(children) == 1 + assert children[0].returncode is not None + assert cache.is_dir() + finally: + for child in children: + if child.poll() is None: + child.kill() + child.wait(timeout=5) + + +@pytest.mark.parametrize('deadline,budget', [(400.0, cleanup.FAILURE_CLEANUP_GRACE_SECONDS), (1000.0, 500.0)]) +def test_failure_cleanup_uses_the_remaining_budget_or_grace(tmp_path, monkeypatch, deadline, budget): + """Give a failed run's cleanup the rest of its budget, or a fixed grace once that budget is spent.""" + run = Mock() + monkeypatch.setattr(cleanup, 'time', SimpleNamespace(monotonic=lambda: 500.0)) + monkeypatch.setattr(cleanup.subprocess, 'run', run) + cleanup.remove_model_cache_after_failure(tmp_path / 'cache', deadline) + assert run.call_args[1]['timeout'] == budget + + +@pytest.mark.parametrize( + 'failure', [subprocess.TimeoutExpired(['cleanup'], 1), + TimeoutError('Killed by SIGTERM or timeout!')] +) +def test_failure_cleanup_never_raises_a_timeout(tmp_path, monkeypatch, failure): + """Log an unfinished cleanup so that the failed run keeps its original error.""" + log_error = Mock() + monkeypatch.setattr(cleanup.subprocess, 'run', Mock(side_effect=failure)) + monkeypatch.setattr(cleanup.logger, 'error', log_error) + cleanup.remove_model_cache_after_failure(tmp_path / 'cache', time.monotonic()) + log_error.assert_called_once() + assert 'after a failed run' in log_error.call_args[0][0] diff --git a/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py b/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py index 7195e8aac..80e8e61a9 100644 --- a/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py +++ b/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py @@ -3,12 +3,15 @@ """CPU adapter tests; complete model correctness is checked by the GPU worker.""" +import subprocess from pathlib import Path +from types import SimpleNamespace from unittest.mock import Mock import pytest from superbench.benchmarks import BenchmarkType, ReturnCode +from superbench.benchmarks.model_benchmarks import deepseek_v2_lite_cache as cache_cleanup from superbench.benchmarks.model_benchmarks import pytorch_deepseek_v2_lite as adapter from superbench.benchmarks.model_benchmarks.deepseek_v2_lite_utils import identity_report, write_json @@ -140,9 +143,15 @@ def worker(command, log, timeout): assert (jobs[0] / 'report.json').is_file() is (outcome == 'success') -def test_cache_removal_failure_keeps_a_valid_measurement(benchmark, monkeypatch): +@pytest.mark.parametrize( + 'failure', + [PermissionError('read-only cache'), + subprocess.CalledProcessError(1, ['cleanup'], output='read-only cache')] +) +def test_cache_removal_failure_keeps_a_valid_measurement(benchmark, monkeypatch, failure): """Log a cleanup error without discarding metrics that were already validated.""" caches = [] + log_error = Mock() def worker(command, log, timeout): cache = Path(command[command.index('--cache_dir') + 1]) @@ -151,10 +160,13 @@ def worker(command, log, timeout): successful_worker(command, log, timeout) monkeypatch.setattr(adapter, 'run_worker', worker) - monkeypatch.setattr(adapter.shutil, 'rmtree', Mock(side_effect=PermissionError('read-only cache'))) + monkeypatch.setattr(cache_cleanup.subprocess, 'run', Mock(side_effect=failure)) + monkeypatch.setattr(adapter.logger, 'error', log_error) assert benchmark.run() assert benchmark.return_code == ReturnCode.SUCCESS assert caches[0].is_dir() + log_error.assert_called_once() + assert 'read-only cache' in str(log_error.call_args[0][-1]) def test_sigterm_during_cache_removal_still_reports_timeout(benchmark, monkeypatch): @@ -163,10 +175,101 @@ def worker(command, log, timeout): Path(command[command.index('--cache_dir') + 1]).mkdir(parents=True) successful_worker(command, log, timeout) + cleanup = Mock(side_effect=TimeoutError('Killed by SIGTERM or timeout!')) monkeypatch.setattr(adapter, 'run_worker', worker) - monkeypatch.setattr(adapter.shutil, 'rmtree', Mock(side_effect=TimeoutError('Killed by SIGTERM or timeout!'))) - benchmark.run() + monkeypatch.setattr(cache_cleanup.subprocess, 'run', cleanup) + assert not benchmark.run() assert benchmark.return_code == ReturnCode.KILLED_BY_TIMEOUT + assert 'end_to_end_seconds' not in benchmark.result + assert cleanup.call_count == 2 + + +@pytest.mark.parametrize('cleanup_seconds', [7, 50, 70]) +def test_cache_cleanup_counts_toward_the_job_deadline(benchmark, monkeypatch, cleanup_seconds): + """Include cleanup in elapsed time and reject the exact deadline as well as an overrun.""" + clock = [100.0] + run_cleanup = subprocess.run + + def worker(command, log, timeout): + assert timeout == 40 + Path(command[command.index('--cache_dir') + 1]).mkdir(parents=True) + successful_worker(command, log, timeout) + clock[0] += 10 + + def cleanup(command, **kwargs): + assert kwargs['timeout'] == 50 + result = run_cleanup(command, **kwargs) + clock[0] += cleanup_seconds + return result + + fake_time = SimpleNamespace(monotonic=lambda: clock[0]) + monkeypatch.setattr(adapter, 'time', fake_time) + monkeypatch.setattr(cache_cleanup, 'time', fake_time) + monkeypatch.setattr(adapter, 'run_worker', worker) + monkeypatch.setattr(cache_cleanup.subprocess, 'run', cleanup) + assert benchmark.run() is (cleanup_seconds < 50) + if cleanup_seconds < 50: + assert benchmark.return_code == ReturnCode.SUCCESS + assert benchmark.result['end_to_end_seconds'] == [10 + cleanup_seconds] + assert benchmark.result['bf16_train_tokens_per_second'] == [2 * 8 * 63 * 1000 / 30] + else: + assert benchmark.return_code == ReturnCode.KILLED_BY_TIMEOUT + assert 'end_to_end_seconds' not in benchmark.result + assert 'bf16_train_tokens_per_second' not in benchmark.result + + +def test_cleanup_after_the_deadline_uses_the_failure_grace(benchmark, monkeypatch): + """Fail an overrun job, then still remove its cache within the bounded failure grace.""" + clock = [100.0] + timeouts = [] + caches = [] + run_cleanup = subprocess.run + + def worker(command, log, timeout): + cache = Path(command[command.index('--cache_dir') + 1]) + cache.mkdir(parents=True) + caches.append(cache) + successful_worker(command, log, timeout) + clock[0] += 60 + + def cleanup(command, **kwargs): + timeouts.append(kwargs['timeout']) + return run_cleanup(command, **kwargs) + + fake_time = SimpleNamespace(monotonic=lambda: clock[0]) + monkeypatch.setattr(adapter, 'time', fake_time) + monkeypatch.setattr(cache_cleanup, 'time', fake_time) + monkeypatch.setattr(adapter, 'run_worker', worker) + monkeypatch.setattr(cache_cleanup.subprocess, 'run', cleanup) + assert not benchmark.run() + assert benchmark.return_code == ReturnCode.KILLED_BY_TIMEOUT + assert 'end_to_end_seconds' not in benchmark.result + assert timeouts == [cache_cleanup.FAILURE_CLEANUP_GRACE_SECONDS] + assert not caches[0].exists() + + +@pytest.mark.parametrize( + 'failure,code', [ + (RuntimeError('worker failed'), ReturnCode.RUNTIME_EXCEPTION_ERROR), + (TimeoutError('whole job deadline'), ReturnCode.KILLED_BY_TIMEOUT), + ] +) +def test_unfinished_failure_cleanup_keeps_the_original_error(benchmark, monkeypatch, failure, code): + """Report the worker failure rather than a later cleanup timeout, and log both.""" + log_error = Mock() + + def worker(command, log, timeout): + Path(command[command.index('--cache_dir') + 1]).mkdir(parents=True) + raise failure + + monkeypatch.setattr(adapter, 'run_worker', worker) + monkeypatch.setattr(cache_cleanup.subprocess, 'run', Mock(side_effect=subprocess.TimeoutExpired(['cleanup'], 1))) + monkeypatch.setattr(adapter.logger, 'error', log_error) + assert not benchmark.run() + assert benchmark.return_code == code + messages = [call[0][0] % call[0][1:] for call in log_error.call_args_list] + assert any(str(failure) in message for message in messages) + assert any('after a failed run' in message for message in messages) @pytest.mark.parametrize( From 18fc0e4bb2c74f0b2b5201b2539f724c012b448f Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:54:04 +0000 Subject: [PATCH 4/9] Docs - Condense V2-Lite training documentation Keep only what users need to run the benchmark and interpret its results: the workload and checks, MoE dispatch, validated profile, usage, cache cleanup and duration. Drop validation timings and implementation details, which remain in the pull request and code. Use full result names in the metrics table. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../benchmarks/model-benchmarks.md | 192 +++++------------- 1 file changed, 46 insertions(+), 146 deletions(-) diff --git a/docs/user-tutorial/benchmarks/model-benchmarks.md b/docs/user-tutorial/benchmarks/model-benchmarks.md index dde10673d..d34d72ba9 100644 --- a/docs/user-tutorial/benchmarks/model-benchmarks.md +++ b/docs/user-tutorial/benchmarks/model-benchmarks.md @@ -163,54 +163,38 @@ 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. | -## Official-checkpoint V2-Lite Training +## DeepSeek-V2-Lite Training ### `deepseek-v2-lite-training` -This opt-in, standalone MODEL benchmark downloads and hash-verifies the complete -`deepseek-ai/DeepSeek-V2-Lite` checkpoint at -`604d5664dddd88a0433dbae533b7fe9472482de0`, then performs full-parameter causal-LM -training. It is not the Megatron benchmark, a classifier-head workload, LoRA, or -the reduced hidden-size configuration from PR #765. - -The model has 15,706,484,224 parameters, hidden size 2048, 27 layers, MLA and MoE. -The four BF16 weight files total 31,413,626,576 bytes. Initial optimizer state is -new: this is short training from pretrained weights, not a resume of DeepSeek's -original optimizer or an attempt to train a converged model within an hour. -The small `fixed-text-v1` fixture uses the official tokenizer and packed token -sequences without padding. It is reproducible, not a production-data accuracy -or representativeness evaluation. Mock data and mocked subprocesses are used -only in auxiliary unit tests. - -#### Validation Status - -H100 acceptance applies only to the -recorded four-GPU stable-sorted/native-allocator profile, its exact runtime and -the corresponding source/configuration identities. It does not qualify the -default official-dispatch example, every H100 configuration or other SKUs. -That profile runs on Standard_ND96isrf_H100_v5 with `num_gpus=4`, -`batch_size=36`, `seq_len=512`, `num_warmup=2`, `num_steps=128`, -`moe_dispatch=stable_sorted` and `PYTORCH_CUDA_ALLOC_CONF=backend:native`. - -#### Runtime And Execution - -Use a separate worker environment; do not replace the legacy SuperBench -framework dependencies. The worker requires Python 3.10+, a GPU-compatible -PyTorch 2.5+ build, and the pinned packages in -[`deepseek-v2-lite-reference.txt`](../../../dockerfile/requirements/deepseek-v2-lite-reference.txt). -The supplied -[`model runtime Dockerfile`](../../../dockerfile/deepseek-v2-lite-training.dockerfile) -pins the CUDA PyTorch base by digest and installs the Python SuperBench -controller, runner and diagnosis entrypoints together with the worker/reference -environment. The -[`controller lock`](../../../dockerfile/requirements/deepseek-v2-lite-controller.txt) -is specific to Python 3.12/Linux x86_64 and retains the base image's GPU -Torch/torchvision builds. Its regeneration command is in the -[`lock inputs`](../../../dockerfile/requirements/deepseek-v2-lite-controller.in). -This opt-in model runtime does not replace the standard images or provide the -complete compiled microbenchmark suite. -The build checks the Torch/NumPy array bridge and the real runner/diagnosis CLI, -not just successful package installation. +#### Introduction + +Run full-parameter BF16 causal-LM training with the official +[DeepSeek-V2-Lite](https://huggingface.co/deepseek-ai/DeepSeek-V2-Lite) checkpoint at revision +`604d5664dddd88a0433dbae533b7fe9472482de0` (15.7B parameters). The worker starts `torchrun` on +`num_gpus` local GPUs (at least two) and trains on a small fixed-text dataset with fully sharded FSDP, +AdamW and activation checkpointing; `batch_size` is the microbatch per GPU. The job downloads the +checkpoint and verifies the SHA256 of its 31.4GB of weight files. Before training, the FSDP loss and +sampled gradients must match an unsharded official-code reference, and every step must produce a +finite loss and a finite, nonzero gradient norm. Training starts from the pretrained weights with a +new optimizer state; it measures training performance, not convergence or model quality. + +`moe_dispatch` defaults to `official`. `stable_sorted` groups routed tokens with a stable sort instead +of repeated Boolean indexing; it keeps the same experts, routing and weights, and the reference check +compares it with the official implementation. + +Validation covers one profile on four H100 80GB GPUs: `batch_size=36`, `seq_len=512`, +`num_warmup=2`, `num_steps=128`, `moe_dispatch=stable_sorted` and +`PYTORCH_CUDA_ALLOC_CONF=backend:native`. The supplied profile is a smaller example +(`batch_size=2`, `num_steps=8`, official dispatch); other configurations are not validated. The +unsharded reference runs on one GPU, so use 80GB-class GPUs. + +#### Usage + +Run the [training profile](../../../superbench/config/deepseek-v2-lite-training.yaml) as its own +benchmark entry with one local process (`proc_num: 1`). The +[model runtime Dockerfile](../../../dockerfile/deepseek-v2-lite-training.dockerfile) provides the +worker environment: ```bash docker build -f dockerfile/deepseek-v2-lite-training.dockerfile -t sb-v2lite-training . @@ -221,105 +205,21 @@ docker run --rm --gpus '"device=0,1,2,3"' --shm-size 32g \ -C superbench.benchmarks.deepseek-v2-lite-training.parameters.cache_root=/results/model-cache ``` -For a separately prepared native installation: -```bash -python3 -m venv --system-site-packages /opt/deepseek-reference -/opt/deepseek-reference/bin/pip install -r dockerfile/requirements/deepseek-v2-lite-reference.txt -sb exec --config-file superbench/config/deepseek-v2-lite-training.yaml -``` +Outside Docker, set `runtime_python` to a separate Python 3.10+ environment with a GPU build of +PyTorch 2.5+ and the [reference packages](../../../dockerfile/requirements/deepseek-v2-lite-reference.txt). + +`cache_root` is required. Each run downloads the checkpoint into a new directory under it and deletes +that model cache at the end, keeping the report and logs. If deletion fails, the cache path is logged +for manual removal. `duration` must be below 3600 seconds and covers the whole job, from download to +cache deletion. + +#### Metrics -The native command assumes SuperBench is already installed in the controller's -environment. Change `runtime_python` if the prepared worker environment lives -elsewhere. Install a compatible CUDA/ROCm PyTorch build before preparing the -worker, rather than letting a generic package install choose the GPU backend. - -Select the -[`training profile`](../../../superbench/config/deepseek-v2-lite-training.yaml) -as its own benchmark entry, with one local launcher. The worker launches -`torchrun --standalone` across `num_gpus` local GPUs. Do not launch this entry -once per GPU or combine it with other models, precisions or actions under the -same deadline. `batch_size` is the microbatch per GPU. - -`moe_dispatch` defaults to `official`. The opt-in `stable_sorted` implementation -groups routed tokens with a stable sort instead of repeated Boolean indexing. -It preserves route order, every expert, router weights, shared experts and -auxiliary-loss gradients; it does not add expert parallelism or remove model -parameters. Only the 26 pinned MoE training forwards change. Evaluation and the -independent unsharded reference retain the official implementation. -The worker records the selected dispatch and rewritten-layer count, and the -adapter rejects missing or mismatched dispatch evidence. Choosing this option -does not by itself qualify a hardware profile or its one-hour budget. - -FSDP shards the full model, gradients and FP32 AdamW master/optimizer state. -Activation checkpointing is enabled for the measured workload. This is not -expert parallelism and does not qualify a Megatron or all-to-all dispatch path. -The default example uses four GPUs and microbatch two, retaining a global batch -of eight sequences. The complete profile also runs an unsharded BF16 loss and -gradient reference on one GPU; use 80GB-class GPUs for this initial example. -This is not a minimum-card proof or a recommendation to replicate the full -model with DDP: FP32 AdamW training state must fit across the selected shards. -Registration for CUDA/ROCm denotes an implementation route, not certification -of every GPU, runtime or memory configuration. - -#### Correctness, Timing And Results - -Before optimization, an unsharded official-code BF16 reference checks the -complete model's loss and sampled embedding, dense, MLA, router and active-expert -gradients against FSDP. Gradient probes include nonzero and distributed positions; -they are not an exhaustive comparison of every parameter. Every training step -requires finite loss and a finite nonzero global gradient norm. The first update -must change model parameters. No checkpoint missing-key or shape mismatch is -accepted. -The reference preserves every sequence of the actual global batch, full context -length and exact per-rank microbatch shape. It evaluates rank batches sequentially -with the complete model and activation checkpointing, requesting gradients only -for the existing probe parameter families. Other reference parameter-gradient -buffers are not materialized; no weights are removed or frozen. The measured -training worker still computes and updates the complete model. -Unused returned vocabulary logits are released before backward. Per-rank losses, -global loss and FP32-averaged gradient probes are checked separately. Replicating -one identical short input or regrouping BF16 rank batches would not establish -this distributed-reduction contract. -The one-time pre-update parameter snapshot is stored in host memory and checked -after the update. Model parameters, gradients and optimizer state remain on the -GPUs; this is validation storage, not training-state CPU offload. - -`cache_root` is required. Every invocation creates its own empty -HF/Hub/Xet/module cache and keeps its report and logs under a new directory in -`cache_root`. After the worker exits, the adapter deletes that 31.4GB model -cache and keeps the report and logs; shared caches are not touched. On a -successful run, cleanup must finish within `duration`; otherwise the run fails -as a timeout. After a failed or timed-out run, cleanup may continue until the -job deadline or for 60 seconds, whichever ends later; an unfinished cleanup is -logged without replacing the original error. Other filesystem errors are logged -without discarding validated measurements. Interrupted cleanup can leave a cache -at the logged path. - -`duration` covers download, SHA256 verification, loading, correctness, -warmup, measured training, worker/rank teardown and model-cache cleanup. It must -be below 3600 seconds; the worker deadline leaves 20 seconds for teardown and -cleanup, and the controller finalizes the elapsed time and success result after -cleanup. A watchdog exit is a failure. -Image pulling, dependency preparation and SuperBench installation are separate -runtime-preparation steps, not certified by the model-cold timer. - -A dedicated Linux child supervisor reaps the complete worker tree, including -torchrun ranks that start separate sessions. A launcher exit with surviving -descendants is a failure; timeout cleanup escalates from termination to forced -exit and verifies that owned children were reaped without targeting other jobs. -The worker records Unix timestamps bounding the measured phase for external -GPU telemetry; the step durations continue to use the monotonic clock. - -| Metric | Unit | Scope | -| --- | --- | --- | -| `bf16_train_step_time` | ms | Mean of the slowest synchronized rank per measured step | -| `bf16_train_tokens_per_second` | loss tokens/s | Global next-token targets, excluding each sequence's first position | -| `bf16_train_loss` | loss | Global mean causal-LM loss | -| `bf16_train_gradient_norm` | norm | Global gradient norm before clipping | -| `end_to_end_seconds` | s | Complete invocation through report validation and model-cache cleanup | -| `checkpoint_bytes` | bytes | Complete weight files, not measured network traffic or GPU memory | - -Step timing includes forward, backward, clipping and the optimizer update. -Input preparation/copy and reference/update checks are excluded from the -steady step metric but included in the complete-job time. Keep model-cold -acceptance, per-GPU utilization and model quality as separate conclusions. +| 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. | From 69ad25e4ef156ccd1d3b7b5200de7a468910dd1a Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Fri, 30 Oct 2026 01:05:35 +0000 Subject: [PATCH 5/9] Benchmarks - Move DeepSeek-V2-Lite helpers into a subpackage Group the V2-Lite worker, reference, MoE dispatch, utility and cache modules under superbench/benchmarks/model_benchmarks/deepseek_v2_lite/; the adapter stays flat like the other model benchmarks. Workers start as `python -m deepseek_v2_lite.` with the package parent on PYTHONPATH and use package-relative imports, so worker interpreters still need no SuperBench install. Merge the tests into one file for this benchmark and one for the shared helpers, and drop tests that repeat another test's coverage or check trivial guards. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../deepseek_v2_lite/__init__.py | 8 + .../cache.py} | 0 .../moe.py} | 0 .../reference.py} | 2 +- .../training_worker.py} | 6 +- .../utils.py} | 14 +- .../pytorch_deepseek_v2_lite.py | 19 +- .../model_benchmarks/test_deepseek_v2_lite.py | 715 ++++++++++++++++++ .../test_deepseek_v2_lite_cache.py | 110 --- .../test_deepseek_v2_lite_moe.py | 148 ---- .../test_deepseek_v2_lite_reference.py | 377 --------- .../test_deepseek_v2_lite_training_worker.py | 285 ------- .../test_deepseek_v2_lite_utils.py | 345 --------- .../test_pytorch_deepseek_v2_lite.py | 479 +++++++++--- 14 files changed, 1143 insertions(+), 1365 deletions(-) create mode 100644 superbench/benchmarks/model_benchmarks/deepseek_v2_lite/__init__.py rename superbench/benchmarks/model_benchmarks/{deepseek_v2_lite_cache.py => deepseek_v2_lite/cache.py} (100%) rename superbench/benchmarks/model_benchmarks/{deepseek_v2_lite_moe.py => deepseek_v2_lite/moe.py} (100%) rename superbench/benchmarks/model_benchmarks/{deepseek_v2_lite_reference.py => deepseek_v2_lite/reference.py} (99%) rename superbench/benchmarks/model_benchmarks/{deepseek_v2_lite_training_worker.py => deepseek_v2_lite/training_worker.py} (98%) rename superbench/benchmarks/model_benchmarks/{deepseek_v2_lite_utils.py => deepseek_v2_lite/utils.py} (96%) create mode 100644 tests/benchmarks/model_benchmarks/test_deepseek_v2_lite.py delete mode 100644 tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_cache.py delete mode 100644 tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_moe.py delete mode 100644 tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_reference.py delete mode 100644 tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_training_worker.py delete mode 100644 tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_utils.py diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/__init__.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/__init__.py new file mode 100644 index 000000000..9cc630068 --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/__init__.py @@ -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.`` in interpreters without SuperBench, so every module +except ``cache`` imports only the standard library and this package at load time. +""" diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_cache.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/cache.py similarity index 100% rename from superbench/benchmarks/model_benchmarks/deepseek_v2_lite_cache.py rename to superbench/benchmarks/model_benchmarks/deepseek_v2_lite/cache.py diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_moe.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/moe.py similarity index 100% rename from superbench/benchmarks/model_benchmarks/deepseek_v2_lite_moe.py rename to superbench/benchmarks/model_benchmarks/deepseek_v2_lite/moe.py diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_reference.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/reference.py similarity index 99% rename from superbench/benchmarks/model_benchmarks/deepseek_v2_lite_reference.py rename to superbench/benchmarks/model_benchmarks/deepseek_v2_lite/reference.py index 1d6e05a6b..313d2c89b 100644 --- a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_reference.py +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/reference.py @@ -8,7 +8,7 @@ import os from pathlib import Path -from deepseek_v2_lite_utils import ( +from .utils import ( FIXED_TEXTS, PARAMETER_COUNT, packed_tokens, read_json, uniform_indices, validate_config, write_json ) diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_training_worker.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/training_worker.py similarity index 98% rename from superbench/benchmarks/model_benchmarks/deepseek_v2_lite_training_worker.py rename to superbench/benchmarks/model_benchmarks/deepseek_v2_lite/training_worker.py index 8e61e5d36..a06f3e7ce 100644 --- a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_training_worker.py +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/training_worker.py @@ -12,9 +12,9 @@ from functools import partial from pathlib import Path -from deepseek_v2_lite_moe import MOE_DISPATCHES, install_sorted_dispatch -from deepseek_v2_lite_reference import fixed_documents, load_model, training_reference -from deepseek_v2_lite_utils import ( +from .moe import MOE_DISPATCHES, install_sorted_dispatch +from .reference import fixed_documents, load_model, training_reference +from .utils import ( configure_cache, download_checkpoint, identity_report, interrupt_worker, packed_tokens, read_json, set_cache_environment, write_json ) diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_utils.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/utils.py similarity index 96% rename from superbench/benchmarks/model_benchmarks/deepseek_v2_lite_utils.py rename to superbench/benchmarks/model_benchmarks/deepseek_v2_lite/utils.py index ca73360ef..0a44520ef 100644 --- a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_utils.py +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/utils.py @@ -12,7 +12,7 @@ import sys import time from pathlib import Path -from typing import Dict, List, Sequence +from typing import Dict, List, Optional, Sequence MODEL_ID = 'deepseek-ai/DeepSeek-V2-Lite' REVISION = '604d5664dddd88a0433dbae533b7fe9472482de0' @@ -283,7 +283,15 @@ def interrupt_worker(signum, frame) -> None: raise TimeoutError('Model worker interrupted by signal {}.'.format(signum)) -def run_worker(command: List[str], log: Path, timeout: float) -> None: +def worker_environment() -> Dict[str, str]: + """Let worker interpreters without SuperBench import this package by module name.""" + environment = dict(os.environ) + paths = [str(Path(__file__).resolve().parents[1]), environment.get('PYTHONPATH', '')] + environment['PYTHONPATH'] = os.pathsep.join(path for path in paths if path) + return environment + + +def run_worker(command: List[str], log: Path, timeout: float, env: Optional[Dict[str, str]] = None) -> None: """Supervise the whole worker tree under one deadline, preserving failure logs.""" if not math.isfinite(timeout) or timeout <= 0: raise TimeoutError('No time remains for the worker.') @@ -300,7 +308,7 @@ def run_worker(command: List[str], log: Path, timeout: float) -> None: *command, ] with log.open('w') as stream: - process = subprocess.Popen(supervisor, stdout=stream, stderr=subprocess.STDOUT, start_new_session=True) + process = subprocess.Popen(supervisor, stdout=stream, stderr=subprocess.STDOUT, start_new_session=True, env=env) try: try: code = process.wait(timeout=timeout + 20) diff --git a/superbench/benchmarks/model_benchmarks/pytorch_deepseek_v2_lite.py b/superbench/benchmarks/model_benchmarks/pytorch_deepseek_v2_lite.py index 291788870..5dd47c78d 100644 --- a/superbench/benchmarks/model_benchmarks/pytorch_deepseek_v2_lite.py +++ b/superbench/benchmarks/model_benchmarks/pytorch_deepseek_v2_lite.py @@ -13,12 +13,12 @@ from superbench.benchmarks import BenchmarkRegistry, BenchmarkType, Platform, ReturnCode from superbench.benchmarks.base import Benchmark from superbench.common.utils import logger -from superbench.benchmarks.model_benchmarks.deepseek_v2_lite_cache import ( +from superbench.benchmarks.model_benchmarks.deepseek_v2_lite.cache import ( remove_model_cache, remove_model_cache_after_failure ) -from superbench.benchmarks.model_benchmarks.deepseek_v2_lite_moe import MOE_DISPATCHES -from superbench.benchmarks.model_benchmarks.deepseek_v2_lite_utils import ( - numeric_series, read_json, run_worker, validate_identity +from superbench.benchmarks.model_benchmarks.deepseek_v2_lite.moe import MOE_DISPATCHES +from superbench.benchmarks.model_benchmarks.deepseek_v2_lite.utils import ( + numeric_series, read_json, run_worker, validate_identity, worker_environment ) @@ -75,7 +75,6 @@ def _preprocess(self): def _worker_command(self, job): """Launch all local GPUs once, retaining argv boundaries.""" - worker = Path(__file__).with_name('deepseek_v2_lite_training_worker.py') args = self._args return [ args.runtime_python, @@ -83,7 +82,8 @@ def _worker_command(self, job): 'torch.distributed.run', '--standalone', '--nproc_per_node={}'.format(args.num_gpus), - str(worker), + '--module', + 'deepseek_v2_lite.training_worker', '--cache_dir', str(job / 'cache'), '--output', @@ -135,7 +135,12 @@ def _benchmark(self): job = Path(tempfile.mkdtemp(prefix='v2lite-training-', dir=str(root))) try: logger.info('V2-Lite training evidence and isolated cache: %s', job) - run_worker(self._worker_command(job), job / 'worker.log', deadline - time.monotonic() - 20) + run_worker( + self._worker_command(job), + job / 'worker.log', + deadline - time.monotonic() - 20, + env=worker_environment(), + ) report = read_json(job / 'report.json') validate_identity(report) steps = numeric_series(report, 'step_ms', self._args.num_steps) diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite.py new file mode 100644 index 000000000..3934bc0fb --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite.py @@ -0,0 +1,715 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""CPU tests for the shared DeepSeek-V2-Lite helpers: checkpoint, worker supervision, cache and reference.""" + +import copy +import ctypes +import hashlib +import json +import math +import os +import signal +import subprocess +import sys +import time +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +from superbench.benchmarks.model_benchmarks.deepseek_v2_lite import ( + cache as cleanup, reference as reference_module, utils +) + +torch = pytest.importorskip('torch') + + +# Checkpoint identity, fixed inputs and worker supervision. +def test_checkpoint_identity(): + """Reject architecture proxies and quantization.""" + config = dict(utils.EXPECTED_CONFIG, model_type='deepseek_v2') + utils.validate_config(config) + config['hidden_size'] = 1024 + with pytest.raises(ValueError, match='hidden_size'): + utils.validate_config(config) + config['hidden_size'] = 2048 + config['quantization_config'] = {'quant_method': 'fp8'} + with pytest.raises(ValueError, match='quantized'): + utils.validate_config(config) + assert utils.WEIGHT_BYTES == 31413626576 + + +def test_packed_text_is_reproducible(): + """Pack actual token inputs with EOS separators, not padding or mock execution.""" + documents = [[1, 2], [3, 4, 5]] + expected = [[1, 2, 9, 3], [4, 5, 9, 1]] + assert utils.packed_tokens(documents, 9, 4, 2) == expected + assert utils.packed_tokens(documents, 9, 4, 2) == expected + assert utils.packed_tokens(documents, 9, 4, 2, offset=1) != expected + + +@pytest.mark.parametrize('documents,length,count', [([], 4, 1), ([[]], 4, 1), ([[True]], 4, 1), ([[1]], 1, 1)]) +def test_invalid_text_inputs(documents, length, count): + """Surface malformed inputs instead of returning an empty batch.""" + with pytest.raises(ValueError): + utils.packed_tokens(documents, 9, length, count) + + +def test_cold_cache_isolated(tmp_path, monkeypatch): + """Reject cache reuse without deleting shared contents.""" + shared = tmp_path / 'shared' + shared.mkdir() + sentinel = shared / 'keep' + sentinel.write_text('unrelated data') + monkeypatch.setenv('HF_HOME', str(shared)) + cache = tmp_path / 'cold' + utils.configure_cache(cache) + assert sentinel.read_text() == 'unrelated data' + assert utils.os.environ['HF_HOME'] == str(cache / 'hf') + assert utils.os.environ['HF_XET_CACHE'] == str(cache / 'xet') + (cache / 'present').touch() + with pytest.raises(ValueError, match='empty'): + utils.configure_cache(cache) + + +def test_report_requires_correctness_and_teardown(): + """Require model identity, not just a successful process exit.""" + report = dict(utils.identity_report(), status='success', correctness_passed=True, teardown_complete=True) + utils.validate_identity(report) + incorrect = copy.deepcopy(report) + incorrect['parameter_count'] = 100 + with pytest.raises(ValueError, match='contract'): + utils.validate_identity(incorrect) + report['correctness_passed'] = False + with pytest.raises(ValueError, match='Correctness'): + utils.validate_identity(report) + + +@pytest.mark.parametrize('length', [1, 512, 209715200, 15706484224]) +def test_large_tensor_probe_indices(length): + """FP32-rounded endpoints must never index beyond a real full-model tensor.""" + indices = utils.uniform_indices(length) + assert len(indices) == 256 + assert indices[0] == 0 and indices[-1] == length - 1 + assert all(0 <= index < length for index in indices) + + +def test_atomic_json_rejects_nonfinite_values(tmp_path): + """A malformed report must not replace a complete report.""" + path = tmp_path / 'report.json' + utils.write_json(path, {'value': 1}) + with pytest.raises(ValueError): + utils.write_json(path, {'value': math.nan}) + assert utils.read_json(path) == {'value': 1} + path.write_text('{"value": NaN}') + with pytest.raises(ValueError, match='Nonfinite'): + utils.read_json(path) + + +def test_worker_failure_is_explicit(tmp_path): + """Reject nonzero exit codes even if the worker writes a result-like message.""" + with pytest.raises(RuntimeError, match='code 7'): + utils.run_worker([sys.executable, '-c', 'print("success"); raise SystemExit(7)'], tmp_path / 'worker.log', 5) + assert 'success' in (tmp_path / 'worker.log').read_text() + + +def test_timeout_reaps_worker(tmp_path): + """A timeout must terminate the created process rather than leave a worker.""" + pid_file = tmp_path / 'pid' + command = [ + sys.executable, + '-c', + 'import os,time; from pathlib import Path; Path({!r}).write_text(str(os.getpid())); time.sleep(60)'.format( + str(pid_file) + ), + ] + with pytest.raises(TimeoutError, match='deadline'): + utils.run_worker(command, tmp_path / 'worker.log', 1) + pid = int(pid_file.read_text()) + with pytest.raises(ProcessLookupError): + utils.os.kill(pid, 0) + + +def test_success_with_live_child_is_rejected(tmp_path): + """A leader's exit code zero is insufficient when its child remains alive.""" + command = [ + sys.executable, + '-c', + 'import subprocess,sys; subprocess.Popen([sys.executable,"-c","import time; time.sleep(60)"])', + ] + with pytest.raises(RuntimeError, match='descendant processes'): + utils.run_worker(command, tmp_path / 'worker.log', 5) + + +@pytest.mark.parametrize('launcher_exits', [False, True]) +def test_separate_session_child_is_reaped(tmp_path, launcher_exits): + """Own escaped rank sessions even when their launcher exits or ignores termination.""" + pid_file = tmp_path / 'rank.pid' + rank = ( + 'import os,signal,time; from pathlib import Path; ' + 'signal.signal(signal.SIGTERM, signal.SIG_IGN); ' + 'Path({!r}).write_text(str(os.getpid())); time.sleep(60)' + ).format(str(pid_file)) + launcher = ( + 'import signal,subprocess,sys,time; from pathlib import Path; ' + 'signal.signal(signal.SIGTERM, signal.SIG_IGN); ' + 'subprocess.Popen([sys.executable, "-c", {!r}], start_new_session=True); ' + 'ready=Path({!r})\n' + 'while not ready.exists(): time.sleep(0.01)\n' + '{}' + ).format(rank, str(pid_file), 'sys.exit(0)' if launcher_exits else 'time.sleep(60)') + try: + expected = RuntimeError if launcher_exits else TimeoutError + with pytest.raises(expected): + utils.run_worker([sys.executable, '-c', launcher], tmp_path / 'worker.log', 5 if launcher_exits else 1) + pid = int(pid_file.read_text()) + with pytest.raises(ProcessLookupError): + os.kill(pid, 0) + finally: + if pid_file.exists(): + pid = int(pid_file.read_text()) + try: + os.kill(pid, signal.SIGKILL) + except ProcessLookupError: + pass + + +def test_worker_signal_does_not_kill_unrelated_process(tmp_path): + """Timeout cleanup must be scoped to the supervised job, not the controller's children.""" + unrelated = utils.subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)']) + try: + with pytest.raises(TimeoutError): + utils.run_worker([sys.executable, '-c', 'import time; time.sleep(60)'], tmp_path / 'worker.log', 0.2) + assert unrelated.poll() is None + finally: + unrelated.terminate() + unrelated.wait(timeout=5) + + +def test_controller_death_reaps_owned_worker(tmp_path): + """A killed controller must not leave its independently supervised job alive.""" + pid_file = tmp_path / 'worker.pid' + worker = ('import os,time; from pathlib import Path; ' + 'Path({!r}).write_text(str(os.getpid())); time.sleep(60)').format(str(pid_file)) + controller = ( + 'import sys; from pathlib import Path; sys.path.insert(0, {!r}); ' + 'from deepseek_v2_lite.utils import run_worker; ' + 'run_worker([sys.executable, "-c", {!r}], Path({!r}), 60)' + ).format(str(Path(utils.__file__).resolve().parents[1]), worker, str(tmp_path / 'worker.log')) + process = utils.subprocess.Popen([sys.executable, '-c', controller]) + try: + deadline = time.monotonic() + 5 + while not pid_file.exists() and time.monotonic() < deadline: + time.sleep(0.02) + assert pid_file.exists() + pid = int(pid_file.read_text()) + process.kill() + process.wait(timeout=5) + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + try: + os.kill(pid, 0) + except ProcessLookupError: + break + time.sleep(0.02) + else: + pytest.fail('The worker survived its controller.') + finally: + if process.poll() is None: + process.kill() + process.wait(timeout=5) + if pid_file.exists(): + try: + os.kill(int(pid_file.read_text()), signal.SIGKILL) + except ProcessLookupError: + pass + + +@pytest.fixture +def checkpoint_files(tmp_path, monkeypatch): + """Create small real files to test the checkpoint integrity contract.""" + root = tmp_path / 'checkpoint' + root.mkdir() + contents = b'CPU checkpoint integrity fixture' + shard = root / 'weights.safetensors' + shard.write_bytes(contents) + monkeypatch.setattr(utils, 'WEIGHT_FILES', { + shard.name: (len(contents), hashlib.sha256(contents).hexdigest()), + }) + utils.write_json(root / 'config.json', dict(utils.EXPECTED_CONFIG, model_type='deepseek_v2')) + utils.write_json(root / 'model.safetensors.index.json', {'weight_map': {'fixture.weight': shard.name}}) + return root, shard + + +@pytest.mark.parametrize('failure', ['missing', 'size', 'hash', 'index']) +def test_invalid_checkpoint_files_fail(checkpoint_files, failure): + """Corrupted, missing or misindexed shards must never become a valid checkpoint.""" + root, shard = checkpoint_files + if failure == 'missing': + shard.unlink() + elif failure == 'size': + shard.write_bytes(b'short') + elif failure == 'hash': + shard.write_bytes(b'x' * shard.stat().st_size) + else: + utils.write_json(root / 'model.safetensors.index.json', {'weight_map': {'fixture.weight': 'other'}}) + with pytest.raises(ValueError): + utils.verify_checkpoint(root) + + +def test_download_uses_pinned_public_identity_and_then_verifies(checkpoint_files, monkeypatch): + """Disable implicit credentials and require the downloaded shard contract.""" + root, shard = checkpoint_files + download = Mock() + monkeypatch.setitem(sys.modules, 'huggingface_hub', SimpleNamespace(snapshot_download=download)) + assert utils.download_checkpoint(root.parent) == root + arguments = download.call_args[1] + assert arguments['repo_id'] == utils.MODEL_ID + assert arguments['revision'] == utils.REVISION + assert arguments['token'] is False + assert arguments['local_dir'] == str(root) + assert shard.name in arguments['allow_patterns'] + + +@pytest.mark.parametrize('timeout', [0, -1, float('nan')]) +def test_invalid_worker_deadline_fails_before_launch(tmp_path, timeout): + """A nonfinite or expired budget must not start a worker.""" + with pytest.raises(TimeoutError): + utils.run_worker([sys.executable, '-c', 'pass'], tmp_path / 'worker.log', timeout) + + +def test_worker_interrupt_is_failure(): + """A termination request must unwind the worker's normal success path.""" + with pytest.raises(TimeoutError, match='interrupted'): + utils.interrupt_worker(signal.SIGTERM, None) + + +def test_supervisor_requires_kernel_ownership_support(monkeypatch): + """Fail before spawning when kernel ownership setup is unavailable.""" + monkeypatch.setattr(utils.signal, 'signal', Mock()) + monkeypatch.setattr(ctypes, 'CDLL', lambda *args, **kwargs: SimpleNamespace(prctl=lambda *args: -1)) + monkeypatch.setattr(ctypes, 'get_errno', lambda: 13) + spawn = Mock() + monkeypatch.setattr(utils.subprocess, 'Popen', spawn) + with pytest.raises(OSError): + utils.supervise_worker([sys.executable, '-c', 'pass'], 1, os.getppid()) + spawn.assert_not_called() + + +# Per-run model cache removal. +def test_removes_only_the_run_cache(tmp_path): + """Delete the downloaded checkpoint while keeping the run's report and logs.""" + cache = tmp_path / 'cache' + (cache / 'checkpoint').mkdir(parents=True) + (cache / 'checkpoint' / 'model-00001-of-000004.safetensors').write_bytes(b'weights') + (tmp_path / 'report.json').write_text('{}') + cleanup.remove_model_cache(cache, time.monotonic() + 30) + assert not cache.exists() + assert (tmp_path / 'report.json').is_file() + + +def test_cleanup_does_not_start_without_budget(tmp_path, monkeypatch): + """Never start an unbounded deletion after the deadline.""" + run = Mock() + monkeypatch.setattr(cleanup.subprocess, 'run', run) + with pytest.raises(TimeoutError, match='No time remains'): + cleanup.remove_model_cache(tmp_path / 'cache', time.monotonic()) + run.assert_not_called() + + +@pytest.mark.parametrize( + 'failure', + [PermissionError('read-only cache'), + subprocess.CalledProcessError(1, ['cleanup'], output='read-only cache')] +) +def test_filesystem_errors_are_logged(tmp_path, monkeypatch, failure): + """Report a cleanup error without treating it as a failed measurement.""" + log_error = Mock() + monkeypatch.setattr(cleanup.subprocess, 'run', Mock(side_effect=failure)) + monkeypatch.setattr(cleanup.logger, 'error', log_error) + cleanup.remove_model_cache(tmp_path / 'cache', time.monotonic() + 30) + log_error.assert_called_once() + assert 'read-only cache' in str(log_error.call_args[0][-1]) + + +@pytest.mark.parametrize('interrupted', [False, True]) +def test_cleanup_timeout_reaps_its_process(tmp_path, monkeypatch, interrupted): + """Stop and reap a real stalled cleanup child on either its deadline or controller interruption.""" + cache = tmp_path / 'cache' + cache.mkdir() + children = [] + popen = subprocess.Popen + + def stalled_cleanup(command, **kwargs): + child = popen([sys.executable, '-c', 'import time; time.sleep(30)'], **kwargs) + children.append(child) + if interrupted: + monkeypatch.setattr(child, 'communicate', Mock(side_effect=TimeoutError('controller interrupted'))) + return child + + monkeypatch.setattr(cleanup.subprocess, 'Popen', stalled_cleanup) + start = time.monotonic() + try: + with pytest.raises(TimeoutError): + cleanup.remove_model_cache(cache, start + 0.25) + assert time.monotonic() - start < 3 + assert len(children) == 1 + assert children[0].returncode is not None + assert cache.is_dir() + finally: + for child in children: + if child.poll() is None: + child.kill() + child.wait(timeout=5) + + +@pytest.mark.parametrize('deadline,budget', [(400.0, cleanup.FAILURE_CLEANUP_GRACE_SECONDS), (1000.0, 500.0)]) +def test_failure_cleanup_uses_the_remaining_budget_or_grace(tmp_path, monkeypatch, deadline, budget): + """Give a failed run's cleanup the rest of its budget, or a fixed grace once that budget is spent.""" + run = Mock() + monkeypatch.setattr(cleanup, 'time', SimpleNamespace(monotonic=lambda: 500.0)) + monkeypatch.setattr(cleanup.subprocess, 'run', run) + cleanup.remove_model_cache_after_failure(tmp_path / 'cache', deadline) + assert run.call_args[1]['timeout'] == budget + + +@pytest.mark.parametrize( + 'failure', [subprocess.TimeoutExpired(['cleanup'], 1), + TimeoutError('Killed by SIGTERM or timeout!')] +) +def test_failure_cleanup_never_raises_a_timeout(tmp_path, monkeypatch, failure): + """Log an unfinished cleanup so that the failed run keeps its original error.""" + log_error = Mock() + monkeypatch.setattr(cleanup.subprocess, 'run', Mock(side_effect=failure)) + monkeypatch.setattr(cleanup.logger, 'error', log_error) + cleanup.remove_model_cache_after_failure(tmp_path / 'cache', time.monotonic()) + log_error.assert_called_once() + assert 'after a failed run' in log_error.call_args[0][0] + + +# Official-code reference. +@pytest.fixture +def reference(monkeypatch): + """Return the reference and redirect only test tensor creation to CPU.""" + tensor = torch.tensor + + def cpu_tensor(data, *args, **kwargs): + if kwargs.get('device') == 'cuda': + kwargs['device'] = 'cpu' + return tensor(data, *args, **kwargs) + + monkeypatch.setattr(torch, 'tensor', cpu_tensor) + return reference_module + + +class ReferenceFixture: + """Expose token-independent logits while checking cached attention shapes.""" + def __init__(self): + """Track cache and full-prefix calls separately.""" + self.calls = [] + + def eval(self): + """Retain the minimal evaluation interface used by the oracle.""" + return self + + def __call__(self, input_ids, attention_mask, past_key_values=None, use_cache=True): + """Require a mask for all past and current positions, including one-token decode.""" + length = input_ids.shape[1] + total = length + (past_key_values or 0) + assert attention_mask.shape == (1, total) + assert attention_mask.all().item() + self.calls.append((length, total, past_key_values, use_cache)) + logits = torch.tensor([0.0, 1.0, 2.0, 3.0]).reshape(1, 1, 4).repeat(1, length, 1) + return SimpleNamespace(logits=logits, past_key_values=total if use_cache else None) + + +def request_fixture(): + """Provide exact fixture probabilities rather than a model-quality claim.""" + probabilities = torch.tensor([0.0, 1.0, 2.0, 3.0]).log_softmax(-1).tolist() + return { + 'prompt_token_ids': [1, 2], + 'token_ids': [3, 3], + 'logprobs': [{str(index): value + for index, value in enumerate(probabilities)} for _ in range(2)], + } + + +def test_cached_decode_mask_covers_full_prefix(reference): + """The second cache call has one input token but a three-position mask.""" + model = ReferenceFixture() + result = reference.inference_reference(model, [request_fixture()]) + assert model.calls == [(2, 2, None, True), (2, 2, None, False), (1, 3, 2, True), (3, 3, None, False)] + assert len(result['comparisons']) == 2 + assert all(row['cache_max_abs_error'] == 0 for row in result['comparisons']) + + +@pytest.mark.parametrize('requests', [[], [{'prompt_token_ids': [], 'token_ids': [], 'logprobs': []}]]) +def test_incomplete_reference_requests_fail(reference, requests): + """Never accept an empty or truncated numerical workload.""" + with pytest.raises(ValueError, match='nonempty|Incomplete'): + reference.inference_reference(ReferenceFixture(), requests) + + +def test_reference_requires_greedy_token_agreement(reference): + """Finite probabilities alone must not certify an incorrect generated token.""" + request = request_fixture() + request['token_ids'][0] = 1 + with pytest.raises(RuntimeError, match='greedy token'): + reference.inference_reference(ReferenceFixture(), [request]) + + +def test_reference_does_not_ignore_probability_mismatch(reference): + """Keep the numerical gate even when all generated tokens are correct.""" + request = request_fixture() + request['logprobs'][0]['3'] += 1.0 + with pytest.raises(AssertionError, match='request 0 step 0'): + reference.inference_reference(ReferenceFixture(), [request]) + + +@pytest.mark.parametrize('positions', [[], [0], [1], [0, 0, 1], [1, 0], [0, 2], [False, 1]]) +def test_invalid_full_prefix_sampling_fails(reference, positions): + """Do not accept malformed or first/final-step-incomplete numerical evidence.""" + request = request_fixture() + request['full_prefix_steps'] = positions + with pytest.raises(ValueError, match='reference positions'): + reference.inference_reference(ReferenceFixture(), [request]) + + +class TrainingReferenceFixture: + """Small autograd fixture for global-batch partitioning, not GPU model validation.""" + def __init__(self): + """Create the named parameters required by reference sampling.""" + names = [ + 'model.embed_tokens.weight', + 'model.layers.0.self_attn.q_proj.weight', + 'model.layers.0.self_attn.kv_a_proj_with_mqa.weight', + 'model.layers.0.mlp.down_proj.weight', + 'model.layers.1.mlp.gate.weight', + 'model.layers.1.mlp.experts.0.down_proj.weight', + ] + self.parameters = {name: torch.nn.Parameter(torch.ones(2, 2)) for name in names} + self.batches = [] + self.checkpointing = False + + def train(self): + """Expose the reference model's training-mode interface.""" + return self + + def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs): + """Require the memory-bounded nonreentrant reference policy.""" + assert gradient_checkpointing_kwargs == {'use_reentrant': False} + self.checkpointing = True + + def named_parameters(self): + """Expose stable names for independently selected gradient probes.""" + return self.parameters.items() + + def get_parameter(self, name): + """Look up the same parameter on each logical rank batch.""" + return self.parameters[name] + + def zero_grad(self, set_to_none): + """Discard local gradients before the next reference batch.""" + assert set_to_none + for parameter in self.parameters.values(): + parameter.grad = None + + def __call__(self, input_ids, labels, use_cache): + """Produce input-dependent gradients that differ between rank batches.""" + assert not use_cache and torch.equal(input_ids, labels) + self.batches.append(input_ids.clone()) + loss = sum(parameter.sum() for parameter in self.parameters.values()) * input_ids.float().mean() + return SimpleNamespace(loss=loss) + + +def test_training_reference_averages_distinct_real_profile_rank_batches(reference, monkeypatch): + """Check different rank inputs and float32 gradient averaging rather than replicated tokens.""" + monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: ([[1, 2, 4, 8]], 16)) + model = TrainingReferenceFixture() + result = reference.training_reference(model, 'unused', batch_size=2, seq_len=32, world_size=3) + expected = torch.tensor(result['tokens']).float().mean().item() + assert model.checkpointing + assert len(result['tokens']) == 6 and all(len(row) == 32 for row in result['tokens']) + assert len(model.batches) == 3 and not torch.equal(model.batches[0], model.batches[1]) + assert result['world_size'] == 3 and result['batch_size'] == 2 and result['seq_len'] == 32 + assert result['loss'] == pytest.approx(sum(result['loss_per_rank']) / 3) + for probe in result['gradients'].values(): + assert probe['values'] == pytest.approx([expected] * len(probe['indices'])) + assert all(parameter.grad is None for parameter in model.parameters.values()) + + +def test_targeted_reference_matches_full_backward_without_unneeded_gradients(reference, monkeypatch): + """Preserve full-model derivatives while avoiding storage for unsampled parameter gradients.""" + documents = [[1, 2, 4, 8]] + monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: (documents, 16)) + model = TrainingReferenceFixture() + ignored = torch.nn.Parameter(torch.tensor([2.0])) + model.parameters['model.layers.2.unprobed.weight'] = ignored + tokens = reference.packed_tokens(documents, 16, 32, 6) + expected = {} + for rank in range(2): + model.zero_grad(set_to_none=True) + inputs = torch.tensor(tokens[rank * 3:(rank + 1) * 3]) + model(input_ids=inputs, labels=inputs, use_cache=False).loss.backward() + for name, parameter in model.parameters.items(): + expected[name] = expected.get(name, torch.zeros_like(parameter)) + parameter.grad.detach() / 2 + model.zero_grad(set_to_none=True) + grad = Mock(wraps=torch.autograd.grad) + monkeypatch.setattr(torch.autograd, 'grad', grad) + result = reference.training_reference(model, 'unused', batch_size=3, seq_len=32, world_size=2) + assert grad.call_count == 2 + for call in grad.call_args_list: + assert all(parameter is not ignored for parameter in call[0][1]) + for name, probe in result['gradients'].items(): + assert probe['values'] == pytest.approx(expected[name].flatten()[probe['indices']].tolist()) + assert all(parameter.requires_grad and parameter.grad is None for parameter in model.parameters.values()) + + +@pytest.mark.parametrize('batch_size,seq_len,world_size', [(0, 32, 1), (1, 16, 1), (1, 32, 0)]) +def test_training_reference_rejects_invalid_profile(reference, batch_size, seq_len, world_size): + """Invalid global-batch definitions must fail before any model work.""" + with pytest.raises(ValueError, match='reference profile'): + reference.training_reference(TrainingReferenceFixture(), 'unused', batch_size, seq_len, world_size) + + +@pytest.fixture +def loading_contract(reference, tmp_path, monkeypatch): + """Mock library boundaries while exercising all loader identity checks.""" + if sys.version_info < (3, 10): + pytest.skip('The standalone model runtime requires Python 3.10 or later.') + import importlib.metadata + from superbench.benchmarks.model_benchmarks.deepseek_v2_lite.utils import EXPECTED_CONFIG + + (tmp_path / 'config.json').write_text(json.dumps(dict(EXPECTED_CONFIG, model_type='deepseek_v2'))) + parameter = SimpleNamespace(numel=lambda: reference.PARAMETER_COUNT, requires_grad=True) + model = SimpleNamespace(parameters=lambda: [parameter]) + loading = {key: [] for key in ['missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs']} + loader = Mock(return_value=(model, loading)) + tokenizer = SimpleNamespace(encode=Mock(return_value=[1, 2]), eos_token_id=9) + tokenizer_loader = Mock(return_value=tokenizer) + monkeypatch.setitem( + sys.modules, 'transformers', + SimpleNamespace( + AutoModelForCausalLM=SimpleNamespace(from_pretrained=loader), + AutoTokenizer=SimpleNamespace(from_pretrained=tokenizer_loader), + ) + ) + version = importlib.metadata.version + monkeypatch.setattr( + importlib.metadata, 'version', lambda name: '4.46.3' if name == 'transformers' else version(name) + ) + monkeypatch.setattr(torch.cuda, 'is_available', lambda: True) + return SimpleNamespace( + path=tmp_path, + model=model, + parameter=parameter, + loading=loading, + loader=loader, + tokenizer=tokenizer, + tokenizer_loader=tokenizer_loader, + ) + + +def test_official_loader_contract(reference, loading_contract): + """Require local official-code loading and complete loading diagnostics.""" + item = loading_contract + assert reference.load_model(str(item.path), torch.bfloat16) is item.model + options = item.loader.call_args[1] + assert options['torch_dtype'] == torch.bfloat16 + assert options['local_files_only'] and options['trust_remote_code'] and options['use_safetensors'] + assert options['attn_implementation'] == 'eager' and options['output_loading_info'] + documents, eos = reference.fixed_documents(str(item.path)) + assert len(documents) == len(reference.FIXED_TEXTS) and eos == 9 + assert item.tokenizer_loader.call_args[1]['local_files_only'] + assert item.tokenizer.encode.call_count == len(reference.FIXED_TEXTS) + + +@pytest.mark.parametrize('field', ['missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs']) +def test_loader_diagnostics_cannot_be_ignored(reference, loading_contract, field): + """Partial or incompatible loading must fail before reference execution.""" + loading_contract.loading[field] = ['invalid checkpoint'] + with pytest.raises(RuntimeError, match='checkpoint loading'): + reference.load_model(str(loading_contract.path), torch.bfloat16) + + +@pytest.mark.parametrize('failure', ['count', 'frozen', 'gpu', 'version']) +def test_loader_rejects_wrong_model_or_runtime(reference, loading_contract, monkeypatch, failure): + """Do not replace full-model GPU verification with a smaller or unsupported runtime.""" + item = loading_contract + if failure == 'count': + item.parameter.numel = lambda: 1 + elif failure == 'frozen': + item.parameter.requires_grad = False + elif failure == 'gpu': + monkeypatch.setattr(torch.cuda, 'is_available', lambda: False) + else: + import importlib.metadata + monkeypatch.setattr(importlib.metadata, 'version', lambda name: '0.0') + with pytest.raises(RuntimeError): + reference.load_model(str(item.path), torch.bfloat16) + + +@pytest.mark.parametrize('mode', ['training', 'inference']) +def test_reference_entrypoint_uses_expected_dtype_and_teardown(reference, tmp_path, monkeypatch, mode): + """Exercise orchestration with fake model work, not GPU numerical acceptance.""" + model = Mock() + model.cuda.return_value = model + loader = Mock(return_value=model) + monkeypatch.setattr(reference, 'load_model', loader) + monkeypatch.setattr(reference, 'training_reference', Mock(return_value={'loss': 1.0})) + monkeypatch.setattr(reference, 'inference_reference', Mock(return_value={'comparisons': []})) + monkeypatch.setattr(torch.cuda, 'set_device', Mock()) + monkeypatch.setattr(torch.cuda, 'synchronize', Mock()) + cleanup = Mock() + monkeypatch.setattr(torch.cuda, 'empty_cache', cleanup) + monkeypatch.setattr(torch.backends.cuda.matmul, 'allow_tf32', False) + monkeypatch.setenv('TORCH_ALLOW_TF32_CUBLAS_OVERRIDE', '0') + requests = tmp_path / 'requests.json' + requests.write_text('[]') + output = tmp_path / 'report.json' + monkeypatch.setattr( + sys, 'argv', [ + 'reference', + '--checkpoint', + str(tmp_path), + '--mode', + mode, + '--requests', + str(requests), + '--output', + str(output), + ] + ) + reference.main() + report = json.loads(output.read_text()) + expected = torch.bfloat16 if mode == 'training' else torch.float32 + assert loader.call_args[0][1] == expected + assert report['reference_dtype'] == str(expected) + assert report['correctness_passed'] and report['teardown_complete'] and not report['tf32_allowed'] + cleanup.assert_called_once() + + +def test_worker_environment_reaches_the_worker(tmp_path, monkeypatch): + """Put this package first on the worker search path and pass it through the supervisor.""" + monkeypatch.setenv('PYTHONPATH', 'existing') + expected = os.pathsep.join([str(Path(utils.__file__).resolve().parents[1]), 'existing']) + command = [sys.executable, '-c', 'import os, sys; assert os.environ["PYTHONPATH"] == sys.argv[1]', expected] + utils.run_worker(command, tmp_path / 'worker.log', 5, env=utils.worker_environment()) + + +def test_worker_modules_import_without_superbench(tmp_path): + """Worker interpreters lack SuperBench and site packages, so loading a worker module must need neither.""" + package = Path(utils.__file__).resolve().parent + # The cache helper uses the SuperBench logger and runs only in the adapter process. + names = sorted(path.stem for path in package.glob('*.py') if path.stem not in ('__init__', 'cache')) + assert {'reference', 'utils'} <= set(names) + code = ( + 'import importlib, sys; [importlib.import_module(name) for name in sys.argv[1:]]; ' + 'assert "superbench" not in sys.modules' + ) + modules = ['{}.{}'.format(package.name, name) for name in names] + utils.subprocess.run( + [sys.executable, '-S', '-c', code, *modules], env=utils.worker_environment(), cwd=str(tmp_path), check=True + ) diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_cache.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_cache.py deleted file mode 100644 index 46a2a0b8b..000000000 --- a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_cache.py +++ /dev/null @@ -1,110 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -"""CPU tests for bounded removal of one V2-Lite run's model cache.""" - -import subprocess -import sys -import time -from types import SimpleNamespace -from unittest.mock import Mock - -import pytest - -from superbench.benchmarks.model_benchmarks import deepseek_v2_lite_cache as cleanup - - -def test_removes_only_the_run_cache(tmp_path): - """Delete the downloaded checkpoint while keeping the run's report and logs.""" - cache = tmp_path / 'cache' - (cache / 'checkpoint').mkdir(parents=True) - (cache / 'checkpoint' / 'model-00001-of-000004.safetensors').write_bytes(b'weights') - (tmp_path / 'report.json').write_text('{}') - cleanup.remove_model_cache(cache, time.monotonic() + 30) - assert not cache.exists() - assert (tmp_path / 'report.json').is_file() - - -def test_missing_cache_is_not_an_error(tmp_path): - """A run that failed before downloading has no cache to remove.""" - cleanup.remove_model_cache(tmp_path / 'cache', time.monotonic() + 30) - assert not (tmp_path / 'cache').exists() - - -def test_cleanup_does_not_start_without_budget(tmp_path, monkeypatch): - """Never start an unbounded deletion after the deadline.""" - run = Mock() - monkeypatch.setattr(cleanup.subprocess, 'run', run) - with pytest.raises(TimeoutError, match='No time remains'): - cleanup.remove_model_cache(tmp_path / 'cache', time.monotonic()) - run.assert_not_called() - - -@pytest.mark.parametrize( - 'failure', - [PermissionError('read-only cache'), - subprocess.CalledProcessError(1, ['cleanup'], output='read-only cache')] -) -def test_filesystem_errors_are_logged(tmp_path, monkeypatch, failure): - """Report a cleanup error without treating it as a failed measurement.""" - log_error = Mock() - monkeypatch.setattr(cleanup.subprocess, 'run', Mock(side_effect=failure)) - monkeypatch.setattr(cleanup.logger, 'error', log_error) - cleanup.remove_model_cache(tmp_path / 'cache', time.monotonic() + 30) - log_error.assert_called_once() - assert 'read-only cache' in str(log_error.call_args[0][-1]) - - -@pytest.mark.parametrize('interrupted', [False, True]) -def test_cleanup_timeout_reaps_its_process(tmp_path, monkeypatch, interrupted): - """Stop and reap a real stalled cleanup child on either its deadline or controller interruption.""" - cache = tmp_path / 'cache' - cache.mkdir() - children = [] - popen = subprocess.Popen - - def stalled_cleanup(command, **kwargs): - child = popen([sys.executable, '-c', 'import time; time.sleep(30)'], **kwargs) - children.append(child) - if interrupted: - monkeypatch.setattr(child, 'communicate', Mock(side_effect=TimeoutError('controller interrupted'))) - return child - - monkeypatch.setattr(cleanup.subprocess, 'Popen', stalled_cleanup) - start = time.monotonic() - try: - with pytest.raises(TimeoutError): - cleanup.remove_model_cache(cache, start + 0.25) - assert time.monotonic() - start < 3 - assert len(children) == 1 - assert children[0].returncode is not None - assert cache.is_dir() - finally: - for child in children: - if child.poll() is None: - child.kill() - child.wait(timeout=5) - - -@pytest.mark.parametrize('deadline,budget', [(400.0, cleanup.FAILURE_CLEANUP_GRACE_SECONDS), (1000.0, 500.0)]) -def test_failure_cleanup_uses_the_remaining_budget_or_grace(tmp_path, monkeypatch, deadline, budget): - """Give a failed run's cleanup the rest of its budget, or a fixed grace once that budget is spent.""" - run = Mock() - monkeypatch.setattr(cleanup, 'time', SimpleNamespace(monotonic=lambda: 500.0)) - monkeypatch.setattr(cleanup.subprocess, 'run', run) - cleanup.remove_model_cache_after_failure(tmp_path / 'cache', deadline) - assert run.call_args[1]['timeout'] == budget - - -@pytest.mark.parametrize( - 'failure', [subprocess.TimeoutExpired(['cleanup'], 1), - TimeoutError('Killed by SIGTERM or timeout!')] -) -def test_failure_cleanup_never_raises_a_timeout(tmp_path, monkeypatch, failure): - """Log an unfinished cleanup so that the failed run keeps its original error.""" - log_error = Mock() - monkeypatch.setattr(cleanup.subprocess, 'run', Mock(side_effect=failure)) - monkeypatch.setattr(cleanup.logger, 'error', log_error) - cleanup.remove_model_cache_after_failure(tmp_path / 'cache', time.monotonic()) - log_error.assert_called_once() - assert 'after a failed run' in log_error.call_args[0][0] diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_moe.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_moe.py deleted file mode 100644 index 8a94e7506..000000000 --- a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_moe.py +++ /dev/null @@ -1,148 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -"""CPU mathematical and gradient controls for stable expert dispatch.""" - -import importlib.util -import sys -from pathlib import Path -from types import SimpleNamespace -from typing import TYPE_CHECKING -from unittest.mock import Mock - -import pytest - -if sys.version_info < (3, 10): - pytest.skip('The standalone V2-Lite training runtime requires Python 3.10 or later.', allow_module_level=True) -if TYPE_CHECKING: - import torch -else: - torch = pytest.importorskip('torch') -SPEC = importlib.util.spec_from_file_location( - 'sorted_dispatch', - Path(__file__).resolve().parents[3] / 'superbench/benchmarks/model_benchmarks/deepseek_v2_lite_moe.py' -) -if SPEC is None or SPEC.loader is None: - raise RuntimeError('Cannot load the stable dispatch implementation.') -dispatch = importlib.util.module_from_spec(SPEC) -SPEC.loader.exec_module(dispatch) - - -class Auxiliary(torch.autograd.Function): - """Match the official auxiliary-loss autograd contract.""" - @staticmethod - def forward(ctx, output, loss): - """Return routed activations without changing the forward loss.""" - return output - - @staticmethod - def backward(ctx, gradient): - """Preserve activation gradients and differentiate the auxiliary loss.""" - return gradient, gradient.new_ones(()) - - -AddAuxiliaryLoss = Auxiliary - - -class Gate(torch.nn.Module): - """Provide deterministic routing with an optionally unused expert.""" - def __init__(self, experts, hidden, empty_expert): - """Create trainable router weights for the control.""" - super().__init__() - self.weight = torch.nn.Parameter(torch.randn(experts, hidden)) - self.empty_expert = empty_expert - - def forward(self, values): - """Return top-two routes and a differentiable auxiliary loss.""" - scores = torch.nn.functional.linear(values.reshape(-1, values.shape[-1]), self.weight).softmax(-1) - routed = scores[:, :-1] if self.empty_expert else scores - indices = routed.topk(2, dim=-1).indices - return indices, scores.gather(1, indices), scores.square().mean() - - -class MoE(torch.nn.Module): - """Implement the original Boolean-indexed reference dispatch.""" - def __init__(self, empty_expert, shared): - """Create expert, router and optional shared-expert parameters.""" - super().__init__() - self.num_experts_per_tok = 2 - self.config = SimpleNamespace(n_shared_experts=1 if shared else None) - self.experts = torch.nn.ModuleList( - [torch.nn.Sequential(torch.nn.Linear(4, 6), torch.nn.SiLU(), torch.nn.Linear(6, 4)) for _ in range(4)] - ) - self.gate = Gate(4, 4, empty_expert) - if shared: - self.shared_experts = torch.nn.Linear(4, 4) - - def forward(self, hidden): - """Evaluate every expert in the original route order.""" - shape = hidden.shape - ids, weights, auxiliary = self.gate(hidden) - values = hidden.reshape(-1, shape[-1]).repeat_interleave(2, dim=0) - result = torch.empty_like(values) - for index, expert in enumerate(self.experts): - selected = ids.reshape(-1) == index - result[selected] = expert(values[selected]) - result = (result.view(*weights.shape, -1) * weights.unsqueeze(-1)).sum(1).view(shape) - result = Auxiliary.apply(result, auxiliary) - return result + self.shared_experts(hidden) if self.config.n_shared_experts else result - - -class DeepseekV2MoE(MoE): - """Use the pinned official class contract for installation controls.""" - - ep_size = 1 - - -@pytest.mark.parametrize('empty_expert', [False, True]) -@pytest.mark.parametrize('shared', [False, True]) -def test_sorted_dispatch_preserves_outputs_inputs_parameters_and_auxiliary_gradients(empty_expert, shared): - """Retain outputs and all gradients, including empty and shared experts.""" - torch.manual_seed(1234) - model = MoE(empty_expert, shared).double() - values = torch.randn(2, 3, 4, dtype=torch.float64, requires_grad=True) - original = model(values) - original.square().mean().backward() - expected_input = values.grad.clone() - expected_parameters = {name: parameter.grad.clone() for name, parameter in model.named_parameters()} - expected_output = original.detach().clone() - model.zero_grad(set_to_none=True) - values.grad = None - actual = dispatch.sorted_training_forward(model, values, Auxiliary.apply) - actual.square().mean().backward() - torch.testing.assert_close(actual, expected_output, rtol=1e-12, atol=1e-12) - torch.testing.assert_close(values.grad, expected_input, rtol=1e-12, atol=1e-12) - for name, parameter in model.named_parameters(): - assert parameter.grad is not None - torch.testing.assert_close(parameter.grad, expected_parameters[name], rtol=1e-12, atol=1e-12) - if empty_expert: - assert torch.count_nonzero(model.experts[-1][0].weight.grad).item() == 0 - - -def test_installation_preserves_parameters_and_the_evaluation_path(monkeypatch): - """Only training dispatch changes; evaluation retains the original forward.""" - model = torch.nn.ModuleList([DeepseekV2MoE(False, True).double() for _ in range(26)]) - parameters = [id(parameter) for parameter in model.parameters()] - values = torch.randn(1, 2, 4, dtype=torch.float64) - model.eval() - expected = model[0](values).detach() - assert dispatch.install_sorted_dispatch(model) == 26 - assert [id(parameter) for parameter in model.parameters()] == parameters - replacement = Mock(side_effect=RuntimeError('training dispatch reached')) - monkeypatch.setattr(dispatch, 'sorted_training_forward', replacement) - torch.testing.assert_close(model[0](values), expected) - replacement.assert_not_called() - model.train() - with pytest.raises(RuntimeError, match='training dispatch reached'): - model[0](values) - - -@pytest.mark.parametrize('count,expert_parallelism', [(25, 1), (27, 1), (26, 2)]) -def test_unsupported_layout_is_rejected_before_any_forward_changes(count, expert_parallelism): - """A partial model or expert-parallel layout cannot receive a partial patch.""" - model = torch.nn.ModuleList([DeepseekV2MoE(False, False) for _ in range(count)]) - model[0].ep_size = expert_parallelism - original = [module.forward for module in model] - with pytest.raises(ValueError): - dispatch.install_sorted_dispatch(model) - assert [module.forward for module in model] == original diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_reference.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_reference.py deleted file mode 100644 index 50a88fc02..000000000 --- a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_reference.py +++ /dev/null @@ -1,377 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -"""CPU control-flow checks, not certification of full-model reference numerics.""" - -import importlib.util -import json -import sys -import weakref -from pathlib import Path -from types import SimpleNamespace -from unittest.mock import Mock - -import pytest - -torch = pytest.importorskip('torch') - - -@pytest.fixture -def reference(monkeypatch): - """Load the standalone oracle and redirect only test tensor creation to CPU.""" - directory = Path(__file__).resolve().parents[3] / 'superbench/benchmarks/model_benchmarks' - monkeypatch.syspath_prepend(str(directory)) - spec = importlib.util.spec_from_file_location('v2lite_reference_test', directory / 'deepseek_v2_lite_reference.py') - if spec is None or spec.loader is None: - raise RuntimeError('Cannot load the standalone reference.') - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - tensor = torch.tensor - - def cpu_tensor(data, *args, **kwargs): - if kwargs.get('device') == 'cuda': - kwargs['device'] = 'cpu' - return tensor(data, *args, **kwargs) - - monkeypatch.setattr(torch, 'tensor', cpu_tensor) - return module - - -class ReferenceFixture: - """Expose token-independent logits while checking cached attention shapes.""" - def __init__(self): - """Track cache and full-prefix calls separately.""" - self.calls = [] - - def eval(self): - """Retain the minimal evaluation interface used by the oracle.""" - return self - - def __call__(self, input_ids, attention_mask, past_key_values=None, use_cache=True): - """Require a mask for all past and current positions, including one-token decode.""" - length = input_ids.shape[1] - total = length + (past_key_values or 0) - assert attention_mask.shape == (1, total) - assert attention_mask.all().item() - self.calls.append((length, total, past_key_values, use_cache)) - logits = torch.tensor([0.0, 1.0, 2.0, 3.0]).reshape(1, 1, 4).repeat(1, length, 1) - return SimpleNamespace(logits=logits, past_key_values=total if use_cache else None) - - -def request_fixture(): - """Provide exact fixture probabilities rather than a model-quality claim.""" - probabilities = torch.tensor([0.0, 1.0, 2.0, 3.0]).log_softmax(-1).tolist() - return { - 'prompt_token_ids': [1, 2], - 'token_ids': [3, 3], - 'logprobs': [{str(index): value - for index, value in enumerate(probabilities)} for _ in range(2)], - } - - -def test_cached_decode_mask_covers_full_prefix(reference): - """The second cache call has one input token but a three-position mask.""" - model = ReferenceFixture() - result = reference.inference_reference(model, [request_fixture()]) - assert model.calls == [(2, 2, None, True), (2, 2, None, False), (1, 3, 2, True), (3, 3, None, False)] - assert len(result['comparisons']) == 2 - assert all(row['cache_max_abs_error'] == 0 for row in result['comparisons']) - - -@pytest.mark.parametrize('requests', [[], [{'prompt_token_ids': [], 'token_ids': [], 'logprobs': []}]]) -def test_incomplete_reference_requests_fail(reference, requests): - """Never accept an empty or truncated numerical workload.""" - with pytest.raises(ValueError, match='nonempty|Incomplete'): - reference.inference_reference(ReferenceFixture(), requests) - - -def test_reference_requires_greedy_token_agreement(reference): - """Finite probabilities alone must not certify an incorrect generated token.""" - request = request_fixture() - request['token_ids'][0] = 1 - with pytest.raises(RuntimeError, match='greedy token'): - reference.inference_reference(ReferenceFixture(), [request]) - - -def test_reference_does_not_ignore_probability_mismatch(reference): - """Keep the numerical gate even when all generated tokens are correct.""" - request = request_fixture() - request['logprobs'][0]['3'] += 1.0 - with pytest.raises(AssertionError, match='request 0 step 0'): - reference.inference_reference(ReferenceFixture(), [request]) - - -def test_long_decode_checks_every_engine_token_with_bounded_full_prefix_calls(reference): - """Only full-prefix recomputation is sampled, never engine probability validation.""" - request = request_fixture() - request['token_ids'] *= 4 - request['logprobs'] *= 4 - request['full_prefix_steps'] = [0, 1, 4, 7] - model = ReferenceFixture() - result = reference.inference_reference(model, [request]) - assert len(result['comparisons']) == 8 - assert len(model.calls) == 12 - assert [row['step'] for row in result['comparisons'] if row['full_prefix_checked']] == [0, 1, 4, 7] - assert all(row['cache_max_abs_error'] is None for row in result['comparisons'] if not row['full_prefix_checked']) - request['logprobs'][2] = dict(request['logprobs'][2], **{'3': 0.0}) - with pytest.raises(AssertionError, match='request 0 step 2'): - reference.inference_reference(ReferenceFixture(), [request]) - - -@pytest.mark.parametrize('positions', [[], [0], [1], [0, 0, 1], [1, 0], [0, 2], [False, 1]]) -def test_invalid_full_prefix_sampling_fails(reference, positions): - """Do not accept malformed or first/final-step-incomplete numerical evidence.""" - request = request_fixture() - request['full_prefix_steps'] = positions - with pytest.raises(ValueError, match='reference positions'): - reference.inference_reference(ReferenceFixture(), [request]) - - -class TrainingReferenceFixture: - """Small autograd fixture for global-batch partitioning, not GPU model validation.""" - def __init__(self): - """Create the named parameters required by reference sampling.""" - names = [ - 'model.embed_tokens.weight', - 'model.layers.0.self_attn.q_proj.weight', - 'model.layers.0.self_attn.kv_a_proj_with_mqa.weight', - 'model.layers.0.mlp.down_proj.weight', - 'model.layers.1.mlp.gate.weight', - 'model.layers.1.mlp.experts.0.down_proj.weight', - ] - self.parameters = {name: torch.nn.Parameter(torch.ones(2, 2)) for name in names} - self.batches = [] - self.checkpointing = False - - def train(self): - """Expose the reference model's training-mode interface.""" - return self - - def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs): - """Require the memory-bounded nonreentrant reference policy.""" - assert gradient_checkpointing_kwargs == {'use_reentrant': False} - self.checkpointing = True - - def named_parameters(self): - """Expose stable names for independently selected gradient probes.""" - return self.parameters.items() - - def get_parameter(self, name): - """Look up the same parameter on each logical rank batch.""" - return self.parameters[name] - - def zero_grad(self, set_to_none): - """Discard local gradients before the next reference batch.""" - assert set_to_none - for parameter in self.parameters.values(): - parameter.grad = None - - def __call__(self, input_ids, labels, use_cache): - """Produce input-dependent gradients that differ between rank batches.""" - assert not use_cache and torch.equal(input_ids, labels) - self.batches.append(input_ids.clone()) - loss = sum(parameter.sum() for parameter in self.parameters.values()) * input_ids.float().mean() - return SimpleNamespace(loss=loss) - - -def test_training_reference_averages_distinct_real_profile_rank_batches(reference, monkeypatch): - """Check different rank inputs and float32 gradient averaging rather than replicated tokens.""" - monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: ([[1, 2, 4, 8]], 16)) - model = TrainingReferenceFixture() - result = reference.training_reference(model, 'unused', batch_size=2, seq_len=32, world_size=3) - expected = torch.tensor(result['tokens']).float().mean().item() - assert model.checkpointing - assert len(result['tokens']) == 6 and all(len(row) == 32 for row in result['tokens']) - assert len(model.batches) == 3 and not torch.equal(model.batches[0], model.batches[1]) - assert result['world_size'] == 3 and result['batch_size'] == 2 and result['seq_len'] == 32 - assert result['loss'] == pytest.approx(sum(result['loss_per_rank']) / 3) - for probe in result['gradients'].values(): - assert probe['values'] == pytest.approx([expected] * len(probe['indices'])) - assert all(parameter.grad is None for parameter in model.parameters.values()) - - -def test_reference_preserves_exact_rank_microbatch_shape(reference, monkeypatch): - """Do not introduce BF16 batch-regrouping differences while checking distributed gradients.""" - monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: ([[1, 2, 4, 8]], 16)) - model = TrainingReferenceFixture() - result = reference.training_reference(model, 'unused', batch_size=3, seq_len=32, world_size=2) - assert [batch.shape[0] for batch in model.batches] == [3, 3] - assert all(batch.shape[1] == 32 for batch in model.batches) - assert torch.equal(torch.cat(model.batches), torch.tensor(result['tokens'])) - expected = torch.tensor(result['tokens']).float().mean().item() - assert result['reference_microbatch_size'] == 3 - assert result['loss'] == pytest.approx(expected * 24) - for probe in result['gradients'].values(): - assert probe['values'] == pytest.approx([expected] * len(probe['indices'])) - - -def test_targeted_reference_matches_full_backward_without_unneeded_gradients(reference, monkeypatch): - """Preserve full-model derivatives while avoiding storage for unsampled parameter gradients.""" - documents = [[1, 2, 4, 8]] - monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: (documents, 16)) - model = TrainingReferenceFixture() - ignored = torch.nn.Parameter(torch.tensor([2.0])) - model.parameters['model.layers.2.unprobed.weight'] = ignored - tokens = reference.packed_tokens(documents, 16, 32, 6) - expected = {} - for rank in range(2): - model.zero_grad(set_to_none=True) - inputs = torch.tensor(tokens[rank * 3:(rank + 1) * 3]) - model(input_ids=inputs, labels=inputs, use_cache=False).loss.backward() - for name, parameter in model.parameters.items(): - expected[name] = expected.get(name, torch.zeros_like(parameter)) + parameter.grad.detach() / 2 - model.zero_grad(set_to_none=True) - grad = Mock(wraps=torch.autograd.grad) - monkeypatch.setattr(torch.autograd, 'grad', grad) - result = reference.training_reference(model, 'unused', batch_size=3, seq_len=32, world_size=2) - assert grad.call_count == 2 - for call in grad.call_args_list: - assert all(parameter is not ignored for parameter in call[0][1]) - for name, probe in result['gradients'].items(): - assert probe['values'] == pytest.approx(expected[name].flatten()[probe['indices']].tolist()) - assert all(parameter.requires_grad and parameter.grad is None for parameter in model.parameters.values()) - - -def test_reference_does_not_retain_unused_model_outputs(reference, monkeypatch): - """Release returned vocabulary tensors before accumulating full-model gradients.""" - monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: ([[1, 2, 4, 8]], 16)) - - class OutputFixture(TrainingReferenceFixture): - def __call__(self, input_ids, labels, use_cache): - output = super().__call__(input_ids, labels, use_cache) - logits = torch.ones(8, 8) - self.logits_reference = weakref.ref(logits) - return SimpleNamespace(loss=output.loss, logits=logits) - - model = OutputFixture() - - def check_released(gradient): - assert model.logits_reference() is None - return gradient - - next(iter(model.parameters.values())).register_hook(check_released) - reference.training_reference(model, 'unused', batch_size=2, seq_len=32, world_size=2) - - -@pytest.mark.parametrize('batch_size,seq_len,world_size', [(0, 32, 1), (1, 16, 1), (1, 32, 0)]) -def test_training_reference_rejects_invalid_profile(reference, batch_size, seq_len, world_size): - """Invalid global-batch definitions must fail before any model work.""" - with pytest.raises(ValueError, match='reference profile'): - reference.training_reference(TrainingReferenceFixture(), 'unused', batch_size, seq_len, world_size) - - -@pytest.fixture -def loading_contract(reference, tmp_path, monkeypatch): - """Mock library boundaries while exercising all loader identity checks.""" - if sys.version_info < (3, 10): - pytest.skip('The standalone model runtime requires Python 3.10 or later.') - import importlib.metadata - from deepseek_v2_lite_utils import EXPECTED_CONFIG - - (tmp_path / 'config.json').write_text(json.dumps(dict(EXPECTED_CONFIG, model_type='deepseek_v2'))) - parameter = SimpleNamespace(numel=lambda: reference.PARAMETER_COUNT, requires_grad=True) - model = SimpleNamespace(parameters=lambda: [parameter]) - loading = {key: [] for key in ['missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs']} - loader = Mock(return_value=(model, loading)) - tokenizer = SimpleNamespace(encode=Mock(return_value=[1, 2]), eos_token_id=9) - tokenizer_loader = Mock(return_value=tokenizer) - monkeypatch.setitem( - sys.modules, 'transformers', - SimpleNamespace( - AutoModelForCausalLM=SimpleNamespace(from_pretrained=loader), - AutoTokenizer=SimpleNamespace(from_pretrained=tokenizer_loader), - ) - ) - version = importlib.metadata.version - monkeypatch.setattr( - importlib.metadata, 'version', lambda name: '4.46.3' if name == 'transformers' else version(name) - ) - monkeypatch.setattr(torch.cuda, 'is_available', lambda: True) - return SimpleNamespace( - path=tmp_path, - model=model, - parameter=parameter, - loading=loading, - loader=loader, - tokenizer=tokenizer, - tokenizer_loader=tokenizer_loader, - ) - - -def test_official_loader_contract(reference, loading_contract): - """Require local official-code loading and complete loading diagnostics.""" - item = loading_contract - assert reference.load_model(str(item.path), torch.bfloat16) is item.model - options = item.loader.call_args[1] - assert options['torch_dtype'] == torch.bfloat16 - assert options['local_files_only'] and options['trust_remote_code'] and options['use_safetensors'] - assert options['attn_implementation'] == 'eager' and options['output_loading_info'] - documents, eos = reference.fixed_documents(str(item.path)) - assert len(documents) == len(reference.FIXED_TEXTS) and eos == 9 - assert item.tokenizer_loader.call_args[1]['local_files_only'] - assert item.tokenizer.encode.call_count == len(reference.FIXED_TEXTS) - - -@pytest.mark.parametrize('field', ['missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs']) -def test_loader_diagnostics_cannot_be_ignored(reference, loading_contract, field): - """Partial or incompatible loading must fail before reference execution.""" - loading_contract.loading[field] = ['invalid checkpoint'] - with pytest.raises(RuntimeError, match='checkpoint loading'): - reference.load_model(str(loading_contract.path), torch.bfloat16) - - -@pytest.mark.parametrize('failure', ['count', 'frozen', 'gpu', 'version']) -def test_loader_rejects_wrong_model_or_runtime(reference, loading_contract, monkeypatch, failure): - """Do not replace full-model GPU verification with a smaller or unsupported runtime.""" - item = loading_contract - if failure == 'count': - item.parameter.numel = lambda: 1 - elif failure == 'frozen': - item.parameter.requires_grad = False - elif failure == 'gpu': - monkeypatch.setattr(torch.cuda, 'is_available', lambda: False) - else: - import importlib.metadata - monkeypatch.setattr(importlib.metadata, 'version', lambda name: '0.0') - with pytest.raises(RuntimeError): - reference.load_model(str(item.path), torch.bfloat16) - - -@pytest.mark.parametrize('mode', ['training', 'inference']) -def test_reference_entrypoint_uses_expected_dtype_and_teardown(reference, tmp_path, monkeypatch, mode): - """Exercise orchestration with fake model work, not GPU numerical acceptance.""" - model = Mock() - model.cuda.return_value = model - loader = Mock(return_value=model) - monkeypatch.setattr(reference, 'load_model', loader) - monkeypatch.setattr(reference, 'training_reference', Mock(return_value={'loss': 1.0})) - monkeypatch.setattr(reference, 'inference_reference', Mock(return_value={'comparisons': []})) - monkeypatch.setattr(torch.cuda, 'set_device', Mock()) - monkeypatch.setattr(torch.cuda, 'synchronize', Mock()) - cleanup = Mock() - monkeypatch.setattr(torch.cuda, 'empty_cache', cleanup) - monkeypatch.setattr(torch.backends.cuda.matmul, 'allow_tf32', False) - monkeypatch.setenv('TORCH_ALLOW_TF32_CUBLAS_OVERRIDE', '0') - requests = tmp_path / 'requests.json' - requests.write_text('[]') - output = tmp_path / 'report.json' - monkeypatch.setattr( - sys, 'argv', [ - 'reference', - '--checkpoint', - str(tmp_path), - '--mode', - mode, - '--requests', - str(requests), - '--output', - str(output), - ] - ) - reference.main() - report = json.loads(output.read_text()) - expected = torch.bfloat16 if mode == 'training' else torch.float32 - assert loader.call_args[0][1] == expected - assert report['reference_dtype'] == str(expected) - assert report['correctness_passed'] and report['teardown_complete'] and not report['tf32_allowed'] - cleanup.assert_called_once() diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_training_worker.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_training_worker.py deleted file mode 100644 index 711acf9a4..000000000 --- a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_training_worker.py +++ /dev/null @@ -1,285 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -"""CPU update-verification checks; full-model capacity needs real GPU calibration.""" - -import importlib.util -import json -import sys -import weakref -from contextlib import nullcontext -from pathlib import Path -from types import SimpleNamespace -from typing import TYPE_CHECKING -from unittest.mock import Mock - -import pytest - -if TYPE_CHECKING: - import torch -else: - torch = pytest.importorskip('torch') - - -@pytest.fixture -def worker(monkeypatch): - """Load the worker and replace only GPU/distributed synchronization in CPU tests.""" - directory = Path(__file__).resolve().parents[3] / 'superbench/benchmarks/model_benchmarks' - monkeypatch.syspath_prepend(str(directory)) - spec = importlib.util.spec_from_file_location( - 'v2lite_training_test', directory / 'deepseek_v2_lite_training_worker.py' - ) - if spec is None or spec.loader is None: - raise RuntimeError('Cannot load the standalone training worker.') - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - monkeypatch.setattr(torch.cuda, 'synchronize', lambda: None) - monkeypatch.setattr(torch.distributed, 'all_reduce', lambda tensor: None) - monkeypatch.setattr(torch.distributed, 'get_world_size', lambda: 1) - tensor = torch.tensor - - def cpu_tensor(data, *args, **kwargs): - if kwargs.get('device') == 'cuda': - kwargs['device'] = 'cpu' - return tensor(data, *args, **kwargs) - - monkeypatch.setattr(torch, 'tensor', cpu_tensor) - return module - - -class UpdateFixture(torch.nn.Module): - """Use a small real autograd/optimizer update, not a full-model proxy result.""" - def __init__(self): - """Initialize a nonzero parameter and loss.""" - super().__init__() - self.weight = torch.nn.Parameter(torch.ones(4)) - - def forward(self, input_ids, labels, use_cache): - """Return a scalar differentiable loss without external model dependencies.""" - return SimpleNamespace(loss=self.weight.sum().square()) - - def clip_grad_norm_(self, maximum): - """Expose the FSDP clipping interface using the CPU parameters.""" - return torch.nn.utils.clip_grad_norm_(self.parameters(), maximum) - - -def test_host_snapshot_still_detects_real_update(worker): - """Host snapshots must be independent copies even for the CPU test model.""" - model = UpdateFixture() - optimizer = torch.optim.SGD(model.parameters(), lr=0.1) - elapsed, loss, norm, changed = worker.training_step(model, optimizer, torch.tensor([[1, 2]]), True) - assert elapsed > 0 and loss > 0 and norm > 0 - assert changed == 4 - assert torch.all(model.weight < 1).item() - - -def test_optimizer_noop_is_not_success(worker, monkeypatch): - """Moving validation storage to host must not weaken the actual-update gate.""" - model = UpdateFixture() - optimizer = torch.optim.SGD(model.parameters(), lr=0.1) - monkeypatch.setattr(optimizer, 'step', lambda: None) - with pytest.raises(RuntimeError, match='did not update'): - worker.training_step(model, optimizer, torch.tensor([[1, 2]]), True) - - -def test_unused_returned_logits_are_released_before_backward(worker): - """Do not retain the full vocabulary output while building gradients and optimizer state.""" - class LogitFixture(UpdateFixture): - def forward(self, input_ids, labels, use_cache): - logits = self.weight.repeat(input_ids.shape[0], 1) - self.logits_reference = weakref.ref(logits) - target = torch.zeros(input_ids.shape[0], dtype=torch.long) - return SimpleNamespace(loss=torch.nn.functional.cross_entropy(logits, target), logits=logits) - - model = LogitFixture() - - def check_released(gradient): - assert model.logits_reference() is None - return gradient - - model.weight.register_hook(check_released) - optimizer = torch.optim.SGD(model.parameters(), lr=0.1) - worker.training_step(model, optimizer, torch.tensor([[1, 2]]), True) - - -@pytest.mark.parametrize('invalid', ['missing_loss', 'nonfinite_loss', 'zero_gradient']) -def test_training_step_rejects_invalid_numerics(worker, monkeypatch, invalid): - """Never publish timing for a missing loss, NaN or zero-gradient workload.""" - model = UpdateFixture() - optimizer = torch.optim.SGD(model.parameters(), lr=0.1) - if invalid == 'missing_loss': - monkeypatch.setattr(model, 'forward', lambda **kwargs: SimpleNamespace(loss=None)) - elif invalid == 'nonfinite_loss': - monkeypatch.setattr(model, 'forward', lambda **kwargs: SimpleNamespace(loss=model.weight.sum() * float('nan'))) - else: - monkeypatch.setattr(model, 'clip_grad_norm_', lambda maximum: torch.tensor(0.0)) - with pytest.raises(RuntimeError): - worker.training_step(model, optimizer, torch.tensor([[1, 2]])) - - -@pytest.fixture -def main_driver(worker, tmp_path, monkeypatch): - """Exercise worker orchestration with explicit fake GPU/model boundaries.""" - monkeypatch.setenv('RANK', '0') - monkeypatch.setenv('LOCAL_RANK', '0') - monkeypatch.setenv('WORLD_SIZE', '2') - monkeypatch.setenv('TORCH_ALLOW_TF32_CUBLAS_OVERRIDE', '0') - monkeypatch.setattr(worker.signal, 'signal', Mock()) - monkeypatch.setattr(worker, 'set_cache_environment', Mock()) - monkeypatch.setattr(worker, 'configure_cache', Mock()) - download = Mock(return_value=tmp_path / 'checkpoint') - monkeypatch.setattr(worker, 'download_checkpoint', download) - model = Mock() - model.cuda.return_value = model - loader = Mock(return_value=model) - reference = Mock(return_value={'world_size': 2, 'batch_size': 2, 'seq_len': 64, 'reference_microbatch_size': 2}) - training = Mock(return_value={'world_size': 2, 'step_ms': [1.0, 2.0]}) - monkeypatch.setattr(worker, 'load_model', loader) - monkeypatch.setattr(worker, 'training_reference', reference) - monkeypatch.setattr(worker, 'run_training', training) - monkeypatch.setattr(torch.cuda, 'device_count', lambda: 2) - monkeypatch.setattr(torch.cuda, 'set_device', Mock()) - monkeypatch.setattr(torch.cuda, 'empty_cache', Mock()) - monkeypatch.setattr(torch.cuda, 'get_device_name', lambda index: 'CPU orchestration fixture') - monkeypatch.setattr(torch, 'manual_seed', Mock()) - monkeypatch.setattr(torch.backends.cuda.matmul, 'allow_tf32', False) - initialize = Mock() - control = object() - destroy = Mock() - monkeypatch.setattr(torch.distributed, 'init_process_group', initialize) - monkeypatch.setattr(torch.distributed, 'new_group', Mock(return_value=control)) - monkeypatch.setattr(torch.distributed, 'barrier', Mock()) - monkeypatch.setattr(torch.distributed, 'destroy_process_group', destroy) - output = tmp_path / 'report.json' - argv = [ - 'worker', - '--cache_dir', - str(tmp_path / 'cache'), - '--output', - str(output), - '--num_gpus', - '2', - '--batch_size', - '2', - '--seq_len', - '64', - '--num_steps', - '2', - '--duration', - '60', - ] - monkeypatch.setattr(sys, 'argv', argv) - return SimpleNamespace( - output=output, - argv=argv, - download=download, - loader=loader, - reference=reference, - training=training, - initialize=initialize, - destroy=destroy, - control=control, - ) - - -def test_worker_main_preserves_profile_and_reaps_groups(worker, main_driver): - """A success report follows reference/training completion and both group teardowns.""" - state = main_driver - worker.main() - report = json.loads(state.output.read_text()) - assert report['status'] == 'success' and report['correctness_passed'] and report['teardown_complete'] - assert state.loader.call_args[0][1] == torch.bfloat16 - assert state.reference.call_args[0][2:] == (2, 64, 2) - assert [call[0] for call in state.destroy.call_args_list] == [(state.control, ), ()] - assert state.training.call_args[0][0].seq_len == 64 - assert state.training.call_args[0][0].moe_dispatch == 'official' - assert 0 < report['total_seconds'] < 60 - - -def test_worker_main_forwards_the_explicit_dispatch_selection(worker, main_driver, monkeypatch): - """Select stable dispatch only for measured training, retaining the official reference loader.""" - monkeypatch.setattr(sys, 'argv', main_driver.argv + ['--moe_dispatch', 'stable_sorted']) - worker.main() - assert main_driver.training.call_args[0][0].moe_dispatch == 'stable_sorted' - assert main_driver.loader.call_args[0][1] == torch.bfloat16 - - -def test_nonzero_rank_does_not_download_or_publish(worker, main_driver, monkeypatch): - """Only rank zero owns checkpoint/reference creation and the final report.""" - state = main_driver - monkeypatch.setenv('RANK', '1') - monkeypatch.setenv('LOCAL_RANK', '1') - state.output.with_name('training-reference.json').write_text(json.dumps({'world_size': 2})) - worker.main() - state.download.assert_not_called() - state.loader.assert_not_called() - assert not state.output.exists() - assert state.destroy.call_count == 2 - - -def test_worker_failure_still_destroys_groups(worker, main_driver): - """A failed numerical/training dependency cannot produce success or leak groups.""" - main_driver.training.side_effect = RuntimeError('numerical mismatch') - with pytest.raises(RuntimeError, match='numerical mismatch'): - worker.main() - assert not main_driver.output.exists() - assert main_driver.destroy.call_count == 2 - - -@pytest.mark.parametrize( - 'override', [ - ['--num_gpus', '1'], - ['--batch_size', '0'], - ['--seq_len', '16'], - ['--num_warmup', '-1'], - ['--num_steps', '0'], - ['--duration', '3600'], - ['--learning_rate', 'nan'], - ] -) -def test_worker_rejects_invalid_profile_before_initializing(worker, main_driver, monkeypatch, override): - """Bad profiles must not start collective groups or download weights.""" - monkeypatch.setattr(sys, 'argv', main_driver.argv + override) - with pytest.raises(ValueError): - worker.main() - main_driver.initialize.assert_not_called() - main_driver.download.assert_not_called() - - -@pytest.mark.parametrize('checkpointed', [False, True]) -def test_gradient_probe_mapping_covers_root_and_checkpointed_layers(worker, monkeypatch, checkpointed): - """Exercise actual parameter lookup while replacing only FSDP's collective context.""" - fsdp = pytest.importorskip('torch.distributed.fsdp').FullyShardedDataParallel - from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper - - root = torch.nn.Module() - root.model = torch.nn.Module() - root.model.embed_tokens = torch.nn.Embedding(2, 2) - layer = torch.nn.Linear(2, 2, bias=False) - for parameter in [root.model.embed_tokens.weight, layer.weight]: - parameter.grad = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) - module = checkpoint_wrapper(layer) if checkpointed else layer - root.model.layers = [SimpleNamespace(module=module)] - model = SimpleNamespace(module=root) - monkeypatch.setattr(fsdp, 'summon_full_params', lambda *args, **kwargs: nullcontext()) - reference = { - 'gradients': { - 'model.embed_tokens.weight': { - 'shape': [2, 2], - 'indices': [0, 3], - 'values': [1.0, 4.0] - }, - 'model.layers.0.weight': { - 'shape': [2, 2], - 'indices': [0, 3], - 'values': [1.0, 4.0] - }, - } - } - assert worker.compare_gradients(model, reference) == 0 - reference['gradients']['model.layers.0.weight']['values'][0] = 10.0 - with pytest.raises(AssertionError): - worker.compare_gradients(model, reference) - layer.weight.grad = None - with pytest.raises(RuntimeError, match='gradient'): - worker.compare_gradients(model, reference) diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_utils.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_utils.py deleted file mode 100644 index f6ff3756f..000000000 --- a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_utils.py +++ /dev/null @@ -1,345 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -"""CPU-only tests for the standalone worker contract, without framework imports.""" - -import copy -import ctypes -import hashlib -import importlib.util -import math -import os -import signal -import sys -import time -from pathlib import Path -from types import SimpleNamespace -from unittest.mock import Mock - -import pytest - -WORKER_PATH = Path(__file__).resolve().parents[3] / 'superbench/benchmarks/model_benchmarks/deepseek_v2_lite_utils.py' -SPEC = importlib.util.spec_from_file_location('deepseek_v2_lite_utils_test', WORKER_PATH) -if SPEC is None or SPEC.loader is None: - raise RuntimeError('Cannot load the standalone worker utilities.') -utils = importlib.util.module_from_spec(SPEC) -SPEC.loader.exec_module(utils) - - -def test_checkpoint_identity(): - """Reject architecture proxies and quantization.""" - config = dict(utils.EXPECTED_CONFIG, model_type='deepseek_v2') - utils.validate_config(config) - config['hidden_size'] = 1024 - with pytest.raises(ValueError, match='hidden_size'): - utils.validate_config(config) - config['hidden_size'] = 2048 - config['quantization_config'] = {'quant_method': 'fp8'} - with pytest.raises(ValueError, match='quantized'): - utils.validate_config(config) - assert utils.WEIGHT_BYTES == 31413626576 - - -@pytest.mark.parametrize('field,value', [('seq_aux', False), ('aux_loss_alpha', 0.1), ('attention_dropout', 0.1)]) -def test_fixed_training_semantics_are_part_of_model_identity(field, value): - """Do not silently change the official auxiliary-loss or dropout configuration.""" - config = dict(utils.EXPECTED_CONFIG, model_type='deepseek_v2') - config[field] = value - with pytest.raises(ValueError, match=field): - utils.validate_config(config) - - -def test_packed_text_is_reproducible(): - """Pack actual token inputs with EOS separators, not padding or mock execution.""" - documents = [[1, 2], [3, 4, 5]] - expected = [[1, 2, 9, 3], [4, 5, 9, 1]] - assert utils.packed_tokens(documents, 9, 4, 2) == expected - assert utils.packed_tokens(documents, 9, 4, 2) == expected - assert utils.packed_tokens(documents, 9, 4, 2, offset=1) != expected - - -@pytest.mark.parametrize('documents,length,count', [([], 4, 1), ([[]], 4, 1), ([[True]], 4, 1), ([[1]], 1, 1)]) -def test_invalid_text_inputs(documents, length, count): - """Surface malformed inputs instead of returning an empty batch.""" - with pytest.raises(ValueError): - utils.packed_tokens(documents, 9, length, count) - - -def test_cold_cache_isolated(tmp_path, monkeypatch): - """Reject cache reuse without deleting shared contents.""" - shared = tmp_path / 'shared' - shared.mkdir() - sentinel = shared / 'keep' - sentinel.write_text('unrelated data') - monkeypatch.setenv('HF_HOME', str(shared)) - cache = tmp_path / 'cold' - utils.configure_cache(cache) - assert sentinel.read_text() == 'unrelated data' - assert utils.os.environ['HF_HOME'] == str(cache / 'hf') - assert utils.os.environ['HF_XET_CACHE'] == str(cache / 'xet') - (cache / 'present').touch() - with pytest.raises(ValueError, match='empty'): - utils.configure_cache(cache) - - -@pytest.mark.parametrize('values', [[math.nan], [math.inf], [-1], [0], [True], [], ['1']]) -def test_invalid_metric_series(values): - """Never accept NaNs, sentinels, incomplete samples or success-shaped defaults.""" - with pytest.raises(ValueError): - utils.numeric_series({'step_ms': values}, 'step_ms', 1) - - -def test_report_requires_correctness_and_teardown(): - """Require model identity, not just a successful process exit.""" - report = dict(utils.identity_report(), status='success', correctness_passed=True, teardown_complete=True) - utils.validate_identity(report) - incorrect = copy.deepcopy(report) - incorrect['parameter_count'] = 100 - with pytest.raises(ValueError, match='contract'): - utils.validate_identity(incorrect) - report['correctness_passed'] = False - with pytest.raises(ValueError, match='Correctness'): - utils.validate_identity(report) - - -@pytest.mark.parametrize('length', [1, 512, 209715200, 15706484224]) -def test_large_tensor_probe_indices(length): - """FP32-rounded endpoints must never index beyond a real full-model tensor.""" - indices = utils.uniform_indices(length) - assert len(indices) == 256 - assert indices[0] == 0 and indices[-1] == length - 1 - assert all(0 <= index < length for index in indices) - - -def test_atomic_json_rejects_nonfinite_values(tmp_path): - """A malformed report must not replace a complete report.""" - path = tmp_path / 'report.json' - utils.write_json(path, {'value': 1}) - with pytest.raises(ValueError): - utils.write_json(path, {'value': math.nan}) - assert utils.read_json(path) == {'value': 1} - path.write_text('{"value": NaN}') - with pytest.raises(ValueError, match='Nonfinite'): - utils.read_json(path) - - -def test_worker_failure_is_explicit(tmp_path): - """Reject nonzero exit codes even if the worker writes a result-like message.""" - with pytest.raises(RuntimeError, match='code 7'): - utils.run_worker([sys.executable, '-c', 'print("success"); raise SystemExit(7)'], tmp_path / 'worker.log', 5) - assert 'success' in (tmp_path / 'worker.log').read_text() - - -def test_timeout_reaps_worker(tmp_path): - """A timeout must terminate the created process rather than leave a worker.""" - pid_file = tmp_path / 'pid' - command = [ - sys.executable, - '-c', - 'import os,time; from pathlib import Path; Path({!r}).write_text(str(os.getpid())); time.sleep(60)'.format( - str(pid_file) - ), - ] - with pytest.raises(TimeoutError, match='deadline'): - utils.run_worker(command, tmp_path / 'worker.log', 1) - pid = int(pid_file.read_text()) - with pytest.raises(ProcessLookupError): - utils.os.kill(pid, 0) - - -def test_worker_argv_is_not_a_shell(tmp_path): - """Preserve argument boundaries rather than reinterpret shell metacharacters.""" - output = tmp_path / 'argv' - value = 'a=b; this is one value' - utils.run_worker( - [ - sys.executable, '-c', 'import sys; from pathlib import Path; Path(sys.argv[1]).write_text(sys.argv[2])', - str(output), value - ], tmp_path / 'worker.log', 5 - ) - assert output.read_text() == value - - -def test_success_with_live_child_is_rejected(tmp_path): - """A leader's exit code zero is insufficient when its child remains alive.""" - command = [ - sys.executable, - '-c', - 'import subprocess,sys; subprocess.Popen([sys.executable,"-c","import time; time.sleep(60)"])', - ] - with pytest.raises(RuntimeError, match='descendant processes'): - utils.run_worker(command, tmp_path / 'worker.log', 5) - - -@pytest.mark.parametrize('launcher_exits', [False, True]) -def test_separate_session_child_is_reaped(tmp_path, launcher_exits): - """Own escaped rank sessions even when their launcher exits or ignores termination.""" - pid_file = tmp_path / 'rank.pid' - rank = ( - 'import os,signal,time; from pathlib import Path; ' - 'signal.signal(signal.SIGTERM, signal.SIG_IGN); ' - 'Path({!r}).write_text(str(os.getpid())); time.sleep(60)' - ).format(str(pid_file)) - launcher = ( - 'import signal,subprocess,sys,time; from pathlib import Path; ' - 'signal.signal(signal.SIGTERM, signal.SIG_IGN); ' - 'subprocess.Popen([sys.executable, "-c", {!r}], start_new_session=True); ' - 'ready=Path({!r})\n' - 'while not ready.exists(): time.sleep(0.01)\n' - '{}' - ).format(rank, str(pid_file), 'sys.exit(0)' if launcher_exits else 'time.sleep(60)') - try: - expected = RuntimeError if launcher_exits else TimeoutError - with pytest.raises(expected): - utils.run_worker([sys.executable, '-c', launcher], tmp_path / 'worker.log', 5 if launcher_exits else 1) - pid = int(pid_file.read_text()) - with pytest.raises(ProcessLookupError): - os.kill(pid, 0) - finally: - if pid_file.exists(): - pid = int(pid_file.read_text()) - try: - os.kill(pid, signal.SIGKILL) - except ProcessLookupError: - pass - - -def test_worker_signal_does_not_kill_unrelated_process(tmp_path): - """Timeout cleanup must be scoped to the supervised job, not the controller's children.""" - unrelated = utils.subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)']) - try: - with pytest.raises(TimeoutError): - utils.run_worker([sys.executable, '-c', 'import time; time.sleep(60)'], tmp_path / 'worker.log', 0.2) - assert unrelated.poll() is None - finally: - unrelated.terminate() - unrelated.wait(timeout=5) - - -def test_controller_death_reaps_owned_worker(tmp_path): - """A killed controller must not leave its independently supervised job alive.""" - pid_file = tmp_path / 'worker.pid' - worker = ('import os,time; from pathlib import Path; ' - 'Path({!r}).write_text(str(os.getpid())); time.sleep(60)').format(str(pid_file)) - controller = ( - 'import sys; from pathlib import Path; sys.path.insert(0, {!r}); ' - 'from deepseek_v2_lite_utils import run_worker; ' - 'run_worker([sys.executable, "-c", {!r}], Path({!r}), 60)' - ).format(str(WORKER_PATH.parent), worker, str(tmp_path / 'worker.log')) - process = utils.subprocess.Popen([sys.executable, '-c', controller]) - try: - deadline = time.monotonic() + 5 - while not pid_file.exists() and time.monotonic() < deadline: - time.sleep(0.02) - assert pid_file.exists() - pid = int(pid_file.read_text()) - process.kill() - process.wait(timeout=5) - deadline = time.monotonic() + 15 - while time.monotonic() < deadline: - try: - os.kill(pid, 0) - except ProcessLookupError: - break - time.sleep(0.02) - else: - pytest.fail('The worker survived its controller.') - finally: - if process.poll() is None: - process.kill() - process.wait(timeout=5) - if pid_file.exists(): - try: - os.kill(int(pid_file.read_text()), signal.SIGKILL) - except ProcessLookupError: - pass - - -@pytest.fixture -def checkpoint_files(tmp_path, monkeypatch): - """Create small real files to test the checkpoint integrity contract.""" - root = tmp_path / 'checkpoint' - root.mkdir() - contents = b'CPU checkpoint integrity fixture' - shard = root / 'weights.safetensors' - shard.write_bytes(contents) - monkeypatch.setattr(utils, 'WEIGHT_FILES', { - shard.name: (len(contents), hashlib.sha256(contents).hexdigest()), - }) - utils.write_json(root / 'config.json', dict(utils.EXPECTED_CONFIG, model_type='deepseek_v2')) - utils.write_json(root / 'model.safetensors.index.json', {'weight_map': {'fixture.weight': shard.name}}) - return root, shard - - -def test_checkpoint_files_are_verified(checkpoint_files): - """Check file sizes, index membership and SHA256 without claiming model execution.""" - root, _ = checkpoint_files - utils.verify_checkpoint(root) - - -@pytest.mark.parametrize('failure', ['missing', 'size', 'hash', 'index']) -def test_invalid_checkpoint_files_fail(checkpoint_files, failure): - """Corrupted, missing or misindexed shards must never become a valid checkpoint.""" - root, shard = checkpoint_files - if failure == 'missing': - shard.unlink() - elif failure == 'size': - shard.write_bytes(b'short') - elif failure == 'hash': - shard.write_bytes(b'x' * shard.stat().st_size) - else: - utils.write_json(root / 'model.safetensors.index.json', {'weight_map': {'fixture.weight': 'other'}}) - with pytest.raises(ValueError): - utils.verify_checkpoint(root) - - -def test_download_uses_pinned_public_identity_and_then_verifies(checkpoint_files, monkeypatch): - """Disable implicit credentials and require the downloaded shard contract.""" - root, shard = checkpoint_files - download = Mock() - monkeypatch.setitem(sys.modules, 'huggingface_hub', SimpleNamespace(snapshot_download=download)) - assert utils.download_checkpoint(root.parent) == root - arguments = download.call_args[1] - assert arguments['repo_id'] == utils.MODEL_ID - assert arguments['revision'] == utils.REVISION - assert arguments['token'] is False - assert arguments['local_dir'] == str(root) - assert shard.name in arguments['allow_patterns'] - - -@pytest.mark.parametrize('length,count', [(0, 2), (1, 1)]) -def test_invalid_probe_dimensions_fail(length, count): - """Reject undefined probe endpoints instead of silently selecting positions.""" - with pytest.raises(ValueError, match='tensor length'): - utils.uniform_indices(length, count) - - -@pytest.mark.parametrize('timeout', [0, -1, float('nan')]) -def test_invalid_worker_deadline_fails_before_launch(tmp_path, timeout): - """A nonfinite or expired budget must not start a worker.""" - with pytest.raises(TimeoutError): - utils.run_worker([sys.executable, '-c', 'pass'], tmp_path / 'worker.log', timeout) - - -def test_empty_worker_command_fails(tmp_path): - """Do not launch a supervisor with no defined workload.""" - with pytest.raises(ValueError, match='command'): - utils.run_worker([], tmp_path / 'worker.log', 1) - - -def test_worker_interrupt_is_failure(): - """A termination request must unwind the worker's normal success path.""" - with pytest.raises(TimeoutError, match='interrupted'): - utils.interrupt_worker(signal.SIGTERM, None) - - -def test_supervisor_requires_kernel_ownership_support(monkeypatch): - """Fail before spawning when kernel ownership setup is unavailable.""" - monkeypatch.setattr(utils.signal, 'signal', Mock()) - monkeypatch.setattr(ctypes, 'CDLL', lambda *args, **kwargs: SimpleNamespace(prctl=lambda *args: -1)) - monkeypatch.setattr(ctypes, 'get_errno', lambda: 13) - spawn = Mock() - monkeypatch.setattr(utils.subprocess, 'Popen', spawn) - with pytest.raises(OSError): - utils.supervise_worker([sys.executable, '-c', 'pass'], 1, os.getppid()) - spawn.assert_not_called() diff --git a/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py b/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py index 80e8e61a9..7a0c92939 100644 --- a/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py +++ b/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py @@ -1,21 +1,36 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -"""CPU adapter tests; complete model correctness is checked by the GPU worker.""" +"""CPU tests for the DeepSeek-V2-Lite training benchmark: adapter, FSDP worker and MoE dispatch.""" +import json +import os import subprocess +import sys +from contextlib import nullcontext from pathlib import Path from types import SimpleNamespace +from typing import TYPE_CHECKING from unittest.mock import Mock import pytest from superbench.benchmarks import BenchmarkType, ReturnCode -from superbench.benchmarks.model_benchmarks import deepseek_v2_lite_cache as cache_cleanup from superbench.benchmarks.model_benchmarks import pytorch_deepseek_v2_lite as adapter -from superbench.benchmarks.model_benchmarks.deepseek_v2_lite_utils import identity_report, write_json +from superbench.benchmarks.model_benchmarks.deepseek_v2_lite import cache as cache_cleanup, moe, training_worker +from superbench.benchmarks.model_benchmarks.deepseek_v2_lite.utils import identity_report, write_json +if TYPE_CHECKING: + import torch +else: + torch = pytest.importorskip('torch') +requires_python_310 = pytest.mark.skipif( + sys.version_info < (3, 10), reason='The V2-Lite training runtime requires Python 3.10 or later.' +) + + +# Adapter. @pytest.fixture def benchmark(tmp_path, monkeypatch): """Use an isolated cache root and a single local launcher.""" @@ -27,8 +42,10 @@ def benchmark(tmp_path, monkeypatch): ) -def successful_worker(command, log, timeout): +def successful_worker(command, log, timeout, env): """Supply a worker-contract fixture, not a claim of model execution.""" + assert command[command.index('--module') + 1] == 'deepseek_v2_lite.training_worker' + assert env['PYTHONPATH'].split(os.pathsep)[0] == str(Path(adapter.__file__).resolve().parent) output = Path(command[command.index('--output') + 1]) dispatch = command[command.index('--moe_dispatch') + 1] report = dict( @@ -100,7 +117,7 @@ def test_duplicate_launcher_is_rejected(benchmark, monkeypatch, world_size): def test_download_or_worker_failure_is_not_success(benchmark, monkeypatch): """Reject a failed subprocess rather than inventing throughput.""" - def failed_worker(command, log, timeout): + def failed_worker(command, log, timeout, env): raise RuntimeError('download failed') monkeypatch.setattr(adapter, 'run_worker', failed_worker) @@ -111,7 +128,7 @@ def failed_worker(command, log, timeout): def test_timeout_is_failure(benchmark, monkeypatch): """Finishing through watchdog termination does not meet the time limit.""" - def timed_out_worker(command, log, timeout): + def timed_out_worker(command, log, timeout, env): raise TimeoutError('whole job deadline') monkeypatch.setattr(adapter, 'run_worker', timed_out_worker) @@ -124,7 +141,7 @@ def test_model_cache_is_removed_after_every_run(benchmark, monkeypatch, outcome) """Delete the per-run checkpoint cache on every exit path while keeping reports and logs.""" jobs = [] - def worker(command, log, timeout): + def worker(command, log, timeout, env): cache = Path(command[command.index('--cache_dir') + 1]) (cache / 'checkpoint').mkdir(parents=True) (cache / 'checkpoint' / 'model-00001-of-000004.safetensors').write_bytes(b'weights') @@ -134,7 +151,7 @@ def worker(command, log, timeout): raise RuntimeError('worker failed') if outcome == 'timeout': raise TimeoutError('whole job deadline') - successful_worker(command, log, timeout) + successful_worker(command, log, timeout, env) monkeypatch.setattr(adapter, 'run_worker', worker) assert benchmark.run() is (outcome == 'success') @@ -143,57 +160,16 @@ def worker(command, log, timeout): assert (jobs[0] / 'report.json').is_file() is (outcome == 'success') -@pytest.mark.parametrize( - 'failure', - [PermissionError('read-only cache'), - subprocess.CalledProcessError(1, ['cleanup'], output='read-only cache')] -) -def test_cache_removal_failure_keeps_a_valid_measurement(benchmark, monkeypatch, failure): - """Log a cleanup error without discarding metrics that were already validated.""" - caches = [] - log_error = Mock() - - def worker(command, log, timeout): - cache = Path(command[command.index('--cache_dir') + 1]) - cache.mkdir(parents=True) - caches.append(cache) - successful_worker(command, log, timeout) - - monkeypatch.setattr(adapter, 'run_worker', worker) - monkeypatch.setattr(cache_cleanup.subprocess, 'run', Mock(side_effect=failure)) - monkeypatch.setattr(adapter.logger, 'error', log_error) - assert benchmark.run() - assert benchmark.return_code == ReturnCode.SUCCESS - assert caches[0].is_dir() - log_error.assert_called_once() - assert 'read-only cache' in str(log_error.call_args[0][-1]) - - -def test_sigterm_during_cache_removal_still_reports_timeout(benchmark, monkeypatch): - """A runner timeout during cleanup must not be reported as a completed run.""" - def worker(command, log, timeout): - Path(command[command.index('--cache_dir') + 1]).mkdir(parents=True) - successful_worker(command, log, timeout) - - cleanup = Mock(side_effect=TimeoutError('Killed by SIGTERM or timeout!')) - monkeypatch.setattr(adapter, 'run_worker', worker) - monkeypatch.setattr(cache_cleanup.subprocess, 'run', cleanup) - assert not benchmark.run() - assert benchmark.return_code == ReturnCode.KILLED_BY_TIMEOUT - assert 'end_to_end_seconds' not in benchmark.result - assert cleanup.call_count == 2 - - @pytest.mark.parametrize('cleanup_seconds', [7, 50, 70]) def test_cache_cleanup_counts_toward_the_job_deadline(benchmark, monkeypatch, cleanup_seconds): """Include cleanup in elapsed time and reject the exact deadline as well as an overrun.""" clock = [100.0] run_cleanup = subprocess.run - def worker(command, log, timeout): + def worker(command, log, timeout, env): assert timeout == 40 Path(command[command.index('--cache_dir') + 1]).mkdir(parents=True) - successful_worker(command, log, timeout) + successful_worker(command, log, timeout, env) clock[0] += 10 def cleanup(command, **kwargs): @@ -218,36 +194,6 @@ def cleanup(command, **kwargs): assert 'bf16_train_tokens_per_second' not in benchmark.result -def test_cleanup_after_the_deadline_uses_the_failure_grace(benchmark, monkeypatch): - """Fail an overrun job, then still remove its cache within the bounded failure grace.""" - clock = [100.0] - timeouts = [] - caches = [] - run_cleanup = subprocess.run - - def worker(command, log, timeout): - cache = Path(command[command.index('--cache_dir') + 1]) - cache.mkdir(parents=True) - caches.append(cache) - successful_worker(command, log, timeout) - clock[0] += 60 - - def cleanup(command, **kwargs): - timeouts.append(kwargs['timeout']) - return run_cleanup(command, **kwargs) - - fake_time = SimpleNamespace(monotonic=lambda: clock[0]) - monkeypatch.setattr(adapter, 'time', fake_time) - monkeypatch.setattr(cache_cleanup, 'time', fake_time) - monkeypatch.setattr(adapter, 'run_worker', worker) - monkeypatch.setattr(cache_cleanup.subprocess, 'run', cleanup) - assert not benchmark.run() - assert benchmark.return_code == ReturnCode.KILLED_BY_TIMEOUT - assert 'end_to_end_seconds' not in benchmark.result - assert timeouts == [cache_cleanup.FAILURE_CLEANUP_GRACE_SECONDS] - assert not caches[0].exists() - - @pytest.mark.parametrize( 'failure,code', [ (RuntimeError('worker failed'), ReturnCode.RUNTIME_EXCEPTION_ERROR), @@ -258,7 +204,7 @@ def test_unfinished_failure_cleanup_keeps_the_original_error(benchmark, monkeypa """Report the worker failure rather than a later cleanup timeout, and log both.""" log_error = Mock() - def worker(command, log, timeout): + def worker(command, log, timeout, env): Path(command[command.index('--cache_dir') + 1]).mkdir(parents=True) raise failure @@ -281,8 +227,8 @@ def worker(command, log, timeout): ) def test_invalid_worker_report(benchmark, monkeypatch, field, value): """Check required metric thresholds and shapes, not only process exit zero.""" - def invalid_worker(command, log, timeout): - successful_worker(command, log, timeout) + def invalid_worker(command, log, timeout, env): + successful_worker(command, log, timeout, env) output = Path(command[command.index('--output') + 1]) report = adapter.read_json(output) report[field] = value @@ -301,6 +247,7 @@ def test_python_and_path_remain_separate_arguments(benchmark): assert command[0] == '/path with spaces/python' assert command[command.index('--cache_dir') + 1] == '/cache with spaces/job/cache' assert '--nproc_per_node=4' in command + assert command[command.index('--module') + 1] == 'deepseek_v2_lite.training_worker' assert command[command.index('--moe_dispatch') + 1] == 'official' @@ -312,10 +259,370 @@ def test_opt_in_dispatch_reaches_the_worker_and_requires_matching_evidence(bench ) commands = [] - def worker(command, log, timeout): + def worker(command, log, timeout, env): commands.append(command) - successful_worker(command, log, timeout) + successful_worker(command, log, timeout, env) monkeypatch.setattr(adapter, 'run_worker', worker) assert selected.run() assert commands[0][commands[0].index('--moe_dispatch') + 1] == 'stable_sorted' + + +# FSDP worker. +@pytest.fixture +def worker(monkeypatch): + """Return the worker and replace only GPU/distributed synchronization in CPU tests.""" + monkeypatch.setattr(torch.cuda, 'synchronize', lambda: None) + monkeypatch.setattr(torch.distributed, 'all_reduce', lambda tensor: None) + monkeypatch.setattr(torch.distributed, 'get_world_size', lambda: 1) + tensor = torch.tensor + + def cpu_tensor(data, *args, **kwargs): + if kwargs.get('device') == 'cuda': + kwargs['device'] = 'cpu' + return tensor(data, *args, **kwargs) + + monkeypatch.setattr(torch, 'tensor', cpu_tensor) + return training_worker + + +class UpdateFixture(torch.nn.Module): + """Use a small real autograd/optimizer update, not a full-model proxy result.""" + def __init__(self): + """Initialize a nonzero parameter and loss.""" + super().__init__() + self.weight = torch.nn.Parameter(torch.ones(4)) + + def forward(self, input_ids, labels, use_cache): + """Return a scalar differentiable loss without external model dependencies.""" + return SimpleNamespace(loss=self.weight.sum().square()) + + def clip_grad_norm_(self, maximum): + """Expose the FSDP clipping interface using the CPU parameters.""" + return torch.nn.utils.clip_grad_norm_(self.parameters(), maximum) + + +def test_host_snapshot_still_detects_real_update(worker): + """Host snapshots must be independent copies even for the CPU test model.""" + model = UpdateFixture() + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + elapsed, loss, norm, changed = worker.training_step(model, optimizer, torch.tensor([[1, 2]]), True) + assert elapsed > 0 and loss > 0 and norm > 0 + assert changed == 4 + assert torch.all(model.weight < 1).item() + + +def test_optimizer_noop_is_not_success(worker, monkeypatch): + """Moving validation storage to host must not weaken the actual-update gate.""" + model = UpdateFixture() + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + monkeypatch.setattr(optimizer, 'step', lambda: None) + with pytest.raises(RuntimeError, match='did not update'): + worker.training_step(model, optimizer, torch.tensor([[1, 2]]), True) + + +@pytest.mark.parametrize('invalid', ['missing_loss', 'nonfinite_loss', 'zero_gradient']) +def test_training_step_rejects_invalid_numerics(worker, monkeypatch, invalid): + """Never publish timing for a missing loss, NaN or zero-gradient workload.""" + model = UpdateFixture() + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + if invalid == 'missing_loss': + monkeypatch.setattr(model, 'forward', lambda **kwargs: SimpleNamespace(loss=None)) + elif invalid == 'nonfinite_loss': + monkeypatch.setattr(model, 'forward', lambda **kwargs: SimpleNamespace(loss=model.weight.sum() * float('nan'))) + else: + monkeypatch.setattr(model, 'clip_grad_norm_', lambda maximum: torch.tensor(0.0)) + with pytest.raises(RuntimeError): + worker.training_step(model, optimizer, torch.tensor([[1, 2]])) + + +@pytest.fixture +def main_driver(worker, tmp_path, monkeypatch): + """Exercise worker orchestration with explicit fake GPU/model boundaries.""" + monkeypatch.setenv('RANK', '0') + monkeypatch.setenv('LOCAL_RANK', '0') + monkeypatch.setenv('WORLD_SIZE', '2') + monkeypatch.setenv('TORCH_ALLOW_TF32_CUBLAS_OVERRIDE', '0') + monkeypatch.setattr(worker.signal, 'signal', Mock()) + monkeypatch.setattr(worker, 'set_cache_environment', Mock()) + monkeypatch.setattr(worker, 'configure_cache', Mock()) + download = Mock(return_value=tmp_path / 'checkpoint') + monkeypatch.setattr(worker, 'download_checkpoint', download) + model = Mock() + model.cuda.return_value = model + loader = Mock(return_value=model) + reference = Mock(return_value={'world_size': 2, 'batch_size': 2, 'seq_len': 64, 'reference_microbatch_size': 2}) + training = Mock(return_value={'world_size': 2, 'step_ms': [1.0, 2.0]}) + monkeypatch.setattr(worker, 'load_model', loader) + monkeypatch.setattr(worker, 'training_reference', reference) + monkeypatch.setattr(worker, 'run_training', training) + monkeypatch.setattr(torch.cuda, 'device_count', lambda: 2) + monkeypatch.setattr(torch.cuda, 'set_device', Mock()) + monkeypatch.setattr(torch.cuda, 'empty_cache', Mock()) + monkeypatch.setattr(torch.cuda, 'get_device_name', lambda index: 'CPU orchestration fixture') + monkeypatch.setattr(torch, 'manual_seed', Mock()) + monkeypatch.setattr(torch.backends.cuda.matmul, 'allow_tf32', False) + initialize = Mock() + control = object() + destroy = Mock() + monkeypatch.setattr(torch.distributed, 'init_process_group', initialize) + monkeypatch.setattr(torch.distributed, 'new_group', Mock(return_value=control)) + monkeypatch.setattr(torch.distributed, 'barrier', Mock()) + monkeypatch.setattr(torch.distributed, 'destroy_process_group', destroy) + output = tmp_path / 'report.json' + argv = [ + 'worker', + '--cache_dir', + str(tmp_path / 'cache'), + '--output', + str(output), + '--num_gpus', + '2', + '--batch_size', + '2', + '--seq_len', + '64', + '--num_steps', + '2', + '--duration', + '60', + ] + monkeypatch.setattr(sys, 'argv', argv) + return SimpleNamespace( + output=output, + argv=argv, + download=download, + loader=loader, + reference=reference, + training=training, + initialize=initialize, + destroy=destroy, + control=control, + ) + + +def test_worker_main_preserves_profile_and_reaps_groups(worker, main_driver): + """A success report follows reference/training completion and both group teardowns.""" + state = main_driver + worker.main() + report = json.loads(state.output.read_text()) + assert report['status'] == 'success' and report['correctness_passed'] and report['teardown_complete'] + assert state.loader.call_args[0][1] == torch.bfloat16 + assert state.reference.call_args[0][2:] == (2, 64, 2) + assert [call[0] for call in state.destroy.call_args_list] == [(state.control, ), ()] + assert state.training.call_args[0][0].seq_len == 64 + assert state.training.call_args[0][0].moe_dispatch == 'official' + assert 0 < report['total_seconds'] < 60 + + +def test_worker_main_forwards_the_explicit_dispatch_selection(worker, main_driver, monkeypatch): + """Select stable dispatch only for measured training, retaining the official reference loader.""" + monkeypatch.setattr(sys, 'argv', main_driver.argv + ['--moe_dispatch', 'stable_sorted']) + worker.main() + assert main_driver.training.call_args[0][0].moe_dispatch == 'stable_sorted' + assert main_driver.loader.call_args[0][1] == torch.bfloat16 + + +def test_nonzero_rank_does_not_download_or_publish(worker, main_driver, monkeypatch): + """Only rank zero owns checkpoint/reference creation and the final report.""" + state = main_driver + monkeypatch.setenv('RANK', '1') + monkeypatch.setenv('LOCAL_RANK', '1') + state.output.with_name('training-reference.json').write_text(json.dumps({'world_size': 2})) + worker.main() + state.download.assert_not_called() + state.loader.assert_not_called() + assert not state.output.exists() + assert state.destroy.call_count == 2 + + +def test_worker_failure_still_destroys_groups(worker, main_driver): + """A failed numerical/training dependency cannot produce success or leak groups.""" + main_driver.training.side_effect = RuntimeError('numerical mismatch') + with pytest.raises(RuntimeError, match='numerical mismatch'): + worker.main() + assert not main_driver.output.exists() + assert main_driver.destroy.call_count == 2 + + +@pytest.mark.parametrize( + 'override', [ + ['--num_gpus', '1'], + ['--batch_size', '0'], + ['--seq_len', '16'], + ['--num_warmup', '-1'], + ['--num_steps', '0'], + ['--duration', '3600'], + ['--learning_rate', 'nan'], + ] +) +def test_worker_rejects_invalid_profile_before_initializing(worker, main_driver, monkeypatch, override): + """Bad profiles must not start collective groups or download weights.""" + monkeypatch.setattr(sys, 'argv', main_driver.argv + override) + with pytest.raises(ValueError): + worker.main() + main_driver.initialize.assert_not_called() + main_driver.download.assert_not_called() + + +@pytest.mark.parametrize('checkpointed', [False, True]) +def test_gradient_probe_mapping_covers_root_and_checkpointed_layers(worker, monkeypatch, checkpointed): + """Exercise actual parameter lookup while replacing only FSDP's collective context.""" + fsdp = pytest.importorskip('torch.distributed.fsdp').FullyShardedDataParallel + from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper + + root = torch.nn.Module() + root.model = torch.nn.Module() + root.model.embed_tokens = torch.nn.Embedding(2, 2) + layer = torch.nn.Linear(2, 2, bias=False) + for parameter in [root.model.embed_tokens.weight, layer.weight]: + parameter.grad = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + module = checkpoint_wrapper(layer) if checkpointed else layer + root.model.layers = [SimpleNamespace(module=module)] + model = SimpleNamespace(module=root) + monkeypatch.setattr(fsdp, 'summon_full_params', lambda *args, **kwargs: nullcontext()) + reference = { + 'gradients': { + 'model.embed_tokens.weight': { + 'shape': [2, 2], + 'indices': [0, 3], + 'values': [1.0, 4.0] + }, + 'model.layers.0.weight': { + 'shape': [2, 2], + 'indices': [0, 3], + 'values': [1.0, 4.0] + }, + } + } + assert worker.compare_gradients(model, reference) == 0 + reference['gradients']['model.layers.0.weight']['values'][0] = 10.0 + with pytest.raises(AssertionError): + worker.compare_gradients(model, reference) + layer.weight.grad = None + with pytest.raises(RuntimeError, match='gradient'): + worker.compare_gradients(model, reference) + + +# Stable MoE dispatch. +class Auxiliary(torch.autograd.Function): + """Match the official auxiliary-loss autograd contract.""" + @staticmethod + def forward(ctx, output, loss): + """Return routed activations without changing the forward loss.""" + return output + + @staticmethod + def backward(ctx, gradient): + """Preserve activation gradients and differentiate the auxiliary loss.""" + return gradient, gradient.new_ones(()) + + +AddAuxiliaryLoss = Auxiliary + + +class Gate(torch.nn.Module): + """Provide deterministic routing with an optionally unused expert.""" + def __init__(self, experts, hidden, empty_expert): + """Create trainable router weights for the control.""" + super().__init__() + self.weight = torch.nn.Parameter(torch.randn(experts, hidden)) + self.empty_expert = empty_expert + + def forward(self, values): + """Return top-two routes and a differentiable auxiliary loss.""" + scores = torch.nn.functional.linear(values.reshape(-1, values.shape[-1]), self.weight).softmax(-1) + routed = scores[:, :-1] if self.empty_expert else scores + indices = routed.topk(2, dim=-1).indices + return indices, scores.gather(1, indices), scores.square().mean() + + +class MoE(torch.nn.Module): + """Implement the original Boolean-indexed reference dispatch.""" + def __init__(self, empty_expert, shared): + """Create expert, router and optional shared-expert parameters.""" + super().__init__() + self.num_experts_per_tok = 2 + self.config = SimpleNamespace(n_shared_experts=1 if shared else None) + self.experts = torch.nn.ModuleList( + [torch.nn.Sequential(torch.nn.Linear(4, 6), torch.nn.SiLU(), torch.nn.Linear(6, 4)) for _ in range(4)] + ) + self.gate = Gate(4, 4, empty_expert) + if shared: + self.shared_experts = torch.nn.Linear(4, 4) + + def forward(self, hidden): + """Evaluate every expert in the original route order.""" + shape = hidden.shape + ids, weights, auxiliary = self.gate(hidden) + values = hidden.reshape(-1, shape[-1]).repeat_interleave(2, dim=0) + result = torch.empty_like(values) + for index, expert in enumerate(self.experts): + selected = ids.reshape(-1) == index + result[selected] = expert(values[selected]) + result = (result.view(*weights.shape, -1) * weights.unsqueeze(-1)).sum(1).view(shape) + result = Auxiliary.apply(result, auxiliary) + return result + self.shared_experts(hidden) if self.config.n_shared_experts else result + + +class DeepseekV2MoE(MoE): + """Use the pinned official class contract for installation controls.""" + + ep_size = 1 + + +@requires_python_310 +@pytest.mark.parametrize('empty_expert', [False, True]) +@pytest.mark.parametrize('shared', [False, True]) +def test_sorted_dispatch_preserves_outputs_inputs_parameters_and_auxiliary_gradients(empty_expert, shared): + """Retain outputs and all gradients, including empty and shared experts.""" + torch.manual_seed(1234) + model = MoE(empty_expert, shared).double() + values = torch.randn(2, 3, 4, dtype=torch.float64, requires_grad=True) + original = model(values) + original.square().mean().backward() + expected_input = values.grad.clone() + expected_parameters = {name: parameter.grad.clone() for name, parameter in model.named_parameters()} + expected_output = original.detach().clone() + model.zero_grad(set_to_none=True) + values.grad = None + actual = moe.sorted_training_forward(model, values, Auxiliary.apply) + actual.square().mean().backward() + torch.testing.assert_close(actual, expected_output, rtol=1e-12, atol=1e-12) + torch.testing.assert_close(values.grad, expected_input, rtol=1e-12, atol=1e-12) + for name, parameter in model.named_parameters(): + assert parameter.grad is not None + torch.testing.assert_close(parameter.grad, expected_parameters[name], rtol=1e-12, atol=1e-12) + if empty_expert: + assert torch.count_nonzero(model.experts[-1][0].weight.grad).item() == 0 + + +@requires_python_310 +def test_installation_preserves_parameters_and_the_evaluation_path(monkeypatch): + """Only training dispatch changes; evaluation retains the original forward.""" + model = torch.nn.ModuleList([DeepseekV2MoE(False, True).double() for _ in range(26)]) + parameters = [id(parameter) for parameter in model.parameters()] + values = torch.randn(1, 2, 4, dtype=torch.float64) + model.eval() + expected = model[0](values).detach() + assert moe.install_sorted_dispatch(model) == 26 + assert [id(parameter) for parameter in model.parameters()] == parameters + replacement = Mock(side_effect=RuntimeError('training dispatch reached')) + monkeypatch.setattr(moe, 'sorted_training_forward', replacement) + torch.testing.assert_close(model[0](values), expected) + replacement.assert_not_called() + model.train() + with pytest.raises(RuntimeError, match='training dispatch reached'): + model[0](values) + + +@requires_python_310 +@pytest.mark.parametrize('count,expert_parallelism', [(25, 1), (27, 1), (26, 2)]) +def test_unsupported_layout_is_rejected_before_any_forward_changes(count, expert_parallelism): + """A partial model or expert-parallel layout cannot receive a partial patch.""" + model = torch.nn.ModuleList([DeepseekV2MoE(False, False) for _ in range(count)]) + model[0].ep_size = expert_parallelism + original = [module.forward for module in model] + with pytest.raises(ValueError): + moe.install_sorted_dispatch(model) + assert [module.forward for module in model] == original From 718f3381a6bb96f9f1b5d60bbf870aca4f216390 Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Fri, 30 Oct 2026 15:13:16 +0000 Subject: [PATCH 6/9] Benchmarks - Run DeepSeek-V2-Lite training in the SuperBench Python Load the official checkpoint for training with the installed transformers instead of the reference loader, whose transformers==4.46.3 pin the inference contract binds by source hash. The profile no longer sets runtime_python, so the worker uses the SuperBench Python. Remove the training Dockerfile and its requirement locks, update the usage docs, and note that only the inference workers run without SuperBench. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../deepseek-v2-lite-training.dockerfile | 18 ----- .../deepseek-v2-lite-controller.in | 15 ---- .../deepseek-v2-lite-controller.txt | 81 ------------------- .../deepseek-v2-lite-reference.txt | 5 -- .../benchmarks/model-benchmarks.md | 18 +---- .../deepseek_v2_lite/__init__.py | 4 +- .../deepseek_v2_lite/training_worker.py | 38 +++++++-- .../config/deepseek-v2-lite-training.yaml | 1 - .../test_pytorch_deepseek_v2_lite.py | 56 ++++++++++++- 9 files changed, 93 insertions(+), 143 deletions(-) delete mode 100644 dockerfile/deepseek-v2-lite-training.dockerfile delete mode 100644 dockerfile/requirements/deepseek-v2-lite-controller.in delete mode 100644 dockerfile/requirements/deepseek-v2-lite-controller.txt delete mode 100644 dockerfile/requirements/deepseek-v2-lite-reference.txt diff --git a/dockerfile/deepseek-v2-lite-training.dockerfile b/dockerfile/deepseek-v2-lite-training.dockerfile deleted file mode 100644 index 3780340f2..000000000 --- a/dockerfile/deepseek-v2-lite-training.dockerfile +++ /dev/null @@ -1,18 +0,0 @@ -FROM nvcr.io/nvidia/pytorch:25.08-py3@sha256:b70bc3ff73fae58e7ec326849b4726eac04200d9ec1da2b385f94c9f7775971f - -COPY dockerfile/requirements/deepseek-v2-lite-controller.txt /tmp/deepseek-v2-lite-controller.txt -RUN python3 -m venv --system-site-packages /opt/deepseek-reference && \ - /opt/deepseek-reference/bin/pip install --no-cache-dir --no-deps -r /tmp/deepseek-v2-lite-controller.txt - -WORKDIR /opt/superbench -COPY setup.py MANIFEST.in LICENSE README.md ./ -COPY superbench ./superbench -RUN /opt/deepseek-reference/bin/pip install --no-cache-dir --no-deps --no-build-isolation . && \ - /opt/deepseek-reference/bin/python -c "import numpy, torch, transformers; assert transformers.__version__ == '4.46.3'; assert torch.from_numpy(numpy.ones(1, dtype=numpy.float32)).numpy()[0] == 1" && \ - /opt/deepseek-reference/bin/sb run --help > /dev/null && \ - /opt/deepseek-reference/bin/sb result diagnosis --help > /dev/null - -RUN apt-get update && apt-get install -y --no-install-recommends rsync && apt-get clean - -ENV PATH="/opt/deepseek-reference/bin:${PATH}" -ENTRYPOINT ["sb"] diff --git a/dockerfile/requirements/deepseek-v2-lite-controller.in b/dockerfile/requirements/deepseek-v2-lite-controller.in deleted file mode 100644 index cef428772..000000000 --- a/dockerfile/requirements/deepseek-v2-lite-controller.in +++ /dev/null @@ -1,15 +0,0 @@ -# Additional constraints for the dedicated Python 3.12 controller/reference runtime. -# Torch and torchvision are provided by the digest-pinned GPU base image. -# The NGC Torch build uses the NumPy 1.x ABI; keep its array bridge functional. -# Regenerate from the repository root with bash: -# uv pip compile setup.py dockerfile/requirements/deepseek-v2-lite-reference.txt \ -# dockerfile/requirements/deepseek-v2-lite-controller.in --python-version 3.12 \ -# --python-platform x86_64-unknown-linux-gnu --excludes <(printf 'torch\ntorchvision\n') \ -# --no-header --no-annotate -o dockerfile/requirements/deepseek-v2-lite-controller.txt -numpy==1.26.4 -pandas==2.2.3 -py3nvml==0.2.7 -setuptools==80.10.2 -setuptools-scm==10.3.4 -vcs-versioning==2.5.0 -wheel diff --git a/dockerfile/requirements/deepseek-v2-lite-controller.txt b/dockerfile/requirements/deepseek-v2-lite-controller.txt deleted file mode 100644 index 905fbf218..000000000 --- a/dockerfile/requirements/deepseek-v2-lite-controller.txt +++ /dev/null @@ -1,81 +0,0 @@ -# Generated for Python 3.12 / Linux x86_64 from setup.py, the reference pins, -# and deepseek-v2-lite-controller.in. The GPU base supplies torch/torchvision. -accelerate==1.2.1 -ansible==14.5.0 -ansible-core==2.21.5 -ansible-runner==2.4.3 -antlr4-python3-runtime==4.9.3 -argcomplete==3.7.2 -attrs==26.1.0 -certifi==2026.10.19 -cffi==2.1.1 -charset-normalizer==3.5.2 -click==8.5.0 -cloudpickle==3.1.2 -colorlog==6.12.0 -contourpy==1.3.3 -cryptography==50.0.2 -cycler==0.12.1 -et-xmlfile==2.0.0 -filelock==4.2.4 -fonttools==4.67.0 -fsspec==2026.9.0 -huggingface-hub==0.26.5 -idna==3.20 -importlib-metadata==9.0.1 -jinja2==3.1.6 -jmespath==1.1.0 -joblib==1.6.0 -jsonlines==4.0.0 -kiwisolver==1.5.1 -knack==0.14.0 -lockfile==0.12.2 -markdown==3.11.2 -markupsafe==3.0.4 -matplotlib==3.11.2 -natsort==8.4.0 -networkx==3.7 -numpy==1.26.4 -omegaconf==2.3.0 -openpyxl==3.1.5 -packaging==26.3 -pandas==2.2.3 -pexpect==4.9.0 -pillow==13.0.0 -prettytable==3.18.0 -protobuf==7.36.2 -pssh @ git+https://github.com/lilydjwg/pssh.git@2dce3d8e45a492985fa1ae0207b6d55afac97c16 -psutil==7.2.2 -ptyprocess==0.7.0 -py3nvml==0.2.7 -pycparser==3.11 -pygments==2.21.0 -pyparsing==3.3.3 -python-daemon==3.1.2 -python-dateutil==2.9.0.post0 -pytz==2026.5 -pyyaml==6.0.3 -regex==2026.9.29 -requests==2.34.2 -resolvelib==1.2.1 -safetensors==0.5.3 -seaborn==0.13.2 -setuptools==80.10.2 -setuptools-scm==10.3.4 -six==1.17.0 -tabulate==0.10.0 -tcping==0.1.1rc1 -tokenizers==0.20.3 -tqdm==4.70.1 -transformers==4.46.3 -types-requests==2.33.0.20261006 -typing-extensions==4.16.0 -tzdata==2026.5 -urllib3==2.8.0 -vcs-versioning==2.5.0 -wcwidth==0.9.3 -wheel==0.48.0 -xlrd==2.0.2 -xlsxwriter==3.2.9 -xmltodict==1.0.4 -zipp==4.1.2 diff --git a/dockerfile/requirements/deepseek-v2-lite-reference.txt b/dockerfile/requirements/deepseek-v2-lite-reference.txt deleted file mode 100644 index e5ab4c95a..000000000 --- a/dockerfile/requirements/deepseek-v2-lite-reference.txt +++ /dev/null @@ -1,5 +0,0 @@ -# Separate worker environment; do not replace SuperBench's framework dependencies. -transformers==4.46.3 -huggingface-hub==0.26.5 -accelerate==1.2.1 -safetensors==0.5.3 diff --git a/docs/user-tutorial/benchmarks/model-benchmarks.md b/docs/user-tutorial/benchmarks/model-benchmarks.md index d34d72ba9..5dd8b773e 100644 --- a/docs/user-tutorial/benchmarks/model-benchmarks.md +++ b/docs/user-tutorial/benchmarks/model-benchmarks.md @@ -192,21 +192,9 @@ unsharded reference runs on one GPU, so use 80GB-class GPUs. #### Usage Run the [training profile](../../../superbench/config/deepseek-v2-lite-training.yaml) as its own -benchmark entry with one local process (`proc_num: 1`). The -[model runtime Dockerfile](../../../dockerfile/deepseek-v2-lite-training.dockerfile) provides the -worker environment: - -```bash -docker build -f dockerfile/deepseek-v2-lite-training.dockerfile -t sb-v2lite-training . -docker run --rm --gpus '"device=0,1,2,3"' --shm-size 32g \ - -v "$PWD/v2lite-results:/results" sb-v2lite-training exec \ - --config-file superbench/config/deepseek-v2-lite-training.yaml \ - --output-dir /results/sb-output \ - -C superbench.benchmarks.deepseek-v2-lite-training.parameters.cache_root=/results/model-cache -``` - -Outside Docker, set `runtime_python` to a separate Python 3.10+ environment with a GPU build of -PyTorch 2.5+ and the [reference packages](../../../dockerfile/requirements/deepseek-v2-lite-reference.txt). +benchmark entry with one local process (`proc_num: 1`) in the SuperBench CUDA image. The worker uses +the SuperBench Python by default (`runtime_python`), with its PyTorch and transformers loading the +official model code; transformers 5 no longer supports that code. `cache_root` is required. Each run downloads the checkpoint into a new directory under it and deletes that model cache at the end, keeping the report and logs. If deletion fails, the cache path is logged diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/__init__.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/__init__.py index 9cc630068..da0e0cb0a 100644 --- a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/__init__.py +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/__init__.py @@ -3,6 +3,6 @@ """DeepSeek-V2-Lite workers and helpers. -Workers run as ``python -m deepseek_v2_lite.`` in interpreters without SuperBench, so every module -except ``cache`` imports only the standard library and this package at load time. +Workers run as ``python -m deepseek_v2_lite.``, the inference ones in interpreters without SuperBench, +so every module except ``cache`` imports only the standard library and this package at load time. """ diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/training_worker.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/training_worker.py index a06f3e7ce..33efcf849 100644 --- a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/training_worker.py +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/training_worker.py @@ -13,13 +13,41 @@ from pathlib import Path from .moe import MOE_DISPATCHES, install_sorted_dispatch -from .reference import fixed_documents, load_model, training_reference +from .reference import fixed_documents, training_reference from .utils import ( - configure_cache, download_checkpoint, identity_report, interrupt_worker, packed_tokens, read_json, - set_cache_environment, write_json + PARAMETER_COUNT, configure_cache, download_checkpoint, identity_report, interrupt_worker, packed_tokens, read_json, + set_cache_environment, validate_config, write_json ) +def load_training_model(checkpoint, dtype): + """Load the complete official checkpoint with the installed transformers for full-parameter training.""" + # Same checks as reference.load_model, minus the transformers pin that the inference contract binds by hash. + import torch + from transformers import AutoModelForCausalLM + + validate_config(read_json(Path(checkpoint) / 'config.json')) + model, loading = AutoModelForCausalLM.from_pretrained( + checkpoint, + torch_dtype=dtype, + trust_remote_code=True, + local_files_only=True, + use_safetensors=True, + attn_implementation='eager', + output_loading_info=True, + ) + for key in ('missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs'): + if key not in loading or loading[key]: + raise RuntimeError('Official checkpoint loading failed: {}={!r}.'.format(key, loading.get(key))) + if sum(parameter.numel() for parameter in model.parameters()) != PARAMETER_COUNT: + raise RuntimeError('Loaded parameter count differs from the complete official V2-Lite.') + if not all(parameter.requires_grad for parameter in model.parameters()): + raise RuntimeError('The full-parameter profile must not freeze model parameters.') + if not torch.cuda.is_available(): + raise RuntimeError('CUDA/ROCm GPU unavailable in the training environment.') + return model + + def compare_gradients(model, reference): """Unshard one layer at a time to check sampled dense, MLA and MoE gradients.""" import torch @@ -119,7 +147,7 @@ def run_training(args, reference, checkpoint): raise ValueError('Training reference has an incomplete global batch.') if args.moe_dispatch not in MOE_DISPATCHES: raise ValueError('Unsupported MoE training dispatch.') - model = load_model(str(checkpoint), torch.float32) + model = load_training_model(str(checkpoint), torch.float32) rewritten_layers = install_sorted_dispatch(model) if args.moe_dispatch == 'stable_sorted' else 0 decoder_type = type(model.model.layers[0]) model = FSDP( @@ -263,7 +291,7 @@ def main(): report['download_verify_seconds'] = time.monotonic() - download_start reference_start = time.monotonic() if rank == 0: - reference_model = load_model(str(checkpoint), torch.bfloat16).cuda() + reference_model = load_training_model(str(checkpoint), torch.bfloat16).cuda() try: write_json( reference_path, diff --git a/superbench/config/deepseek-v2-lite-training.yaml b/superbench/config/deepseek-v2-lite-training.yaml index d27697cb4..d47d988ed 100644 --- a/superbench/config/deepseek-v2-lite-training.yaml +++ b/superbench/config/deepseek-v2-lite-training.yaml @@ -14,7 +14,6 @@ superbench: parallel: false timeout: 3600 parameters: - runtime_python: /opt/deepseek-reference/bin/python cache_root: /data/deepseek-v2-lite num_gpus: 4 batch_size: 2 diff --git a/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py b/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py index 7a0c92939..1ccd80542 100644 --- a/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py +++ b/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py @@ -353,7 +353,7 @@ def main_driver(worker, tmp_path, monkeypatch): loader = Mock(return_value=model) reference = Mock(return_value={'world_size': 2, 'batch_size': 2, 'seq_len': 64, 'reference_microbatch_size': 2}) training = Mock(return_value={'world_size': 2, 'step_ms': [1.0, 2.0]}) - monkeypatch.setattr(worker, 'load_model', loader) + monkeypatch.setattr(worker, 'load_training_model', loader) monkeypatch.setattr(worker, 'training_reference', reference) monkeypatch.setattr(worker, 'run_training', training) monkeypatch.setattr(torch.cuda, 'device_count', lambda: 2) @@ -504,6 +504,60 @@ def test_gradient_probe_mapping_covers_root_and_checkpointed_layers(worker, monk worker.compare_gradients(model, reference) +@pytest.fixture +def training_loader(tmp_path, monkeypatch): + """Replace transformers with a fake loader while keeping every training loader check real.""" + from superbench.benchmarks.model_benchmarks.deepseek_v2_lite.utils import EXPECTED_CONFIG, PARAMETER_COUNT + + (tmp_path / 'config.json').write_text(json.dumps(dict(EXPECTED_CONFIG, model_type='deepseek_v2'))) + parameter = SimpleNamespace(numel=lambda: PARAMETER_COUNT, requires_grad=True) + model = SimpleNamespace(parameters=lambda: [parameter]) + loading = {key: [] for key in ['missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs']} + loader = Mock(return_value=(model, loading)) + monkeypatch.setitem( + sys.modules, 'transformers', SimpleNamespace(AutoModelForCausalLM=SimpleNamespace(from_pretrained=loader)) + ) + monkeypatch.setattr(torch.cuda, 'is_available', lambda: True) + return SimpleNamespace(path=tmp_path, model=model, parameter=parameter, loading=loading, loader=loader) + + +@requires_python_310 +def test_training_loader_accepts_the_platform_transformers(training_loader, monkeypatch): + """Training loads official code with the SuperBench transformers, which the pinned reference loader rejects.""" + import importlib.metadata + from superbench.benchmarks.model_benchmarks.deepseek_v2_lite import reference + + item = training_loader + version = importlib.metadata.version + monkeypatch.setattr( + importlib.metadata, 'version', lambda name: '4.52.4' if name == 'transformers' else version(name) + ) + assert training_worker.load_training_model(str(item.path), torch.float32) is item.model + options = item.loader.call_args[1] + assert options['torch_dtype'] == torch.float32 + assert options['local_files_only'] and options['trust_remote_code'] and options['use_safetensors'] + assert options['attn_implementation'] == 'eager' and options['output_loading_info'] + with pytest.raises(RuntimeError, match='4.46.3'): + reference.load_model(str(item.path), torch.float32) + + +@requires_python_310 +@pytest.mark.parametrize('failure', ['diagnostics', 'count', 'frozen', 'gpu']) +def test_training_loader_rejects_incomplete_models(training_loader, monkeypatch, failure): + """Keep the complete-checkpoint, trainable-parameter and GPU checks of the reference loader.""" + item = training_loader + if failure == 'diagnostics': + item.loading['missing_keys'] = ['model.norm.weight'] + elif failure == 'count': + item.parameter.numel = lambda: 1 + elif failure == 'frozen': + item.parameter.requires_grad = False + else: + monkeypatch.setattr(torch.cuda, 'is_available', lambda: False) + with pytest.raises(RuntimeError): + training_worker.load_training_model(str(item.path), torch.float32) + + # Stable MoE dispatch. class Auxiliary(torch.autograd.Function): """Match the official auxiliary-loss autograd contract.""" From dce81da3a61c5e3ee88de5c195ed5cb84124698b Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Fri, 30 Oct 2026 21:18:30 +0000 Subject: [PATCH 7/9] Docs - Simplify the DeepSeek-V2-Lite training section Keep what users need to run and read the benchmark: the workload, its reference check, the validated profile, the CUDA 13.0 image with transformers 4.x, and the cache_root and duration rules. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../benchmarks/model-benchmarks.md | 44 +++++++------------ 1 file changed, 16 insertions(+), 28 deletions(-) diff --git a/docs/user-tutorial/benchmarks/model-benchmarks.md b/docs/user-tutorial/benchmarks/model-benchmarks.md index 5dd8b773e..13435e325 100644 --- a/docs/user-tutorial/benchmarks/model-benchmarks.md +++ b/docs/user-tutorial/benchmarks/model-benchmarks.md @@ -169,37 +169,25 @@ Run GPT pretrain tasks with float32, float16, bfloat16 precisions with [Megatron #### Introduction -Run full-parameter BF16 causal-LM training with the official -[DeepSeek-V2-Lite](https://huggingface.co/deepseek-ai/DeepSeek-V2-Lite) checkpoint at revision -`604d5664dddd88a0433dbae533b7fe9472482de0` (15.7B parameters). The worker starts `torchrun` on -`num_gpus` local GPUs (at least two) and trains on a small fixed-text dataset with fully sharded FSDP, -AdamW and activation checkpointing; `batch_size` is the microbatch per GPU. The job downloads the -checkpoint and verifies the SHA256 of its 31.4GB of weight files. Before training, the FSDP loss and -sampled gradients must match an unsharded official-code reference, and every step must produce a -finite loss and a finite, nonzero gradient norm. Training starts from the pretrained weights with a -new optimizer state; it measures training performance, not convergence or model quality. - -`moe_dispatch` defaults to `official`. `stable_sorted` groups routed tokens with a stable sort instead -of repeated Boolean indexing; it keeps the same experts, routing and weights, and the reference check -compares it with the official implementation. - -Validation covers one profile on four H100 80GB GPUs: `batch_size=36`, `seq_len=512`, -`num_warmup=2`, `num_steps=128`, `moe_dispatch=stable_sorted` and -`PYTORCH_CUDA_ALLOC_CONF=backend:native`. The supplied profile is a smaller example -(`batch_size=2`, `num_steps=8`, official dispatch); other configurations are not validated. The -unsharded reference runs on one GPU, so use 80GB-class GPUs. +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 with `batch_size=36`, `num_steps=128`, `moe_dispatch=stable_sorted` +and `PYTORCH_CUDA_ALLOC_CONF=backend:native`; the supplied profile is a smaller example. The reference +needs an 80GB GPU. #### Usage -Run the [training profile](../../../superbench/config/deepseek-v2-lite-training.yaml) as its own -benchmark entry with one local process (`proc_num: 1`) in the SuperBench CUDA image. The worker uses -the SuperBench Python by default (`runtime_python`), with its PyTorch and transformers loading the -official model code; transformers 5 no longer supports that code. - -`cache_root` is required. Each run downloads the checkpoint into a new directory under it and deletes -that model cache at the end, keeping the report and logs. If deletion fails, the cache path is logged -for manual removal. `duration` must be below 3600 seconds and covers the whole job, from download to -cache deletion. +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 From 3ab6ee53c10f1ee5624b4aa7e58fee0733698b52 Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:03:00 +0000 Subject: [PATCH 8/9] Benchmarks - Enforce one V2-Lite launcher and keep timeouts after failed cleanup - Check PROC_RANK, WORLD_SIZE and OMPI_COMM_WORLD_SIZE independently, so a second local process or a masked MPI world size cannot start another full-model job. - If descendant cleanup fails after the deadline, the supervisor returns 126 and run_worker raises a TimeoutError that names the failed cleanup. - The download test now proves that a corrupted shard is rejected. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../deepseek_v2_lite/utils.py | 64 ++++++++++++++----- .../pytorch_deepseek_v2_lite.py | 12 ++-- .../model_benchmarks/test_deepseek_v2_lite.py | 41 +++++++++++- .../test_pytorch_deepseek_v2_lite.py | 12 ++-- 4 files changed, 103 insertions(+), 26 deletions(-) diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/utils.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/utils.py index 0a44520ef..9ab65448e 100644 --- a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/utils.py +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/utils.py @@ -12,7 +12,7 @@ import sys import time from pathlib import Path -from typing import Dict, List, Optional, Sequence +from typing import Callable, Dict, List, Mapping, Optional, Sequence MODEL_ID = 'deepseek-ai/DeepSeek-V2-Lite' REVISION = '604d5664dddd88a0433dbae533b7fe9472482de0' @@ -238,6 +238,20 @@ def _stop_children() -> None: time.sleep(0.02) +def _wait_for_worker(process: subprocess.Popen, deadline: float, interrupted: Callable[[], bool]) -> int: + """Return the worker status, 124 at the deadline or on interruption, or 125 for live descendants.""" + while process.poll() is None: + if interrupted() or time.monotonic() >= deadline: + return 124 + time.sleep(0.02) + code = process.wait() + _reap_children() + if code == 0 and _owned_children(): + print('Worker exited with live descendant processes.', file=sys.stderr, flush=True) + return 125 + return code if code >= 0 else 128 - code + + def supervise_worker(command: List[str], timeout: float, parent_pid: int) -> int: """Contain Linux worker descendants in a separate single-threaded supervisor.""" import ctypes @@ -262,20 +276,21 @@ def stop(signum, frame): return 124 deadline = time.monotonic() + timeout process = subprocess.Popen(command) + stopped = False try: - while process.poll() is None: - if interrupted or time.monotonic() >= deadline: - return 124 - time.sleep(0.02) - code = process.wait() - _reap_children() - if code == 0 and _owned_children(): - print('Worker exited with live descendant processes.', file=sys.stderr, flush=True) - return 125 - return code if code >= 0 else 128 - code + code = _wait_for_worker(process, deadline, lambda: interrupted) finally: - _stop_children() - process.wait() + try: + _stop_children() + stopped = True + except RuntimeError as error: + print(error, file=sys.stderr, flush=True) + if stopped: + process.wait() + if stopped: + return code + # Keep cleanup failures visible: 126 is a deadline whose cleanup also failed, and a clean exit becomes 125. + return 126 if code == 124 else code or 125 def interrupt_worker(signum, frame) -> None: @@ -283,6 +298,24 @@ def interrupt_worker(signum, frame) -> None: raise TimeoutError('Model worker interrupted by signal {}.'.format(signum)) +# SuperBench local ranks and the torch and MPI world sizes; any other value means another launcher. +SINGLE_LAUNCHER = {'PROC_RANK': 0, 'WORLD_SIZE': 1, 'OMPI_COMM_WORLD_SIZE': 1} + + +def validate_single_launcher(environment: Mapping[str, str]) -> None: + """Reject a second local process or a distributed group, checking every launcher variable.""" + for name, expected in SINGLE_LAUNCHER.items(): + value = environment.get(name) + if value is None: + continue + try: + single = int(value) == expected + except ValueError: + single = False + if not single: + raise ValueError('{}={!r} means another launcher; run one local process.'.format(name, value)) + + def worker_environment() -> Dict[str, str]: """Let worker interpreters without SuperBench import this package by module name.""" environment = dict(os.environ) @@ -314,8 +347,9 @@ def run_worker(command: List[str], log: Path, timeout: float, env: Optional[Dict code = process.wait(timeout=timeout + 20) except subprocess.TimeoutExpired as error: raise TimeoutError('Model worker supervisor exceeded its cleanup deadline.') from error - if code == 124: - raise TimeoutError('Model worker exceeded the download-inclusive deadline.') + if code in (124, 126): + cleanup = ' and its descendants did not exit; see {}'.format(log) if code == 126 else '' + raise TimeoutError('Model worker exceeded the download-inclusive deadline{}.'.format(cleanup)) if code == 125: raise RuntimeError('Model worker left descendant processes running; see {}.'.format(log)) if code != 0: diff --git a/superbench/benchmarks/model_benchmarks/pytorch_deepseek_v2_lite.py b/superbench/benchmarks/model_benchmarks/pytorch_deepseek_v2_lite.py index 5dd47c78d..2242a5b96 100644 --- a/superbench/benchmarks/model_benchmarks/pytorch_deepseek_v2_lite.py +++ b/superbench/benchmarks/model_benchmarks/pytorch_deepseek_v2_lite.py @@ -18,7 +18,7 @@ ) from superbench.benchmarks.model_benchmarks.deepseek_v2_lite.moe import MOE_DISPATCHES from superbench.benchmarks.model_benchmarks.deepseek_v2_lite.utils import ( - numeric_series, read_json, run_worker, validate_identity, worker_environment + numeric_series, read_json, run_worker, validate_identity, validate_single_launcher, worker_environment ) @@ -62,13 +62,13 @@ def _preprocess(self): or args.seq_len < 32 or args.num_warmup < 0 or args.num_steps < 1 or not 0 < args.learning_rate < 1 ) try: - world_size = int(os.environ.get('WORLD_SIZE', os.environ.get('OMPI_COMM_WORLD_SIZE', '1'))) - except ValueError: - logger.error('V2-Lite training launcher world size must be an integer.') + validate_single_launcher(os.environ) + except ValueError as error: + logger.error('V2-Lite training requires one local launcher: %s', error) self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) return False - if invalid or world_size != 1: - logger.error('V2-Lite training requires one local launcher, valid positive dimensions and duration <3600s.') + if invalid: + logger.error('V2-Lite training requires valid positive dimensions and duration <3600s.') self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) return False return True diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite.py index 3934bc0fb..36cf39a8a 100644 --- a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite.py +++ b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite.py @@ -260,7 +260,7 @@ def test_invalid_checkpoint_files_fail(checkpoint_files, failure): def test_download_uses_pinned_public_identity_and_then_verifies(checkpoint_files, monkeypatch): - """Disable implicit credentials and require the downloaded shard contract.""" + """Disable implicit credentials and reject a downloaded shard that fails verification.""" root, shard = checkpoint_files download = Mock() monkeypatch.setitem(sys.modules, 'huggingface_hub', SimpleNamespace(snapshot_download=download)) @@ -271,6 +271,9 @@ def test_download_uses_pinned_public_identity_and_then_verifies(checkpoint_files assert arguments['token'] is False assert arguments['local_dir'] == str(root) assert shard.name in arguments['allow_patterns'] + download.side_effect = lambda **kwargs: shard.write_bytes(b'x' * shard.stat().st_size) + with pytest.raises(ValueError, match='SHA256'): + utils.download_checkpoint(root.parent) @pytest.mark.parametrize('timeout', [0, -1, float('nan')]) @@ -298,6 +301,42 @@ def test_supervisor_requires_kernel_ownership_support(monkeypatch): spawn.assert_not_called() +def test_timeout_survives_failed_descendant_cleanup(tmp_path, monkeypatch, capsys): + """A cleanup failure after the deadline stays a timeout and keeps its own details.""" + worker = SimpleNamespace(poll=lambda: None, wait=Mock()) + monkeypatch.setattr(utils.signal, 'signal', Mock()) + monkeypatch.setattr(ctypes, 'CDLL', lambda *args, **kwargs: SimpleNamespace(prctl=lambda *args: 0)) + monkeypatch.setattr(utils.subprocess, 'Popen', lambda command: worker) + monkeypatch.setattr(utils, '_stop_children', Mock(side_effect=RuntimeError('descendants did not exit: [4242]'))) + assert utils.supervise_worker([sys.executable, '-c', 'pass'], 0.05, os.getppid()) == 126 + assert '[4242]' in capsys.readouterr().err + worker.wait.assert_not_called() + supervisor = SimpleNamespace(wait=lambda timeout: 126, poll=lambda: 126) + monkeypatch.setattr(utils.subprocess, 'Popen', lambda *args, **kwargs: supervisor) + with pytest.raises(TimeoutError, match='deadline and its descendants did not exit'): + utils.run_worker([sys.executable, '-c', 'pass'], tmp_path / 'worker.log', 5) + + +@pytest.mark.parametrize( + 'environment, accepted', [ + ('', True), + ('PROC_RANK=0 WORLD_SIZE=1 OMPI_COMM_WORLD_SIZE=1', True), + ('PROC_RANK=1', False), + ('WORLD_SIZE=1 OMPI_COMM_WORLD_SIZE=8', False), + ('OMPI_COMM_WORLD_SIZE=1 WORLD_SIZE=2', False), + ('PROC_RANK=', False), + ] +) +def test_launcher_variables_are_checked_independently(environment, accepted): + """A local rank or any one distributed world size above one means another launcher.""" + variables = dict(item.split('=', 1) for item in environment.split()) + if accepted: + utils.validate_single_launcher(variables) + else: + with pytest.raises(ValueError, match='another launcher'): + utils.validate_single_launcher(variables) + + # Per-run model cache removal. def test_removes_only_the_run_cache(tmp_path): """Delete the downloaded checkpoint while keeping the run's report and logs.""" diff --git a/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py b/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py index 1ccd80542..1283e1075 100644 --- a/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py +++ b/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py @@ -36,6 +36,7 @@ def benchmark(tmp_path, monkeypatch): """Use an isolated cache root and a single local launcher.""" monkeypatch.delenv('WORLD_SIZE', raising=False) monkeypatch.delenv('OMPI_COMM_WORLD_SIZE', raising=False) + monkeypatch.delenv('PROC_RANK', raising=False) return adapter.DeepSeekV2LiteTraining( 'deepseek-v2-lite-training', '--cache_root "{}" --num_steps 2 --seq_len 64 --duration 60'.format(tmp_path), @@ -107,10 +108,13 @@ def test_parameters_render_in_help(): assert '--cache_root' in settings -@pytest.mark.parametrize('world_size', ['8', 'not-an-integer']) -def test_duplicate_launcher_is_rejected(benchmark, monkeypatch, world_size): - """An MPI worker group must not launch eight independent full-model jobs.""" - monkeypatch.setenv('WORLD_SIZE', world_size) +@pytest.mark.parametrize( + 'environment', ['WORLD_SIZE=8', 'WORLD_SIZE=not-an-integer', 'PROC_RANK=1', 'WORLD_SIZE=1 OMPI_COMM_WORLD_SIZE=8'] +) +def test_duplicate_launcher_is_rejected(benchmark, monkeypatch, environment): + """Neither a second local process nor an MPI or torch group may start another full-model job.""" + for item in environment.split(): + monkeypatch.setenv(*item.split('=', 1)) assert not benchmark.run() assert benchmark.return_code == ReturnCode.INVALID_ARGUMENT From 125697ad893e8ccf6f196ce78294392889c20049 Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:45:47 +0000 Subject: [PATCH 9/9] Docs - Qualify the V2-Lite training validation and host memory Name the runtime that the H100 validation used and state the host memory that full-model FP32 loading needs before FSDP sharding, as measured on four H100 GPUs. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/user-tutorial/benchmarks/model-benchmarks.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/user-tutorial/benchmarks/model-benchmarks.md b/docs/user-tutorial/benchmarks/model-benchmarks.md index 13435e325..c7847d0a7 100644 --- a/docs/user-tutorial/benchmarks/model-benchmarks.md +++ b/docs/user-tutorial/benchmarks/model-benchmarks.md @@ -177,9 +177,11 @@ text; it measures training performance, not convergence. `batch_size` is the mic `moe_dispatch=stable_sorted` replaces the official expert dispatch with a stable sort that keeps the same routing. -Validated on four H100 80GB GPUs with `batch_size=36`, `num_steps=128`, `moe_dispatch=stable_sorted` -and `PYTORCH_CUDA_ALLOC_CONF=backend:native`; the supplied profile is a smaller example. The reference -needs an 80GB GPU. +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 +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