diff --git a/docs/user-tutorial/benchmarks/model-benchmarks.md b/docs/user-tutorial/benchmarks/model-benchmarks.md index c782abbcc..c7847d0a7 100644 --- a/docs/user-tutorial/benchmarks/model-benchmarks.md +++ b/docs/user-tutorial/benchmarks/model-benchmarks.md @@ -163,3 +163,41 @@ Run GPT pretrain tasks with float32, float16, bfloat16 precisions with [Megatron | megatron-gpt/${precision}_train_mem_allocated | GB | The average GPU memory allocated per iteration. | | megatron-gpt/${precision}_train_max_mem_allocated | GB | The average maximum GPU memory allocated per iteration. | +## DeepSeek-V2-Lite Training + +### `deepseek-v2-lite-training` + +#### Introduction + +Run full-parameter BF16 training of the official +[DeepSeek-V2-Lite](https://huggingface.co/deepseek-ai/DeepSeek-V2-Lite) checkpoint (15.7B parameters) +with FSDP and AdamW on `num_gpus` local GPUs. Each run downloads and verifies the 31.4GB checkpoint, +checks the loss and sampled gradients against an unsharded official-code reference, then trains on fixed +text; it measures training performance, not convergence. `batch_size` is the microbatch per GPU. +`moe_dispatch=stable_sorted` replaces the official expert dispatch with a stable sort that keeps the +same routing. + +Validated on four H100 80GB GPUs in the SuperBench CUDA 13.0 image with `batch_size=36`, `num_steps=128`, +`moe_dispatch=stable_sorted` and `PYTORCH_CUDA_ALLOC_CONF=backend:native`; the supplied profile is a +smaller example. The reference needs an 80GB GPU. Each GPU's process first loads the full model in FP32 +on the host, about 63GB, before FSDP shards it; the validated four-GPU run used about 275GB of host +memory at its peak. + +#### Usage + +Run the [training profile](../../../superbench/config/deepseek-v2-lite-training.yaml) as its own entry +with one local process in the SuperBench CUDA 13.0 image. The worker uses the SuperBench Python +(`runtime_python`), whose transformers 4.x runs the official model code. `cache_root` is required: each +run downloads into a new directory under it and deletes the checkpoint at the end. `duration` must be +below 3600 seconds and covers the whole job. + +#### Metrics + +| Name | Unit | Description | +|---|---|---| +| deepseek-v2-lite-training/bf16_train_step_time | time (ms) | The average training step time of the slowest GPU, including forward, backward, gradient clipping and the optimizer update. | +| deepseek-v2-lite-training/bf16_train_tokens_per_second | throughput (tokens/s) | Next-token targets trained per second across all GPUs. | +| deepseek-v2-lite-training/bf16_train_loss | loss | The average global causal-LM loss. | +| deepseek-v2-lite-training/bf16_train_gradient_norm | norm | The average global gradient norm before clipping. | +| deepseek-v2-lite-training/end_to_end_seconds | time (s) | The complete job time, including checkpoint download and cache deletion. | +| deepseek-v2-lite-training/checkpoint_bytes | size (bytes) | The total size of the checkpoint weight files. | 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/__init__.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/__init__.py new file mode 100644 index 000000000..da0e0cb0a --- /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.``, 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/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/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..313d2c89b --- /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 .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..33efcf849 --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/training_worker.py @@ -0,0 +1,327 @@ +# 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 .moe import MOE_DISPATCHES, install_sorted_dispatch +from .reference import fixed_documents, training_reference +from .utils import ( + 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 + 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_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( + 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_training_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..9ab65448e --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/utils.py @@ -0,0 +1,406 @@ +# 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 Callable, Dict, List, Mapping, Optional, 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 _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 + + 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) + stopped = False + try: + code = _wait_for_worker(process, deadline, lambda: interrupted) + finally: + 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: + """Unwind subprocess waits so nested reference workers are cleaned up.""" + 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) + 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.') + 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, env=env) + 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 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: + 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..2242a5b96 --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/pytorch_deepseek_v2_lite.py @@ -0,0 +1,176 @@ +# 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.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, validate_single_launcher, worker_environment +) + + +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=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', 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 + ) + try: + 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: + logger.error('V2-Lite training requires 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.""" + args = self._args + return [ + args.runtime_python, + '-m', + 'torch.distributed.run', + '--standalone', + '--nproc_per_node={}'.format(args.num_gpus), + '--module', + 'deepseek_v2_lite.training_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 _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() + 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))) + 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, + env=worker_environment(), + ) + 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.') + 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..d47d988ed --- /dev/null +++ b/superbench/config/deepseek-v2-lite-training.yaml @@ -0,0 +1,24 @@ +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: + 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.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite.py new file mode 100644 index 000000000..36cf39a8a --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite.py @@ -0,0 +1,754 @@ +# 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 reject a downloaded shard that fails verification.""" + 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'] + 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')]) +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() + + +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.""" + 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_pytorch_deepseek_v2_lite.py b/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py new file mode 100644 index 000000000..1283e1075 --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_pytorch_deepseek_v2_lite.py @@ -0,0 +1,686 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""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 pytorch_deepseek_v2_lite as adapter +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.""" + 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), + ) + + +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( + 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(tmp_path, parameters): + """Reject invalid shapes, architecture overrides and combined timing profiles.""" + 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( + '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 + + +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, env): + 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, env): + 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('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, 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') + 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, env) + + 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') + + +@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, env): + assert timeout == 40 + Path(command[command.index('--cache_dir') + 1]).mkdir(parents=True) + successful_worker(command, log, timeout, env) + 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 + + +@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, env): + 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( + '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, env): + successful_worker(command, log, timeout, env) + 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('--module') + 1] == 'deepseek_v2_lite.training_worker' + 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, env): + commands.append(command) + 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_training_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) + + +@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.""" + @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