From be753b9bf3115e5b791f940819a870912e0b4a95 Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Wed, 28 Oct 2026 18:03:55 +0000 Subject: [PATCH 1/8] Benchmarks - Add official-checkpoint V2-Lite generative inference Add deepseek-v2-lite-inference, an opt-in benchmark that downloads the official DeepSeek-V2-Lite checkpoint and measures single-GPU BF16 generation with an isolated vLLM 0.31.0 worker. - Prefill and cached-decode metrics from actual output token counts. - Independent official-code reference with an explicit H100 BF16 numerical policy; strict FP32 remains the default policy. - Download-inclusive deadline and supervised worker cleanup. - Runtime image recipe, configuration, CPU tests and documentation. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- MANIFEST.in | 1 + .../deepseek-v2-lite-inference.dockerfile | 23 + .../deepseek-v2-lite-controller.in | 15 + .../deepseek-v2-lite-controller.txt | 81 +++ .../deepseek-v2-lite-reference.txt | 5 + .../benchmarks/model-benchmarks.md | 173 ++++++ .../benchmarks/model_benchmarks/__init__.py | 3 +- .../deepseek_v2_lite_inference_worker.py | 340 +++++++++++ .../deepseek_v2_lite_numerics.py | 488 +++++++++++++++ .../deepseek_v2_lite_reference.py | 266 +++++++++ .../deepseek_v2_lite_utils.py | 364 ++++++++++++ .../model_benchmarks/vllm_deepseek_v2_lite.py | 165 ++++++ .../deepseek-v2-lite-h100-numerics.json | 124 ++++ .../config/deepseek-v2-lite-inference.yaml | 27 + .../test_deepseek_v2_lite_inference_worker.py | 502 ++++++++++++++++ .../test_deepseek_v2_lite_numerics.py | 555 ++++++++++++++++++ .../test_deepseek_v2_lite_reference.py | 377 ++++++++++++ .../test_deepseek_v2_lite_utils.py | 345 +++++++++++ .../test_vllm_deepseek_v2_lite.py | 153 +++++ 19 files changed, 4006 insertions(+), 1 deletion(-) create mode 100644 dockerfile/deepseek-v2-lite-inference.dockerfile create mode 100644 dockerfile/requirements/deepseek-v2-lite-controller.in create mode 100644 dockerfile/requirements/deepseek-v2-lite-controller.txt create mode 100644 dockerfile/requirements/deepseek-v2-lite-reference.txt create mode 100644 superbench/benchmarks/model_benchmarks/deepseek_v2_lite_inference_worker.py create mode 100644 superbench/benchmarks/model_benchmarks/deepseek_v2_lite_numerics.py create mode 100644 superbench/benchmarks/model_benchmarks/deepseek_v2_lite_reference.py create mode 100644 superbench/benchmarks/model_benchmarks/deepseek_v2_lite_utils.py create mode 100644 superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py create mode 100644 superbench/config/deepseek-v2-lite-h100-numerics.json create mode 100644 superbench/config/deepseek-v2-lite-inference.yaml create mode 100644 tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_inference_worker.py create mode 100644 tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_numerics.py create mode 100644 tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_reference.py create mode 100644 tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_utils.py create mode 100644 tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py diff --git a/MANIFEST.in b/MANIFEST.in index 34d9d0272..7fab786c5 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,3 +1,4 @@ include LICENSE README.md +include superbench/config/deepseek-v2-lite-h100-numerics.json recursive-include superbench *.py *.j2 *.yaml global-exclude *.py[cod] __pycache__ diff --git a/dockerfile/deepseek-v2-lite-inference.dockerfile b/dockerfile/deepseek-v2-lite-inference.dockerfile new file mode 100644 index 000000000..dcaa4f11d --- /dev/null +++ b/dockerfile/deepseek-v2-lite-inference.dockerfile @@ -0,0 +1,23 @@ +FROM vllm/vllm-openai:v0.31.0@sha256:c1c9f6fd5c109ba7f0546a59f5b2f15fb87f64c77782e90a27b648b42a8e67c3 + +RUN apt-get update && apt-get install -y --no-install-recommends git && apt-get clean + +COPY dockerfile/requirements/deepseek-v2-lite-controller.txt /tmp/deepseek-v2-lite-controller.txt +RUN mkdir -p /opt/vllm/bin && ln -s /usr/bin/python3 /opt/vllm/bin/python && \ + python3 -m venv --system-site-packages /opt/deepseek-reference && \ + python3 -c "import pathlib, sys, sysconfig; source=sysconfig.get_path('purelib'); target=pathlib.Path('/opt/deepseek-reference/lib') / ('python%d.%d' % sys.version_info[:2]) / 'site-packages'; (target / 'engine-torch.pth').write_text(source + '\n')" && \ + /opt/deepseek-reference/bin/pip install --no-cache-dir --no-deps -r /tmp/deepseek-v2-lite-controller.txt + +WORKDIR /opt/superbench +COPY setup.py MANIFEST.in LICENSE README.md ./ +COPY superbench ./superbench +RUN /opt/deepseek-reference/bin/pip install --no-cache-dir --no-deps --no-build-isolation . && \ + /opt/deepseek-reference/bin/python -c "import numpy, torch, transformers; assert transformers.__version__ == '4.46.3'; assert torch.from_numpy(numpy.ones(1, dtype=numpy.float32)).numpy()[0] == 1" && \ + /opt/vllm/bin/python -c "from importlib.metadata import version; import numpy, torch; assert version('vllm').split('+')[0] == '0.31.0'; assert version('transformers') == '5.17.0'; assert torch.from_numpy(numpy.ones(1, dtype=numpy.float32)).numpy()[0] == 1" && \ + /opt/deepseek-reference/bin/sb run --help > /dev/null && \ + /opt/deepseek-reference/bin/sb result diagnosis --help > /dev/null + +RUN apt-get update && apt-get install -y --no-install-recommends rsync && apt-get clean + +ENV PATH="/opt/deepseek-reference/bin:${PATH}" +ENTRYPOINT ["sb"] diff --git a/dockerfile/requirements/deepseek-v2-lite-controller.in b/dockerfile/requirements/deepseek-v2-lite-controller.in new file mode 100644 index 000000000..cef428772 --- /dev/null +++ b/dockerfile/requirements/deepseek-v2-lite-controller.in @@ -0,0 +1,15 @@ +# Additional constraints for the dedicated Python 3.12 controller/reference runtime. +# Torch and torchvision are provided by the digest-pinned GPU base image. +# The NGC Torch build uses the NumPy 1.x ABI; keep its array bridge functional. +# Regenerate from the repository root with bash: +# uv pip compile setup.py dockerfile/requirements/deepseek-v2-lite-reference.txt \ +# dockerfile/requirements/deepseek-v2-lite-controller.in --python-version 3.12 \ +# --python-platform x86_64-unknown-linux-gnu --excludes <(printf 'torch\ntorchvision\n') \ +# --no-header --no-annotate -o dockerfile/requirements/deepseek-v2-lite-controller.txt +numpy==1.26.4 +pandas==2.2.3 +py3nvml==0.2.7 +setuptools==80.10.2 +setuptools-scm==10.3.4 +vcs-versioning==2.5.0 +wheel diff --git a/dockerfile/requirements/deepseek-v2-lite-controller.txt b/dockerfile/requirements/deepseek-v2-lite-controller.txt new file mode 100644 index 000000000..905fbf218 --- /dev/null +++ b/dockerfile/requirements/deepseek-v2-lite-controller.txt @@ -0,0 +1,81 @@ +# Generated for Python 3.12 / Linux x86_64 from setup.py, the reference pins, +# and deepseek-v2-lite-controller.in. The GPU base supplies torch/torchvision. +accelerate==1.2.1 +ansible==14.5.0 +ansible-core==2.21.5 +ansible-runner==2.4.3 +antlr4-python3-runtime==4.9.3 +argcomplete==3.7.2 +attrs==26.1.0 +certifi==2026.10.19 +cffi==2.1.1 +charset-normalizer==3.5.2 +click==8.5.0 +cloudpickle==3.1.2 +colorlog==6.12.0 +contourpy==1.3.3 +cryptography==50.0.2 +cycler==0.12.1 +et-xmlfile==2.0.0 +filelock==4.2.4 +fonttools==4.67.0 +fsspec==2026.9.0 +huggingface-hub==0.26.5 +idna==3.20 +importlib-metadata==9.0.1 +jinja2==3.1.6 +jmespath==1.1.0 +joblib==1.6.0 +jsonlines==4.0.0 +kiwisolver==1.5.1 +knack==0.14.0 +lockfile==0.12.2 +markdown==3.11.2 +markupsafe==3.0.4 +matplotlib==3.11.2 +natsort==8.4.0 +networkx==3.7 +numpy==1.26.4 +omegaconf==2.3.0 +openpyxl==3.1.5 +packaging==26.3 +pandas==2.2.3 +pexpect==4.9.0 +pillow==13.0.0 +prettytable==3.18.0 +protobuf==7.36.2 +pssh @ git+https://github.com/lilydjwg/pssh.git@2dce3d8e45a492985fa1ae0207b6d55afac97c16 +psutil==7.2.2 +ptyprocess==0.7.0 +py3nvml==0.2.7 +pycparser==3.11 +pygments==2.21.0 +pyparsing==3.3.3 +python-daemon==3.1.2 +python-dateutil==2.9.0.post0 +pytz==2026.5 +pyyaml==6.0.3 +regex==2026.9.29 +requests==2.34.2 +resolvelib==1.2.1 +safetensors==0.5.3 +seaborn==0.13.2 +setuptools==80.10.2 +setuptools-scm==10.3.4 +six==1.17.0 +tabulate==0.10.0 +tcping==0.1.1rc1 +tokenizers==0.20.3 +tqdm==4.70.1 +transformers==4.46.3 +types-requests==2.33.0.20261006 +typing-extensions==4.16.0 +tzdata==2026.5 +urllib3==2.8.0 +vcs-versioning==2.5.0 +wcwidth==0.9.3 +wheel==0.48.0 +xlrd==2.0.2 +xlsxwriter==3.2.9 +xmltodict==1.0.4 +zipp==4.1.2 diff --git a/dockerfile/requirements/deepseek-v2-lite-reference.txt b/dockerfile/requirements/deepseek-v2-lite-reference.txt new file mode 100644 index 000000000..e5ab4c95a --- /dev/null +++ b/dockerfile/requirements/deepseek-v2-lite-reference.txt @@ -0,0 +1,5 @@ +# Separate worker environment; do not replace SuperBench's framework dependencies. +transformers==4.46.3 +huggingface-hub==0.26.5 +accelerate==1.2.1 +safetensors==0.5.3 diff --git a/docs/user-tutorial/benchmarks/model-benchmarks.md b/docs/user-tutorial/benchmarks/model-benchmarks.md index c782abbcc..6692c5147 100644 --- a/docs/user-tutorial/benchmarks/model-benchmarks.md +++ b/docs/user-tutorial/benchmarks/model-benchmarks.md @@ -163,3 +163,176 @@ Run GPT pretrain tasks with float32, float16, bfloat16 precisions with [Megatron | megatron-gpt/${precision}_train_mem_allocated | GB | The average GPU memory allocated per iteration. | | megatron-gpt/${precision}_train_max_mem_allocated | GB | The average maximum GPU memory allocated per iteration. | +## Official-checkpoint V2-Lite Generative Inference + +### `deepseek-v2-lite-inference` + +This opt-in standalone MODEL benchmark loads the complete official +`deepseek-ai/DeepSeek-V2-Lite` checkpoint at +`604d5664dddd88a0433dbae533b7fe9472482de0`, with four BF16 weight files totaling +31,413,626,576 bytes. It benchmarks prefill and multi-token cached generation, +not repeated forward passes on randomly initialized weights. No Megatron, +training implementation, quantization or CPU offload is required. + +Use the +[`inference profile`](../../../superbench/config/deepseek-v2-lite-inference.yaml) +as its own entry, with one local controller and one GPU inference replica. +The supplied profile explicitly selects the qualified H100 numerical policy; +it is not a generic CUDA/ROCm acceptance profile. +`batch_size` is the number of simultaneous requests in each measured batch. +The versioned, small fixed-text fixture controls prompt token lengths; it is +not a model-quality or production-request-distribution benchmark. +Generated counts come from actual output token IDs, including EOS when emitted, +not `batch_size * max_new_tokens`. EOS and maximum-length termination remain +enabled; all-first-token-EOS output does not satisfy the cached-decode workload. + +#### Validation Status + +This remains a draft implementation. The explicit `h100_bf16_v6` numerical +method has passed independent-reference checks and all six preregistered H100 +engine windows: 3,216 positive positions pass and all 6,438 fixed fault cases +are rejected. The recorded public runtime completed a download-inclusive cold +bootstrap in 1323.74 seconds. Its opt-in internal package then passed three +ordinary-entrypoint cold repetitions in 1339.17, 1342.39 and 1329.00 seconds, +with complete diagnosis, 97.85-98.32% mean GPU busy and a maximum throughput +deviation of 0.334% from the median. Each repetition includes all numerical checks. +These results qualify the recorded local source/image/profile snapshot, not an +unchanged older PR head, a later rebuilt image, another SKU or production deployment. +Do not replace numerical validation with matching generated tokens or exit code zero. + +The adapter default remains `numerical_policy=strict_fp32`, preserving the +original pointwise FP32 checks. `h100_bf16_v6` is explicitly restricted to one +H100, batch 8, sequence 512, maximum decode 64, two warmup batches and 256 +measured batches. It uses compiled, batch-invariant BF16 inference with the +compressed-MLA implementation; there is no FP32 measured-model fallback. + +The [shipped numerical contract](../../../superbench/config/deepseek-v2-lite-h100-numerics.json) +is bound to an exact SHA256 by the worker. After engine shutdown, independent +official BF16 cached execution measures the precision discrepancy on the same +fixed input prefixes; an FP32 model then recomputes every complete prefix. +For each of the three probability/mass/normalized-log metrics, the budget is +the independently calibrated reference budget plus that input's measured +BF16/FP32 discrepancy. Engine probabilities never determine their own budget. +The same budget must reject half-normalization, temperature-two and wrong-context +faults. Excessive reference uncertainty fails explicitly rather than passing. + +Every runtime numerical check retains all requests and positions at offsets +`0, 1024, 32768, 98304, 130560, 131584`, including short variable-length and +single-request cases. These are windows of one fixed stream, not statistically +independent datasets. Reference qualification also uses retained and fresh +reference-only corpora; 1,152 non-anchor comparisons supplement the canonical +cached-batch anchors. This empirical contract is not a universal BF16 error bound. + +#### Isolated Runtime + +The engine requires vLLM 0.31.0 and a compatible CUDA/ROCm/PyTorch installation. +Do not install vLLM over the existing SuperBench training environment. +Set `runtime_python` to the interpreter in its separate engine environment. +Set `reference_python` to a separate environment containing the pinned +[`official-code reference packages`](../../../dockerfile/requirements/deepseek-v2-lite-reference.txt). +The controller only imports standard-library worker helpers, not vLLM. + +The optional +[`model runtime Dockerfile`](../../../dockerfile/deepseek-v2-lite-inference.dockerfile) +installs the Python SuperBench controller and its `sb` entrypoint in the +reference-compatible environment without replacing the engine's Transformers. +`/opt/vllm/bin/python` selects the engine interpreter; +`/opt/deepseek-reference/bin/python` selects the reference/controller interpreter. +The +[`controller lock`](../../../dockerfile/requirements/deepseek-v2-lite-controller.txt) +retains the base GPU Torch/torchvision installation; its regeneration command is +in the [lock inputs](../../../dockerfile/requirements/deepseek-v2-lite-controller.in). +This is an opt-in model runtime, not the standard compiled microbenchmark image. +CUDA/ROCm registration is not certification of every GPU/runtime combination. +The build checks both interpreters' framework versions and Torch/NumPy array +interoperability. Controller/reference package pins must not replace the engine's +own environment. + +```bash +docker build -f dockerfile/deepseek-v2-lite-inference.dockerfile -t sb-v2lite-inference . +docker run --rm --gpus device=0 --shm-size 32g \ + -v "$PWD/v2lite-results:/results" sb-v2lite-inference exec \ + --config-file superbench/config/deepseek-v2-lite-inference.yaml \ + --output-dir /results/sb-output \ + -C superbench.benchmarks.deepseek-v2-lite-inference.parameters.cache_root=/results/model-cache +``` + +For a separately prepared native installation: +```bash +sb exec --config-file superbench/config/deepseek-v2-lite-inference.yaml +``` + +The command assumes SuperBench and both worker environments are already prepared +and accessible on the same host. In a container, mount the updated checkout +read-only and provide a writable, dedicated result/cache directory. + +#### Correctness And Lifecycle + +The engine exercises variable-length batched prompts, single requests and forced +EOS termination. Outputs must match the submitted prompt token IDs. A separate +unsharded official-code FP32 reference, with TF32 disabled, then checks +prefill and multiple decode steps on the same token prefixes, comparing cached +and complete-prefix logits across the vocabulary and sampled engine top-token +log probabilities and requires greedy token agreement. Sampled engine +probabilities do not constitute an exhaustive +comparison of the engine's full vocabulary logits or all expert routing paths. +Correctness, complete requests, finite timestamps and actual token counts must +all pass; a plausible generated sentence or process exit zero is insufficient. +Numerical records must contain the requested top-20 log probabilities, not only +the selected token. For long selected requests, every generated token is checked +against the cached FP32 reference; full-prefix recomputation checks the first, +second, middle and final positions. A position without full-prefix recomputation +is explicitly marked rather than reporting a fabricated zero cache error. + +Engine model residency is BF16, with no quantized or offloaded fallback. +The router uses FP32 to match the official gate. NVIDIA TF32, vLLM FP32 matmul +precision and Triton FP32 arithmetic are explicitly controlled; these settings +do not turn the BF16 performance workload into full-FP32 inference. +The worker enables `VLLM_RAISE_ON_LOGIT_NANS` before importing vLLM, so NaN +logits fail the run even during measured requests that do not collect log +probabilities. Corrupted request statistics also prevent a successful report. +Inter-request prefix caching and chunked prefill are disabled for this initial +profile; within-request decode state is retained. Changing those policies or +using tensor/expert parallelism requires a separately named validation profile. + +vLLM 0.31.0 reports engine-core monotonic timestamps and provides explicit worker +joining through its engine-core client. This version-specific access is +intentional: incompatible metrics or shutdown APIs fail rather than supplying +default timings. The engine is shut down before the independent reference is +loaded, so their full model copies do not simultaneously consume GPU memory. +The FP32 reference has approximately 62.8GB of parameter storage alone, so this +initial complete validation profile needs an 80GB-class GPU even if the BF16 +engine could fit on a smaller device. That is a reference-profile requirement, +not a claim that the model intrinsically requires H100 or eight GPUs. + +#### Timing And Metrics + +Every invocation uses a new empty HF/Hub/Xet/module cache without deleting shared +caches. One `duration <3600s` covers model download, complete weight hashes, +loading, graph/kernel preparation, warmup, measured generation, reference checks, +result writing and worker teardown. The controller reserves cleanup time and +rejects watchdog exits. Image pulls, dependency installation and controller +installation are separate preparation steps, not certified by the model-cold +timer. + +A dedicated Linux child supervisor reaps worker descendants even when they start +separate sessions. A successful launcher exit with surviving children is rejected. +Worker measurement-phase Unix timestamps allow external telemetry to exclude +setup, correctness and warmup; the timed generation durations use a monotonic +clock. CPU regression tests cover warmup exclusion and mixed EOS/decode counts. + +| Metric | Unit | Scope | +| --- | --- | --- | +| `bf16_inference_step_time` | ms | Mean complete synchronized generation batch | +| `bf16_inference_output_tokens_per_second` | tokens/s | Actual outputs divided by measured batch time | +| `bf16_inference_request_prefill_time` | ms | Engine scheduled-to-first-token interval | +| `bf16_inference_ttft` | ms | Engine first-token latency, including frontend/queue effects | +| `bf16_inference_decode_tpot` | ms/token | First-to-last-token span divided by actual decode intervals | +| `successful_requests` | requests | Completed measured requests | +| `actual_output_tokens` | tokens | Actual measured output IDs, not the configured maximum | +| `end_to_end_seconds` | s | Complete worker launch through teardown/report validation | + +Request prefill/decode timestamps are not isolated GPU kernel timings. +One-token EOS requests contribute to total tokens and latency but not to TPOT. +Keep cold-start time, steady per-GPU utilization and model quality separate; +GPU device busy time is not MFU. diff --git a/superbench/benchmarks/model_benchmarks/__init__.py b/superbench/benchmarks/model_benchmarks/__init__.py index 818469822..af4294512 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.vllm_deepseek_v2_lite import DeepSeekV2LiteInference __all__ = [ 'ModelBenchmark', 'PytorchBERT', 'PytorchGPT2', 'PytorchCNN', 'PytorchLSTM', 'MegatronGPT', 'PytorchLlama', - 'PytorchMixtral' + 'PytorchMixtral', 'DeepSeekV2LiteInference' ] if PytorchMixtral is not None: diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_inference_worker.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_inference_worker.py new file mode 100644 index 000000000..fc312c3e5 --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_inference_worker.py @@ -0,0 +1,340 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Official V2-Lite generation with vLLM, actual token counts and a separate reference.""" + +import argparse +import gc +import math +import os +import signal +import time +from pathlib import Path + +import deepseek_v2_lite_numerics as numerics +from deepseek_v2_lite_utils import ( + FIXED_TEXTS, configure_cache, download_checkpoint, identity_report, interrupt_worker, packed_tokens, read_json, + run_worker, write_json +) + + +def output_record(output, maximum, prompt_token_ids, include_logprobs=False): + """Require finished requests, real tokens and bounded, finite probabilities.""" + if not output.finished or len(output.outputs) != 1 or not output.prompt_token_ids: + raise RuntimeError('Missing or unfinished inference request.') + if list(output.prompt_token_ids) != list(prompt_token_ids): + raise RuntimeError('Engine output is associated with a different prompt.') + completion = output.outputs[0] + tokens = list(completion.token_ids) + if not 0 < len(tokens) <= maximum or completion.finish_reason not in ('stop', 'length'): + raise RuntimeError('Invalid completion count or finish reason.') + record = { + 'prompt_token_ids': list(output.prompt_token_ids), + 'token_ids': tokens, + 'finish_reason': completion.finish_reason, + } + if include_logprobs: + if completion.logprobs is None or len(completion.logprobs) != len(tokens): + raise RuntimeError('Missing per-token engine log probabilities.') + values = [] + for token, probabilities in zip(tokens, completion.logprobs): + if token not in probabilities: + raise RuntimeError('Selected token has no log probability.') + if not 20 <= len(probabilities) <= 21: + raise RuntimeError('Incomplete or oversized top-20 engine log probabilities.') + row = {str(key): float(value.logprob) for key, value in probabilities.items()} + if any(not math.isfinite(value) for value in row.values()): + raise RuntimeError('Nonfinite engine log probability.') + values.append(row) + record['logprobs'] = values + return record + + +def request_times(output): + """Use pinned engine timestamps, not fabricated prefill/decode durations.""" + metrics = output.metrics + if metrics is None or metrics.is_corrupted: + raise RuntimeError('Request statistics are missing or logits were corrupted.') + count = len(output.outputs[0].token_ids) + if metrics.num_generation_tokens != count: + raise RuntimeError('Engine token statistics disagree with actual output.') + prefill = metrics.first_token_ts - metrics.scheduled_ts + ttft = metrics.first_token_latency + decode = metrics.last_token_ts - metrics.first_token_ts + if not math.isfinite(prefill) or prefill <= 0 or not math.isfinite(ttft) or ttft <= 0: + raise RuntimeError('Invalid engine prefill/first-token timestamps.') + if not math.isfinite(decode) or decode < 0 or (count > 1 and decode <= 0): + raise RuntimeError('Invalid cached-decode timestamps.') + return prefill * 1000, ttft * 1000, decode * 1000 / (count - 1) if count > 1 else None + + +def engine_checks(engine, documents, eos): + """Exercise variable-length batches, single requests and EOS termination.""" + from vllm import SamplingParams + + sequences = [packed_tokens(documents, eos, length, 1, index * 7)[0] for index, length in enumerate((16, 23, 32))] + prompts = [{'prompt_token_ids': sequence} for sequence in sequences] + params = SamplingParams(temperature=0, max_tokens=4, logprobs=20, seed=20261015) + batch = engine.generate(prompts, params, use_tqdm=False) + if len(batch) != len(prompts): + raise RuntimeError('Variable-length batch lost a request.') + records = [output_record(output, 4, sequence, True) for output, sequence in zip(batch, sequences)] + for prompt in prompts: + single = engine.generate([prompt], params, use_tqdm=False) + if len(single) != 1: + raise RuntimeError('Single-request execution produced the wrong output count.') + records.append(output_record(single[0], 4, prompt['prompt_token_ids'], True)) + stopped = engine.generate( + [prompts[0]], SamplingParams(temperature=0, max_tokens=4, allowed_token_ids=[eos]), use_tqdm=False + ) + if len(stopped) != 1 or list(stopped[0].outputs[0].token_ids) != [eos]: + raise RuntimeError('EOS was not counted as exactly one generated token.') + output_record(stopped[0], 4, sequences[0]) + if stopped[0].outputs[0].finish_reason != 'stop': + raise RuntimeError('EOS did not terminate the request.') + return records + + +def measured_generation(engine, documents, eos, args): + """Measure complete generation batches, retaining actual request/token counts.""" + import torch + from vllm import SamplingParams + + parameters = SamplingParams(temperature=0, max_tokens=args.max_new_tokens, seed=20261015) + step_times, input_counts, output_counts, prefills, ttfts, tpots = [], [], [], [], [], [] + measurement_start = None + measurement_end = None + for step in range(args.num_warmup + args.num_steps): + sequences = packed_tokens(documents, eos, args.seq_len, args.batch_size, offset=step * args.seq_len) + prompts = [{'prompt_token_ids': sequence} for sequence in sequences] + torch.cuda.synchronize() + if step == args.num_warmup: + measurement_start = time.time() + start = time.monotonic() + outputs = engine.generate(prompts, parameters, use_tqdm=False) + torch.cuda.synchronize() + elapsed = (time.monotonic() - start) * 1000 + if len(outputs) != len(prompts): + raise RuntimeError('Generation returned fewer requests than submitted.') + rows = [output_record(output, args.max_new_tokens, sequence) for output, sequence in zip(outputs, sequences)] + timings = [request_times(output) for output in outputs] + if step >= args.num_warmup: + measurement_end = time.time() + step_times.append(elapsed) + for row, (prefill, ttft, tpot) in zip(rows, timings): + input_counts.append(len(row['prompt_token_ids'])) + output_counts.append(len(row['token_ids'])) + prefills.append(prefill) + ttfts.append(ttft) + if tpot is not None: + tpots.append(tpot) + print( + 'generation_batch={} actual_output_tokens={}'.format(step, sum(len(row['token_ids']) for row in rows)), + flush=True + ) + if not tpots: + raise RuntimeError('The profile never exercised multi-token cached decode.') + return { + 'step_ms': step_times, + 'input_token_counts': input_counts, + 'output_token_counts': output_counts, + 'request_prefill_ms': prefills, + 'ttft_ms': ttfts, + 'decode_tpot_ms': tpots, + 'request_count': len(output_counts), + 'num_gpus': 1, + 'metric_scope': 'engine scheduled-to-first-token and first-to-last-token; not isolated GPU kernel time', + 'measurement_start_unix_seconds': measurement_start, + 'measurement_end_unix_seconds': measurement_end, + } + + +def profile_checks(engine, documents, eos, args, offset=0, capture_all=False): + """Numerically sample the real prompt length and batching, including later decode.""" + from vllm import SamplingParams + + sequences = packed_tokens(documents, eos, args.seq_len, args.batch_size, offset=offset) + prompts = [{'prompt_token_ids': sequence} for sequence in sequences] + parameters = SamplingParams(temperature=0, max_tokens=args.max_new_tokens, logprobs=20, seed=20261015) + outputs = engine.generate(prompts, parameters, use_tqdm=False) + if len(outputs) != len(prompts): + raise RuntimeError('Numerical profile check lost a request.') + records = [] + selected = set(range(len(prompts))) if capture_all else {0, len(prompts) - 1} + for index, (output, sequence) in enumerate(zip(outputs, sequences)): + record = output_record(output, args.max_new_tokens, sequence, index in selected) + if index in selected: + count = len(record['token_ids']) + record['full_prefix_steps'] = sorted({0, min(1, count - 1), count // 2, count - 1}) + record['profile_request_index'] = index + record['profile_batch_size'] = args.batch_size + records.append(record) + return records + + +def qualified_checks(engine, documents, eos, args): + """Reproduce every qualified short-case and complete-batch numerical window.""" + records = [] + for offset in numerics.OFFSETS: + selected = engine_checks(engine, documents, eos) + selected.extend(profile_checks(engine, documents, eos, args, offset=offset, capture_all=True)) + for record in selected: + record['numerical_set_offset'] = offset + records.extend(selected) + return records + + +def prepare_numerical_policy(args): + """Bind the explicit H100 policy before importing the engine.""" + numerics.validate_profile(args) + if args.numerical_policy == numerics.POLICY: + os.environ['VLLM_BATCH_INVARIANT'] = '1' + os.environ['VLLM_MLA_DISABLE'] = '0' + return numerics.load_contract() + return None + + +def numerical_checks(engine, documents, eos, args): + """Check actual engine precision before selecting the declared numerical coverage.""" + import torch + + config = engine.llm_engine.model_config + if config.dtype != torch.bfloat16 or config.quantization: + raise RuntimeError('Engine did not retain the requested unquantized BF16 model.') + if args.numerical_policy == numerics.POLICY: + if not config.use_mla: + raise RuntimeError('The qualified H100 engine must retain its compressed-MLA implementation.') + return qualified_checks(engine, documents, eos, args) + records = engine_checks(engine, documents, eos) + records.extend(profile_checks(engine, documents, eos, args)) + return records + + +def main(): + """Include cold download, engine setup, generation, reference and shutdown.""" + from importlib.metadata import version + + 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('--reference_python', required=True) + parser.add_argument('--batch_size', type=int, default=8) + 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('--max_new_tokens', type=int, default=64) + parser.add_argument('--gpu_memory_utilization', type=float, default=0.8) + parser.add_argument('--numerical_policy', choices=numerics.POLICIES, default='strict_fp32') + 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' + os.environ['NVIDIA_TF32_OVERRIDE'] = '0' + os.environ['VLLM_FLOAT32_MATMUL_PRECISION'] = 'highest' + os.environ['TRITON_F32_DEFAULT'] = 'ieee' + os.environ['VLLM_RAISE_ON_LOGIT_NANS'] = '1' + configure_cache(args.cache_dir) + if args.batch_size < 1 or args.seq_len < 32 or args.num_warmup < 0 or args.num_steps < 1: + raise ValueError('Invalid generative inference dimensions.') + if args.max_new_tokens < 4 or not 0 < args.gpu_memory_utilization <= 0.95 or not 30 < args.duration < 3600: + raise ValueError('Invalid decode length, memory reservation or complete-job duration.') + contract = prepare_numerical_policy(args) + if version('vllm').split('+', 1)[0] != '0.31.0': + raise RuntimeError('This adapter requires the pinned vLLM 0.31.0 statistics/shutdown contract.') + import torch + from vllm import LLM + + if not torch.cuda.is_available(): + raise RuntimeError('CUDA/ROCm GPU unavailable; no CPU or quantized fallback is allowed.') + torch.cuda.set_device(0) + if contract and torch.cuda.get_device_name(0) != contract['calibrated_contract']['runtime_identity']['gpu_name']: + raise ValueError('The selected numerical policy requires its qualified H100 hardware.') + report = identity_report() + download_start = time.monotonic() + checkpoint = download_checkpoint(args.cache_dir) + report['download_verify_seconds'] = time.monotonic() - download_start + engine_start = time.monotonic() + engine = LLM( + model=str(checkpoint), + tokenizer=str(checkpoint), + dtype='bfloat16', + tensor_parallel_size=1, + quantization=None, + cpu_offload_gb=0, + gpu_memory_utilization=args.gpu_memory_utilization, + max_model_len=args.seq_len + args.max_new_tokens, + max_num_seqs=args.batch_size, + enable_prefix_caching=False, + enable_chunked_prefill=False, + disable_log_stats=False, + seed=20261015, + trust_remote_code=False, + hf_overrides={'moe_router_dtype': 'float32'}, + ) + try: + tokenizer = engine.get_tokenizer() + documents = [tokenizer.encode(text, add_special_tokens=False) for text in FIXED_TEXTS] + eos = tokenizer.eos_token_id + report['engine_setup_seconds'] = time.monotonic() - engine_start + records = numerical_checks(engine, documents, eos, args) + measurement_start = time.monotonic() + report.update(measured_generation(engine, documents, eos, args)) + report['generation_seconds'] = time.monotonic() - measurement_start + finally: + # vLLM 0.31.0 exposes worker joining through its engine-core client. + engine.llm_engine.engine_core.shutdown(timeout=10) + del engine + gc.collect() + torch.cuda.empty_cache() + torch.cuda.synchronize() + requests = args.output.parent / 'reference-requests.json' + reference = args.output.parent / 'inference-reference.json' + write_json(requests, records) + reference_start = time.monotonic() + reference_command = ( + [ + args.reference_python, + str(Path(__file__).with_name('deepseek_v2_lite_numerics.py')), '--checkpoint', + str(checkpoint), '--requests', + str(requests), '--output', + str(reference) + ] if contract else [ + args.reference_python, + str(Path(__file__).with_name('deepseek_v2_lite_reference.py')), '--checkpoint', + str(checkpoint), '--mode', 'inference', '--requests', + str(requests), '--output', + str(reference) + ] + ) + run_worker( + reference_command, + args.output.parent / 'reference.log', + args.duration - (time.monotonic() - start) - 20, + ) + result = read_json(reference) + if result.get('correctness_passed') is not True or result.get('teardown_complete') is not True: + raise RuntimeError('Official-code inference reference did not complete.') + if contract: + numerics.validate_reference_result(result) + report['reference'] = result + report['numerical_policy'] = args.numerical_policy + report['batch_invariant'] = os.environ.get('VLLM_BATCH_INVARIANT') == '1' + report['reference_seconds'] = time.monotonic() - reference_start + report['correctness_passed'] = True + report['teardown_complete'] = True + report['vllm_version'] = version('vllm') + report['router_dtype'] = 'float32' + report['float32_matmul_precision'] = 'highest' + report['triton_float32_precision'] = 'ieee' + report['torch_version'] = torch.__version__ + report['gpu_name'] = torch.cuda.get_device_name(0) + report['total_seconds'] = time.monotonic() - start + if report['total_seconds'] >= args.duration: + raise TimeoutError('Generation exceeded the complete-job duration.') + report['status'] = 'success' + write_json(args.output, report) + + +if __name__ == '__main__': + main() diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_numerics.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_numerics.py new file mode 100644 index 000000000..2b2ed6e4b --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_numerics.py @@ -0,0 +1,488 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Independent input-matched BF16 and full-prefix FP32 inference references.""" + +import argparse +import gc +import hashlib +import inspect +import json +import math +import os +from pathlib import Path + +if __package__: + from .deepseek_v2_lite_utils import packed_tokens, read_json, write_json +else: + from deepseek_v2_lite_utils import packed_tokens, read_json, write_json + +METHOD = 'bf16-input-matched-probability-log-v6' +POLICY = 'h100_bf16_v6' +POLICIES = ('strict_fp32', POLICY) +PROFILE = {'batch_size': 8, 'seq_len': 512, 'max_new_tokens': 64, 'num_warmup': 2, 'num_steps': 256} +OFFSETS = (0, 1024, 32768, 98304, 130560, 131584) +CONTRACT_SHA256 = '1f95fe705da2bf8cba1b7846b8a84592add397d6bfc94acf691dbed7756de008' +TOP_K = 20 +SLACK = 1e-6 +METRICS = ('max_probability_error', 'relative_probability_mass_error', 'normalized_logprob_error') +LIMIT_RULE = 'reference calibration budget + input-matched BF16 reference deviation' + + +def canonical_hash(value): + """Hash a policy independently of JSON whitespace.""" + return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':')).encode()).hexdigest() + + +def validate_profile(args): + """Keep the original policy and explicitly restrict the qualified H100 shape.""" + if args.numerical_policy not in POLICIES: + raise ValueError('Unknown V2-Lite numerical policy.') + if args.numerical_policy == POLICY and any(getattr(args, key) != value for key, value in PROFILE.items()): + raise ValueError('The H100 numerical policy requires its complete frozen generation profile.') + + +def load_contract(): + """Require the shipped, qualified artifact rather than caller-supplied tolerances.""" + if not CONTRACT_SHA256: + raise RuntimeError('The H100 numerical policy has not been installed as a qualified contract.') + path = Path(__file__).resolve().parents[2] / 'config/deepseek-v2-lite-h100-numerics.json' + content = path.read_bytes() + if hashlib.sha256(content).hexdigest() != CONTRACT_SHA256: + raise ValueError('The qualified H100 numerical contract changed.') + contract = json.loads(content) + candidate = contract['calibrated_contract'] + payload = {key: value for key, value in candidate.items() if key != 'frozen_limits_sha256'} + if ( + contract.get('status') != 'qualified' or candidate.get('method') != METHOD + or candidate.get('reference_only') is not True or candidate.get('input_matched_limit_rule') != LIMIT_RULE + or canonical_hash(payload) != candidate.get('frozen_limits_sha256') + or candidate.get('qualification_offsets') != list(OFFSETS) + or candidate.get('profile') != {key: PROFILE[key] + for key in ('batch_size', 'seq_len', 'max_new_tokens')} + or candidate.get('qualification_stream') != {key: PROFILE[key] + for key in ('num_warmup', 'num_steps')} + or {row['profile_offset'] + for row in contract.get('qualification', [])} != set(OFFSETS) + or contract.get('reference_validation', {}).get('non_anchor_comparisons', 0) <= 0 + ): + raise ValueError('Incomplete or incompatible H100 numerical qualification.') + return contract + + +def probability_errors(reference_logprobs, observed_logprobs): + """Compare every represented token and the unrepresented probability mass.""" + if not reference_logprobs or len(reference_logprobs) != len(observed_logprobs): + raise ValueError('Probability comparisons must be nonempty and aligned.') + for values in (reference_logprobs, observed_logprobs): + if any(type(value) not in (float, int) or not math.isfinite(value) or value > 0 for value in values): + raise ValueError('Log probabilities must be finite and nonpositive.') + expected = [math.exp(value) for value in reference_logprobs] + actual = [math.exp(value) for value in observed_logprobs] + expected_mass, actual_mass = math.fsum(expected), math.fsum(actual) + if expected_mass <= 0 or max(expected_mass, actual_mass) > 1 + SLACK: + raise ValueError('Invalid represented probability mass.') + differences = [abs(left - right) for left, right in zip(expected, actual)] + variation = 0.5 * (math.fsum(differences) + abs(expected_mass - actual_mass)) + return { + 'max_probability_error': + max(differences), + 'coarsened_total_variation': + variation, + 'relative_probability_mass_error': + variation / expected_mass, + 'reference_mass': + expected_mass, + 'observed_mass': + actual_mass, + 'max_logprob_error': + max(abs(left - right) for left, right in zip(reference_logprobs, observed_logprobs)), + 'normalized_logprob_error': + max( + abs(left - right) / (0.05 + 0.02 * abs(left)) for left, right in zip(reference_logprobs, observed_logprobs) + ), + } + + +def tensor_errors(expected, actual): + """Measure reference variation on both natural top-k supports.""" + results = [ + probability_errors(expected[support].tolist(), actual[support].tolist()) + for support in (expected.topk(TOP_K).indices, actual.topk(TOP_K).indices) + ] + return { + 'max_probability_error': (expected.double().exp() - actual.double().exp()).abs().max().item(), + 'relative_probability_mass_error': max(row['relative_probability_mass_error'] for row in results), + 'coarsened_total_variation': max(row['coarsened_total_variation'] for row in results), + 'normalized_logprob_error': max(row['normalized_logprob_error'] for row in results), + 'greedy_match': expected.argmax().item() == actual.argmax().item(), + } + + +def input_matched_limits(calibrated, reference_errors): + """Never use engine probabilities to determine their own acceptance budget.""" + limits = {} + for metric in METRICS: + budget, deviation = calibrated[metric], reference_errors[metric] + if ( + type(budget) not in (int, float) or not math.isfinite(budget) or budget <= 0 + or type(deviation) not in (int, float) or not math.isfinite(deviation) or deviation < 0 + ): + raise ValueError('Invalid calibrated budget or input-matched reference error.') + limits[metric] = budget + deviation + if limits['relative_probability_mass_error'] >= 0.5: + raise ValueError('Input-matched reference uncertainty cannot distinguish half-normalization.') + return limits + + +def score_probabilities(expected, observed, chosen_token, reference_best, limits): + """Require all three numerical metrics and a reference-bounded greedy choice.""" + if set(expected) != set(observed) or chosen_token not in observed or reference_best not in observed: + raise ValueError('Incomplete aligned probabilities or missing reference/engine greedy token.') + ids = sorted(expected) + metrics = probability_errors([expected[key] for key in ids], [observed[key] for key in ids]) + reasons = [] + for name in METRICS: + bound = limits[name] + if type(bound) not in (int, float) or not math.isfinite(bound) or bound <= 0: + raise ValueError('Invalid frozen numerical bound.') + if metrics[name] > bound: + reasons.append(name) + if observed[chosen_token] + SLACK < max(observed.values()): + reasons.append('reported token is not greedy') + gap = math.exp(expected[reference_best]) - math.exp(expected[chosen_token]) + effective_bound = min( + limits['max_probability_error'], limits['relative_probability_mass_error'] * metrics['reference_mass'] + ) + if gap > 2 * effective_bound + SLACK: + reasons.append('greedy choice exceeds calibrated uncertainty') + return dict( + metrics, + accepted=not reasons, + failures=reasons, + greedy_match=chosen_token == reference_best, + greedy_probability_gap=gap, + greedy_gap_bound=2 * effective_bound, + ) + + +def evaluate_logits(reference_logprobs, observed, chosen_token, limits): + """Do not reduce a top-20 check to its selected token.""" + if not 20 <= len(observed) <= 21: + raise ValueError('Holdout records must retain the complete top-20 probabilities.') + ids = [int(key) for key in observed] + if len(set(ids)) != len(ids) or any(key < 0 or key >= reference_logprobs.numel() for key in ids): + raise ValueError('A reported vocabulary position is duplicated or out of range.') + expected = {key: reference_logprobs[key].item() for key in ids} + actual = {int(key): value for key, value in observed.items()} + reference_best = reference_logprobs.argmax().item() + if reference_best not in actual: + return {'accepted': False, 'failures': ['reference greedy token absent from complete engine top-k']} + return score_probabilities(expected, actual, chosen_token, reference_best, limits) + + +def full_logits(model, token_rows): + """Use a fresh complete prefix for every FP32 oracle position.""" + import torch + + inputs = torch.tensor(token_rows, device='cuda', dtype=torch.long) + output = model(input_ids=inputs, attention_mask=torch.ones_like(inputs), use_cache=False) + logits = output.logits[:, -1, :].float().clone() + del output + if not torch.isfinite(logits).all().item(): + raise RuntimeError('Nonfinite official reference logits.') + return logits + + +def cached_logits(model, cases): + """Retain the complete batch's teacher-forced KV-cache trajectory.""" + import torch + + cache = None + length = len(cases[0]['prompt_token_ids']) + count = len(cases[0]['continuation_ids']) + if any(len(case['prompt_token_ids']) != length or len(case['continuation_ids']) != count for case in cases): + raise ValueError('Reference calibration batches must have matching sequence shapes.') + for step in range(count): + tokens = [case['prompt_token_ids'] if step == 0 else [case['continuation_ids'][step - 1]] for case in cases] + inputs = torch.tensor(tokens, device='cuda', dtype=torch.long) + mask = torch.ones((len(cases), length + step), device='cuda', dtype=torch.long) + output = model(input_ids=inputs, attention_mask=mask, past_key_values=cache, use_cache=True) + cache = output.past_key_values + logits = output.logits[:, -1, :].float().clone() + del output + if not torch.isfinite(logits).all().item(): + raise RuntimeError('Nonfinite cached reference logits.') + yield step, logits + + +def configured_batches(cases, batch_size): + """Use the frozen configured shape and deterministic padding of incomplete groups.""" + if not cases or len({case['id'] for case in cases}) != len(cases) or batch_size < 1: + raise ValueError('Reference batches require nonempty uniquely identified cases and a positive batch size.') + batches = [] + for length, count in sorted({(len(case['prompt_token_ids']), len(case['continuation_ids'])) for case in cases}): + selected = [ + case for case in cases if (len(case['prompt_token_ids']), len(case['continuation_ids'])) == (length, count) + ] + for start in range(0, len(selected), batch_size): + batches.append([selected[(start + index) % len(selected)] for index in range(batch_size)]) + return batches + + +def collect_matched_bf16(model, cases, batch_size): + """Compute reference values without access to any engine probabilities.""" + import torch + + values = {} + with torch.no_grad(): + for batch in configured_batches(cases, batch_size): + records = [[] for _ in batch] + for step, logits in cached_logits(model, batch): + if step != len(records[0]): + raise ValueError('Input-matched reference produced out-of-order decode positions.') + for index, row in enumerate(logits.log_softmax(-1).cpu()): + records[index].append(row.clone()) + for case, rows in zip(batch, records): + if len(rows) != len(case['continuation_ids']): + raise ValueError('Incomplete input-matched reference continuation.') + if case['id'] not in values: + values[case['id']] = torch.stack(rows) + print('Input-matched BF16 completed ' + batch[0]['id'], flush=True) + if set(values) != {case['id'] for case in cases}: + raise ValueError('Input-matched reference omitted a case.') + return values + + +def validate_requests(requests, documents, eos): + """Require every frozen window, complete configured batches and both short execution modes.""" + if not isinstance(requests, list) or len(requests) != len(OFFSETS) * (6 + PROFILE['batch_size']): + raise ValueError('Incomplete H100 numerical request sets.') + short = [packed_tokens(documents, eos, length, 1, index * 7)[0] for index, length in enumerate((16, 23, 32))] + groups = {} + for offset in OFFSETS: + selected = [request for request in requests if request.get('numerical_set_offset') == offset] + expected = short * 2 + packed_tokens(documents, eos, PROFILE['seq_len'], PROFILE['batch_size'], offset) + if len(selected) != len(expected) or [request['prompt_token_ids'] for request in selected] != expected: + raise ValueError('Numerical requests do not match the complete frozen input stream.') + for index, request in enumerate(selected): + maximum = 4 if index < 6 else PROFILE['max_new_tokens'] + tokens = request['token_ids'] + if ( + not isinstance(tokens, list) or not 0 < len(tokens) <= maximum + or any(type(token) is not int or token < 0 for token in tokens) + or len(request['logprobs']) != len(tokens) + ): + raise ValueError('Incomplete or invalid numerical continuation.') + if index >= 6 and ( + request.get('profile_request_index') != index - 6 + or request.get('profile_batch_size') != PROFILE['batch_size'] + ): + raise ValueError('Numerical evidence lost a configured-batch row.') + if not any(len(request['token_ids']) == PROFILE['max_new_tokens'] for request in selected[6:]): + raise ValueError('Numerical window did not exercise the complete decode length.') + groups[offset] = selected + return groups + + +def _validate_window_result(window): + """Check all request positions and corresponding faults in one numerical window.""" + if not isinstance(window, dict): + raise ValueError('Invalid numerical window report.') + positives, negatives = window.get('all_positive_records'), window.get('all_negative_records') + if ( + not isinstance(positives, list) or not positives or not isinstance(negatives, list) + or window.get('positive_positions') != len(positives) + or window.get('negative_positions') != 2 * len(positives) + 1 or len(negatives) != window['negative_positions'] + or window.get('positive_failures') != [] or window.get('negative_failures') != [] + or any(not isinstance(row, dict) or row.get('accepted') is not True for row in positives) + or any(not isinstance(row, dict) or row.get('accepted') is not False for row in negatives) + ): + raise ValueError('H100 numerical reference has missing or failed positions or faults.') + if any(type(row.get(key)) is not int or row[key] < 0 for row in positives for key in ('request', 'step')): + raise ValueError('Invalid numerical request or step indices.') + positions = {(row['request'], row['step']) for row in positives} + if len(positions) != len(positives) or {request for request, _ in positions} != set(range(14)): + raise ValueError('H100 numerical reference lost or duplicated a request position.') + full_decode = False + for request in range(14): + steps = {step for index, step in positions if index == request} + maximum = 4 if request < 6 else PROFILE['max_new_tokens'] + if not 0 < len(steps) <= maximum or steps != set(range(len(steps))): + raise ValueError('H100 numerical reference lost a decode position.') + full_decode |= request >= 6 and len(steps) == PROFILE['max_new_tokens'] + expected_faults = { + (fault, request, step) + for request, step in positions for fault in ('half-normalization', 'temperature-two') + } | {('last-request-context-for-first', 0, 0)} + actual_faults = {(row.get('fault'), row.get('request'), row.get('step')) for row in negatives} + if not full_decode or actual_faults != expected_faults or len(actual_faults) != len(negatives): + raise ValueError('H100 numerical reference omitted complete decode or a required fault.') + return len(positives), len(negatives) + + +def validate_reference_result(report): + """Reject incomplete or substituted serialized reference evidence.""" + if not isinstance(report, dict) or ( + report.get('correctness_passed') is not True or report.get('teardown_complete') is not True + or report.get('numerical_policy') != POLICY or report.get('contract_sha256') != CONTRACT_SHA256 + or report.get('profile_offsets') != list(OFFSETS) or report.get('request_count') != len(OFFSETS) * + (6 + PROFILE['batch_size']) + ): + raise ValueError('Incomplete or mismatched H100 numerical reference result.') + windows = report.get('windows') + if not isinstance(windows, dict) or set(windows) != {str(offset) for offset in OFFSETS}: + raise ValueError('H100 numerical reference omitted a frozen window.') + positive_count, negative_count = 0, 0 + for window in windows.values(): + positives, negatives = _validate_window_result(window) + positive_count += positives + negative_count += negatives + if report.get('positive_positions') != positive_count or report.get('negative_positions') != negative_count: + raise ValueError('H100 numerical reference totals differ from its individual windows.') + + +def evaluate_group(model, requests, matched, limits): + """Keep every positive and all faults, using one reference-only budget per position.""" + import torch + + positives, negatives = [], [] + contexts = {} + with torch.no_grad(): + for request_index, request in enumerate(requests): + for step, chosen in enumerate(request['token_ids']): + prefix = request['prompt_token_ids'] + request['token_ids'][:step] + expected = full_logits(model, [prefix])[0].log_softmax(-1).cpu() + reference_errors = tensor_errors(expected, matched['request-{}'.format(request_index)][step]) + effective = input_matched_limits(limits, reference_errors) + observed = request['logprobs'][step] + result = evaluate_logits(expected, observed, chosen, effective) + positives.append( + dict( + result, + request=request_index, + step=step, + input_reference_errors=reference_errors, + effective_limits=effective + ) + ) + half = {key: value - math.log(2) for key, value in observed.items()} + result = evaluate_logits(expected, half, chosen, effective) + negatives.append(dict(result, fault='half-normalization', request=request_index, step=step)) + wrong = (expected / 2).log_softmax(-1) + ids = wrong.topk(TOP_K).indices.tolist() + result = evaluate_logits( + expected, {str(key): wrong[key].item() + for key in ids}, + wrong.argmax().item(), effective + ) + negatives.append(dict(result, fault='temperature-two', request=request_index, step=step)) + if step == 0 and request_index in (0, len(requests) - 1): + contexts[request_index] = expected + print('Full-prefix FP32 completed request {}'.format(request_index), flush=True) + first, last = contexts[0], contexts[len(requests) - 1] + ids = last.topk(TOP_K).indices.tolist() + result = evaluate_logits( + first, {str(key): last[key].item() + for key in ids}, + last.argmax().item(), positives[0]['effective_limits'] + ) + negatives.append(dict(result, fault='last-request-context-for-first', request=0, step=0)) + return { + 'positive_positions': len(positives), + 'negative_positions': len(negatives), + 'positive_failures': [row for row in positives if not row['accepted']], + 'negative_failures': [row for row in negatives if row['accepted']], + 'all_positive_records': positives, + 'all_negative_records': negatives, + } + + +def run_reference(checkpoint, requests, contract): + """Keep measured BF16 inference separate from both independent reference models.""" + import torch + from importlib.metadata import version + if __package__: + from .deepseek_v2_lite_reference import fixed_documents, load_model + else: + from deepseek_v2_lite_reference import fixed_documents, load_model + + torch.backends.cuda.matmul.allow_tf32 = False + torch.set_float32_matmul_precision('highest') + torch.set_num_threads(1) + torch.cuda.set_device(0) + candidate = contract['calibrated_contract'] + identity = { + 'torch_version': torch.__version__, + 'transformers_version': version('transformers'), + 'gpu_name': torch.cuda.get_device_name(0), + 'reference_loader_sha256': hashlib.sha256(inspect.getsource(load_model).encode()).hexdigest(), + 'tf32_allowed': False, + 'bf16_reduced_precision_reduction': torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction, + } + if identity != candidate['runtime_identity']: + raise ValueError('Reference runtime or hardware differs from the qualified H100 policy.') + documents, eos = fixed_documents(str(checkpoint)) + groups = validate_requests(requests, documents, eos) + model = load_model(str(checkpoint), torch.bfloat16).cuda().eval() + matched = {} + try: + for offset, selected in groups.items(): + cases = [ + { + 'id': 'request-{}'.format(index), + 'prompt_token_ids': request['prompt_token_ids'], + 'continuation_ids': request['token_ids'] + } for index, request in enumerate(selected) + ] + matched[offset] = collect_matched_bf16(model, cases, PROFILE['batch_size']) + finally: + del model + gc.collect() + torch.cuda.empty_cache() + torch.cuda.synchronize() + results = {} + model = load_model(str(checkpoint), torch.float32).cuda().eval() + try: + for offset, selected in groups.items(): + results[str(offset)] = evaluate_group(model, selected, matched[offset], candidate['limits']) + finally: + del model + gc.collect() + torch.cuda.empty_cache() + torch.cuda.synchronize() + passed = all(not row['positive_failures'] and not row['negative_failures'] for row in results.values()) + return { + 'numerical_policy': POLICY, + 'contract_sha256': CONTRACT_SHA256, + 'frozen_limits_sha256': candidate['frozen_limits_sha256'], + 'runtime_identity': identity, + 'profile_offsets': list(OFFSETS), + 'request_count': len(requests), + 'positive_positions': sum(row['positive_positions'] for row in results.values()), + 'negative_positions': sum(row['negative_positions'] for row in results.values()), + 'correctness_passed': passed, + 'teardown_complete': True, + 'windows': results, + } + + +def main(): + """Publish complete numerical evidence and fail the process on any rejected position or fault.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--checkpoint', type=Path, required=True) + parser.add_argument('--requests', type=Path, required=True) + parser.add_argument('--output', type=Path, required=True) + args = parser.parse_args() + os.environ['NVIDIA_TF32_OVERRIDE'] = '0' + os.environ['TORCH_ALLOW_TF32_CUBLAS_OVERRIDE'] = '0' + result = run_reference(args.checkpoint, read_json(args.requests), load_contract()) + if result['correctness_passed'] is True: + validate_reference_result(result) + write_json(args.output, result) + if result['correctness_passed'] is not True: + raise RuntimeError('Input-matched H100 numerical validation rejected a position or accepted a fault.') + + +if __name__ == '__main__': + main() diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_reference.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_reference.py new file mode 100644 index 000000000..1d6e05a6b --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_reference.py @@ -0,0 +1,266 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Unsharded official-code reference, executed in a separate pinned environment.""" + +import argparse +import gc +import os +from pathlib import Path + +from deepseek_v2_lite_utils import ( + FIXED_TEXTS, PARAMETER_COUNT, packed_tokens, read_json, uniform_indices, validate_config, write_json +) + +TRAINING_GRADIENT_PARAMETERS = { + 'model.embed_tokens.weight', + 'model.layers.0.self_attn.q_proj.weight', + 'model.layers.0.self_attn.kv_a_proj_with_mqa.weight', + 'model.layers.0.mlp.down_proj.weight', + 'model.layers.1.mlp.gate.weight', +} + + +def load_model(checkpoint, dtype): + """Load official causal-LM weights with no quantization or model reduction.""" + from importlib.metadata import version + + import torch + from transformers import AutoModelForCausalLM + + if version('transformers') != '4.46.3': + raise RuntimeError('The official-code reference requires transformers==4.46.3.') + validate_config(read_json(Path(checkpoint) / 'config.json')) + model, loading = AutoModelForCausalLM.from_pretrained( + checkpoint, + torch_dtype=dtype, + trust_remote_code=True, + local_files_only=True, + use_safetensors=True, + attn_implementation='eager', + output_loading_info=True, + ) + for key in ('missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs'): + if key not in loading or loading[key]: + raise RuntimeError('Official checkpoint loading failed: {}={!r}.'.format(key, loading.get(key))) + if sum(parameter.numel() for parameter in model.parameters()) != PARAMETER_COUNT: + raise RuntimeError('Loaded parameter count differs from the complete official V2-Lite.') + if not all(parameter.requires_grad for parameter in model.parameters()): + raise RuntimeError('The full-parameter profile must not freeze model parameters.') + if not torch.cuda.is_available(): + raise RuntimeError('CUDA/ROCm GPU unavailable in the reference environment.') + return model + + +def fixed_documents(checkpoint): + """Tokenize the small, versioned natural-text input with the official tokenizer.""" + from transformers import AutoTokenizer + + tokenizer = AutoTokenizer.from_pretrained(checkpoint, local_files_only=True, trust_remote_code=True) + return [tokenizer.encode(text, add_special_tokens=False) for text in FIXED_TEXTS], tokenizer.eos_token_id + + +def _training_gradient_probes(model, gradients): + """Select fixed dense/MLA/router/active-expert positions from the first rank batch.""" + import torch + + required = TRAINING_GRADIENT_PARAMETERS + probes = {} + expert_probe = False + for name, parameter in model.named_parameters(): + gradient = gradients.get(name) + if gradient is None: + continue + selected_expert = ( + not expert_probe and name.startswith('model.layers.1.mlp.experts.') and name.endswith('down_proj.weight') + and torch.count_nonzero(gradient).item() > 0 + ) + if name in required or selected_expert: + flat = gradient.detach().flatten() + nonzero = torch.nonzero(flat, as_tuple=False).flatten()[:512] + spread = torch.tensor(uniform_indices(flat.numel()), device=flat.device, dtype=torch.long) + indices = torch.unique(torch.cat((nonzero, spread))) + values = flat[indices].float().cpu() + if not torch.isfinite(values).all().item(): + raise RuntimeError('Nonfinite reference gradient: {}'.format(name)) + probes[name] = { + 'shape': list(parameter.shape), + 'indices': indices.cpu().tolist(), + 'values': torch.zeros_like(values) + } + if selected_expert: + expert_probe = True + if not required.issubset(probes) or not expert_probe: + raise RuntimeError('Required dense/MLA/router/expert reference gradients are missing.') + return probes + + +def training_reference(model, checkpoint, batch_size=1, seq_len=32, world_size=1): + """Reference exact rank batches without storing unrequested parameter gradients.""" + import torch + + if batch_size < 1 or seq_len < 32 or world_size < 1: + raise ValueError('Invalid training reference profile.') + documents, eos = fixed_documents(checkpoint) + model.train() + model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={'use_reentrant': False}) + tokens = packed_tokens(documents, eos, seq_len, batch_size * world_size) + losses, probes = [], {} + targets = { + name: parameter + for name, parameter in model.named_parameters() if name in TRAINING_GRADIENT_PARAMETERS or + (name.startswith('model.layers.1.mlp.experts.') and name.endswith('down_proj.weight')) + } + for rank in range(world_size): + batch = tokens[rank * batch_size:(rank + 1) * batch_size] + inputs = torch.tensor(batch, device='cuda', dtype=torch.long) + model.zero_grad(set_to_none=True) + output = model(input_ids=inputs, labels=inputs, use_cache=False) + loss = output.loss + del output + if loss is None or not torch.isfinite(loss).item(): + raise RuntimeError('Nonfinite or missing reference causal-LM loss.') + losses.append(loss.item()) + gradients = dict(zip(targets, torch.autograd.grad(loss, tuple(targets.values()), allow_unused=True))) + if not probes: + probes = _training_gradient_probes(model, gradients) + for name, probe in probes.items(): + gradient = gradients[name] + if gradient is None: + if '.experts.' not in name: + raise RuntimeError('Missing reference gradient: {}'.format(name)) + continue + indices = torch.tensor(probe['indices'], device=gradient.device, dtype=torch.long) + values = gradient.detach().flatten()[indices].float().cpu() + if not torch.isfinite(values).all().item(): + raise RuntimeError('Nonfinite reference gradient: {}'.format(name)) + probe['values'] += values / world_size + del gradients, loss, inputs + model.zero_grad(set_to_none=True) + for probe in probes.values(): + probe['values'] = probe['values'].tolist() + return { + 'tokens': tokens, + 'loss': sum(losses) / world_size, + 'loss_per_rank': losses, + 'gradients': probes, + 'batch_size': batch_size, + 'seq_len': seq_len, + 'world_size': world_size, + 'reference_microbatch_size': batch_size, + } + + +def inference_reference(model, requests): + """Compare cached decode to full-prefix logits and engine-selected logprobs.""" + import torch + + if not isinstance(requests, list) or not requests: + raise ValueError('Inference reference requests must be nonempty.') + model.eval() + comparisons = [] + with torch.no_grad(): + for request_index, request in enumerate(requests): + prompt = request['prompt_token_ids'] + completion = request['token_ids'] + logprobs = request['logprobs'] + if not prompt or not completion or len(completion) != len(logprobs): + raise ValueError('Incomplete inference reference request.') + full_prefix_steps = request.get('full_prefix_steps', list(range(len(completion)))) + if ( + not isinstance(full_prefix_steps, list) or not full_prefix_steps + or any(type(step) is not int + for step in full_prefix_steps) or full_prefix_steps != sorted(set(full_prefix_steps)) + or full_prefix_steps[0] != 0 or full_prefix_steps[-1] != len(completion) - 1 + ): + raise ValueError('Full-prefix reference positions must include ordered first and final steps.') + prefix = torch.tensor([prompt], device='cuda', dtype=torch.long) + cache = None + for step, token in enumerate(completion): + attention_mask = torch.ones_like(prefix) + output = model( + input_ids=prefix if step == 0 else prefix[:, -1:], + attention_mask=attention_mask, + past_key_values=cache, + use_cache=True + ) + cache = output.past_key_values + cached = output.logits[:, -1, :].float() + check_full_prefix = step in full_prefix_steps + full = ( + model(input_ids=prefix, attention_mask=attention_mask, use_cache=False).logits[:, -1, :].float() + if check_full_prefix else cached + ) + if not torch.isfinite(cached).all().item() or not torch.isfinite(full).all().item(): + raise RuntimeError('Nonfinite reference logits.') + if check_full_prefix: + torch.testing.assert_close(cached, full, rtol=0.02, atol=0.05) + if full[0].argmax().item() != token: + raise RuntimeError('Engine greedy token differs at request {} step {}.'.format(request_index, step)) + expected = torch.log_softmax(full[0], dim=-1) + ids = [int(value) for value in logprobs[step]] + if token not in ids or not ids: + raise ValueError('Missing selected-token engine log probability.') + actual = torch.tensor([logprobs[step][str(value)] for value in ids], device='cuda') + target = expected[ids] + torch.testing.assert_close( + actual, + target, + rtol=0.02, + atol=0.05, + msg=lambda message: 'Engine/reference request {} step {}:\n{}'.format(request_index, step, message), + ) + comparisons.append( + { + 'request': request_index, + 'step': step, + 'logprob_positions': len(ids), + 'full_prefix_checked': check_full_prefix, + 'cache_max_abs_error': (cached - full).abs().max().item() if check_full_prefix else None, + 'engine_logprob_max_abs_error': (actual - target).abs().max().item(), + } + ) + prefix = torch.cat((prefix, torch.tensor([[token]], device='cuda')), dim=1) + return {'comparisons': comparisons, 'logprob_rtol': 0.02, 'logprob_atol': 0.05} + + +def main(): + """Run a bounded reference and write only numeric/token-ID evidence.""" + import torch + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--checkpoint', required=True) + parser.add_argument('--mode', choices=['training', 'inference'], required=True) + parser.add_argument('--requests') + parser.add_argument('--output', required=True) + parser.add_argument('--batch_size', type=int, default=1) + parser.add_argument('--seq_len', type=int, default=32) + parser.add_argument('--world_size', type=int, default=1) + args = parser.parse_args() + torch.cuda.set_device(0) + os.environ['TORCH_ALLOW_TF32_CUBLAS_OVERRIDE'] = '0' + torch.backends.cuda.matmul.allow_tf32 = False + dtype = torch.bfloat16 if args.mode == 'training' else torch.float32 + model = load_model(args.checkpoint, dtype).cuda() + try: + if args.mode == 'training': + result = training_reference(model, args.checkpoint, args.batch_size, args.seq_len, args.world_size) + else: + if not args.requests: + raise ValueError('--requests is required for inference reference.') + result = inference_reference(model, read_json(Path(args.requests))) + torch.cuda.synchronize() + finally: + del model + gc.collect() + torch.cuda.empty_cache() + torch.cuda.synchronize() + result['correctness_passed'] = True + result['teardown_complete'] = True + result['reference_dtype'] = str(dtype) + result['tf32_allowed'] = False + write_json(Path(args.output), result) + + +if __name__ == '__main__': + main() diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_utils.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_utils.py new file mode 100644 index 000000000..ca73360ef --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_utils.py @@ -0,0 +1,364 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Checkpoint, input and subprocess contracts for the fixed V2-Lite workload.""" + +import hashlib +import json +import math +import os +import signal +import subprocess +import sys +import time +from pathlib import Path +from typing import Dict, List, Sequence + +MODEL_ID = 'deepseek-ai/DeepSeek-V2-Lite' +REVISION = '604d5664dddd88a0433dbae533b7fe9472482de0' +PARAMETER_COUNT = 15706484224 +WEIGHT_FILES = { + 'model-00001-of-000004.safetensors': + (8594887408, '0d7e9f39bde40111a4c0f390b87497dce4565cf578d916395e6b2c7851f1e8da'), + 'model-00002-of-000004.safetensors': + (8591757448, 'e0656832b0d594b4a64cad40ff8465231de6ed44c854f74f6b217797660aa4bb'), + 'model-00003-of-000004.safetensors': + (8590718520, '843ec689624f3a520526e040f0326c4dc9865e8172942ca98a084fe136fdb21a'), + 'model-00004-of-000004.safetensors': + (5636263200, 'cfb51658f67cedfbbc4d62ad14187830ceec8ee82c788c5f718feea98905ef31'), +} +WEIGHT_BYTES = sum(size for size, _ in WEIGHT_FILES.values()) +EXPECTED_CONFIG = { + 'hidden_size': 2048, + 'num_hidden_layers': 27, + 'num_attention_heads': 16, + 'intermediate_size': 10944, + 'moe_intermediate_size': 1408, + 'n_routed_experts': 64, + 'n_shared_experts': 2, + 'num_experts_per_tok': 6, + 'first_k_dense_replace': 1, + 'kv_lora_rank': 512, + 'q_lora_rank': None, + 'qk_nope_head_dim': 128, + 'qk_rope_head_dim': 64, + 'v_head_dim': 128, + 'vocab_size': 102400, + 'seq_aux': True, + 'aux_loss_alpha': 0.001, + 'attention_dropout': 0.0, +} +FIXED_TEXTS = ( + 'The engineering team measures a system before changing its configuration. ' + 'Each measurement records the input, the software version, and the observation time.', + 'A warehouse receives several shipments each morning. Workers check the labels, ' + 'sort the packages by destination, and keep a record of damaged items.', + 'A weather station samples temperature and wind speed at regular intervals. ' + 'Missing readings are reported explicitly instead of being replaced with zero.', + 'The library contains books about science, history, and music. Readers can search ' + 'the catalog, reserve an available book, and return it at the front desk.', + 'A numerical experiment compares two implementations on the same input. ' + 'The result includes the error tolerance and every failed comparison.', + 'A small garden has three rows of vegetables and a rainwater tank. ' + 'The gardener checks soil moisture before deciding how much water to use.', + 'The train arrives at the northern platform at eight in the morning. ' + 'Passengers check their tickets and leave space for people getting off.', + 'A computer processes a sequence of tokens using a language model. ' + 'Training computes a loss and gradients, while generation reuses attention state.', +) +INPUT_SHA256 = hashlib.sha256('\n'.join(FIXED_TEXTS).encode('utf-8')).hexdigest() + + +def read_json(path: Path): + """Read a JSON document without accepting nonfinite JSON constants.""" + def reject_constant(value): + raise ValueError('Nonfinite JSON constant: {}'.format(value)) + + with path.open() as stream: + return json.load(stream, parse_constant=reject_constant) + + +def write_json(path: Path, document) -> None: + """Write a complete report atomically, rejecting nonfinite numbers.""" + temporary = path.with_suffix(path.suffix + '.tmp') + with temporary.open('w') as stream: + json.dump(document, stream, indent=2, allow_nan=False) + stream.write('\n') + temporary.replace(path) + + +def validate_config(config) -> None: + """Reject a reduced, quantized or different model configuration.""" + if not isinstance(config, dict) or config.get('model_type') != 'deepseek_v2': + raise ValueError('Expected the official DeepSeek-V2 configuration.') + for key, expected in EXPECTED_CONFIG.items(): + if key not in config or config[key] != expected: + raise ValueError('Official V2-Lite {} must be {!r}, got {!r}.'.format(key, expected, config.get(key))) + if config.get('quantization_config') is not None: + raise ValueError('This profile does not accept quantized checkpoints.') + + +def configure_cache(cache: Path) -> None: + """Isolate all model caches without reading or removing shared caches.""" + cache.mkdir(parents=True, exist_ok=True) + if any(cache.iterdir()): + raise ValueError('Cold-start cache must be empty: {}'.format(cache)) + set_cache_environment(cache) + + +def set_cache_environment(cache: Path) -> None: + """Select the same isolated cache in each distributed worker.""" + for variable, directory in { + 'HF_HOME': 'hf', + 'HF_HUB_CACHE': 'hub', + 'HF_XET_CACHE': 'xet', + 'HF_MODULES_CACHE': 'modules', + 'TRANSFORMERS_CACHE': 'transformers', + }.items(): + os.environ[variable] = str(cache / directory) + os.environ['HF_HUB_DISABLE_IMPLICIT_TOKEN'] = '1' + os.environ['HF_HUB_DISABLE_TELEMETRY'] = '1' + + +def verify_checkpoint(checkpoint: Path) -> None: + """Verify the complete fixed checkpoint, its index and every weight hash.""" + validate_config(read_json(checkpoint / 'config.json')) + index = read_json(checkpoint / 'model.safetensors.index.json') + if not isinstance(index, dict) or not isinstance(index.get('weight_map'), dict): + raise ValueError('Missing checkpoint weight map.') + if set(index['weight_map'].values()) != set(WEIGHT_FILES): + raise ValueError('Checkpoint index does not describe the four official weight shards.') + for filename, (size, expected_hash) in WEIGHT_FILES.items(): + path = checkpoint / filename + if not path.is_file() or path.stat().st_size != size: + raise ValueError('Missing or incorrectly sized checkpoint shard: {}'.format(filename)) + digest = hashlib.sha256() + with path.open('rb') as stream: + for block in iter(lambda: stream.read(8 * 1024 * 1024), b''): + digest.update(block) + if digest.hexdigest() != expected_hash: + raise ValueError('Checkpoint SHA256 mismatch: {}'.format(filename)) + + +def download_checkpoint(cache: Path) -> Path: + """Download and verify official weights before any GPU model construction.""" + from huggingface_hub import snapshot_download + + checkpoint = cache / 'checkpoint' + snapshot_download( + repo_id=MODEL_ID, + revision=REVISION, + local_dir=str(checkpoint), + cache_dir=str(cache / 'hub'), + allow_patterns=list(WEIGHT_FILES) + [ + 'config.json', 'generation_config.json', 'model.safetensors.index.json', 'tokenizer*', + 'special_tokens_map.json', '*.py' + ], + token=False, + max_workers=4, + ) + verify_checkpoint(checkpoint) + return checkpoint + + +def packed_tokens(documents: Sequence[Sequence[int]], + eos: int, + length: int, + count: int, + offset: int = 0) -> List[List[int]]: + """Pack deterministic real-text tokens without padding a pressure workload.""" + if length < 2 or count < 1 or offset < 0 or not documents or eos < 0: + raise ValueError('Invalid packed-input dimensions or documents.') + stream: List[int] = [] + for document in documents: + if not document or any(type(token) is not int or token < 0 for token in document): + raise ValueError('Each document must contain nonnegative integer token IDs.') + stream.extend(document) + stream.append(eos) + return [ + [stream[(offset + row * length + column) % len(stream)] for column in range(length)] for row in range(count) + ] + + +def numeric_series(report, name: str, count: int, positive: bool = True) -> List[float]: + """Require a complete finite metric series, never a default or sentinel.""" + values = report.get(name) if isinstance(report, dict) else None + if not isinstance(values, list) or len(values) != count: + raise ValueError('Expected {} {} samples.'.format(count, name)) + if any( + isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or + (positive and value <= 0) for value in values + ): + raise ValueError('Invalid numeric metric: {}'.format(name)) + return [float(value) for value in values] + + +def uniform_indices(length: int, count: int = 256) -> List[int]: + """Sample large tensor offsets with integer arithmetic, never FP32 rounding.""" + if length < 1 or count < 2: + raise ValueError('Invalid tensor length or sample count.') + return [position * (length - 1) // (count - 1) for position in range(count)] + + +def _owned_children() -> List[int]: + """Read the dedicated supervisor's direct and adopted children.""" + path = Path('/proc/self/task/{}/children'.format(os.getpid())) + return [int(pid) for pid in path.read_text().split()] + + +def _reap_children() -> None: + """Reap exited owned children so no stale PID is treated as running.""" + while True: + try: + pid, _ = os.waitpid(-1, os.WNOHANG) + except ChildProcessError: + return + if pid == 0: + return + + +def _stop_children() -> None: + """Reap all job descendants, including ranks that created new sessions.""" + graceful_deadline = time.monotonic() + 10 + deadline = graceful_deadline + 5 + while True: + children = _owned_children() + if not children: + return + current = time.monotonic() + if current >= deadline: + raise RuntimeError('Owned worker descendants did not exit: {}.'.format(children)) + signum = signal.SIGTERM if current < graceful_deadline else signal.SIGKILL + for pid in children: + try: + os.kill(pid, signum) + except ProcessLookupError: + pass + _reap_children() + time.sleep(0.02) + + +def supervise_worker(command: List[str], timeout: float, parent_pid: int) -> int: + """Contain Linux worker descendants in a separate single-threaded supervisor.""" + import ctypes + + if sys.platform != 'linux': + raise RuntimeError('The isolated model worker supervisor requires Linux.') + libc = ctypes.CDLL(None, use_errno=True) + interrupted = False + + def stop(signum, frame): + nonlocal interrupted + interrupted = True + + signal.signal(signal.SIGTERM, stop) + signal.signal(signal.SIGINT, stop) + # Adopt orphaned rank sessions and clean up if the controller itself dies. + for option, value in [(36, 1), (1, signal.SIGTERM)]: # PR_SET_CHILD_SUBREAPER, PR_SET_PDEATHSIG + if libc.prctl(option, ctypes.c_ulong(value), ctypes.c_ulong(0), ctypes.c_ulong(0), ctypes.c_ulong(0)) != 0: + error = ctypes.get_errno() + raise OSError(error, os.strerror(error)) + if os.getppid() != parent_pid: + return 124 + deadline = time.monotonic() + timeout + process = subprocess.Popen(command) + try: + while process.poll() is None: + if interrupted or time.monotonic() >= deadline: + return 124 + time.sleep(0.02) + code = process.wait() + _reap_children() + if code == 0 and _owned_children(): + print('Worker exited with live descendant processes.', file=sys.stderr, flush=True) + return 125 + return code if code >= 0 else 128 - code + finally: + _stop_children() + process.wait() + + +def interrupt_worker(signum, frame) -> None: + """Unwind subprocess waits so nested reference workers are cleaned up.""" + raise TimeoutError('Model worker interrupted by signal {}.'.format(signum)) + + +def run_worker(command: List[str], log: Path, timeout: float) -> None: + """Supervise the whole worker tree under one deadline, preserving failure logs.""" + if not math.isfinite(timeout) or timeout <= 0: + raise TimeoutError('No time remains for the worker.') + if not command: + raise ValueError('The model worker command must not be empty.') + supervisor = [ + sys.executable, + str(Path(__file__).resolve()), + '--worker-timeout', + str(timeout), + '--parent-pid', + str(os.getpid()), + '--', + *command, + ] + with log.open('w') as stream: + process = subprocess.Popen(supervisor, stdout=stream, stderr=subprocess.STDOUT, start_new_session=True) + try: + try: + code = process.wait(timeout=timeout + 20) + except subprocess.TimeoutExpired as error: + raise TimeoutError('Model worker supervisor exceeded its cleanup deadline.') from error + if code == 124: + raise TimeoutError('Model worker exceeded the download-inclusive deadline.') + if code == 125: + raise RuntimeError('Model worker left descendant processes running; see {}.'.format(log)) + if code != 0: + raise RuntimeError('Model worker exited with code {}; see {}.'.format(code, log)) + finally: + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=20) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + raise RuntimeError('Model worker supervisor did not complete descendant cleanup.') + + +def identity_report() -> Dict[str, object]: + """Describe the fixed model and input contract without generated text.""" + return { + 'model_id': MODEL_ID, + 'revision': REVISION, + 'weight_bytes': WEIGHT_BYTES, + 'weight_sha256': {name: digest + for name, (_, digest) in WEIGHT_FILES.items()}, + 'parameter_count': PARAMETER_COUNT, + 'precision': 'bfloat16', + 'input_dataset': 'fixed-text-v1', + 'input_sha256': INPUT_SHA256, + 'cold_cache': True, + } + + +def validate_identity(report) -> None: + """Require a successful official-model report before accepting any metrics.""" + expected = identity_report() + if not isinstance(report, dict) or report.get('status') != 'success': + raise ValueError('Worker did not produce a successful model report.') + if any(report.get(key) != value for key, value in expected.items()): + raise ValueError('Worker report does not match the official checkpoint/input contract.') + if report.get('correctness_passed') is not True or report.get('teardown_complete') is not True: + raise ValueError('Correctness or worker teardown was not completed.') + + +if __name__ == '__main__': + import argparse + + parser = argparse.ArgumentParser(description='Supervise one isolated model worker command.') + parser.add_argument('--worker-timeout', type=float, required=True) + parser.add_argument('--parent-pid', type=int, required=True) + parser.add_argument('command', nargs=argparse.REMAINDER) + arguments = parser.parse_args() + worker_command = arguments.command[1:] if arguments.command[:1] == ['--'] else arguments.command + if not worker_command or not math.isfinite(arguments.worker_timeout) or arguments.worker_timeout <= 0: + parser.error('A worker command and finite positive timeout are required.') + sys.exit(supervise_worker(worker_command, arguments.worker_timeout, arguments.parent_pid)) diff --git a/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py b/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py new file mode 100644 index 000000000..a11c6551d --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py @@ -0,0 +1,165 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""SuperBench adapter for isolated official-checkpoint V2-Lite generation.""" + +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 import deepseek_v2_lite_numerics as numerics +from superbench.benchmarks.model_benchmarks.deepseek_v2_lite_utils import ( + numeric_series, read_json, run_worker, validate_identity +) + + +class DeepSeekV2LiteInference(Benchmark): + """Benchmark one BF16 inference replica, not a training or forward-only loop.""" + def __init__(self, name, parameters=''): + """Initialize without importing vLLM into the legacy SuperBench process.""" + super().__init__(name, parameters) + self._benchmark_type = BenchmarkType.MODEL + + def add_parser_arguments(self): + """Configure one separately timed checkpoint and generation 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('--reference_python', type=str, default='/opt/deepseek-reference/bin/python') + self._parser.add_argument('--cache_root', type=str, default='model-cache') + self._parser.add_argument('--batch_size', type=int, default=8) + self._parser.add_argument('--seq_len', type=int, default=512) + self._parser.add_argument('--max_new_tokens', type=int, default=64) + self._parser.add_argument('--num_warmup', type=int, default=2) + self._parser.add_argument('--num_steps', type=int, default=8) + self._parser.add_argument('--gpu_memory_utilization', type=float, default=0.8) + self._parser.add_argument('--numerical_policy', choices=numerics.POLICIES, default='strict_fp32') + + def _preprocess(self): + """Reject duplicate launchers and unsupported profile settings explicitly.""" + if not super()._preprocess(): + return False + args = self._args + try: + world_size = int(os.environ.get('WORLD_SIZE', os.environ.get('OMPI_COMM_WORLD_SIZE', '1'))) + except ValueError: + world_size = 0 + invalid = ( + args.run_count != 1 or not 30 < args.duration < 3600 or args.batch_size < 1 or args.seq_len < 32 + or args.max_new_tokens < 4 or args.num_warmup < 0 or args.num_steps < 1 + or not 0 < args.gpu_memory_utilization <= 0.95 or world_size != 1 + ) + if invalid: + logger.error('V2-Lite inference requires one local replica and a valid BF16 generation/deadline profile.') + self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) + return False + try: + numerics.validate_profile(args) + if args.numerical_policy == numerics.POLICY: + numerics.load_contract() + except (OSError, ValueError, RuntimeError) as error: + logger.error('V2-Lite numerical policy is unavailable or incompatible: %s', error) + self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) + return False + return True + + def _worker_command(self, job): + """Keep executable paths and every worker argument separate.""" + args = self._args + return [ + args.runtime_python, + str(Path(__file__).with_name('deepseek_v2_lite_inference_worker.py')), + '--cache_dir', + str(job / 'cache'), + '--output', + str(job / 'report.json'), + '--reference_python', + args.reference_python, + '--batch_size', + str(args.batch_size), + '--seq_len', + str(args.seq_len), + '--max_new_tokens', + str(args.max_new_tokens), + '--num_warmup', + str(args.num_warmup), + '--num_steps', + str(args.num_steps), + '--gpu_memory_utilization', + str(args.gpu_memory_utilization), + '--numerical_policy', + args.numerical_policy, + '--duration', + str(args.duration), + ] + + def _validate_numerical_report(self, report): + """Require complete evidence for the explicitly selected H100 policy.""" + if self._args.numerical_policy == numerics.POLICY: + if report.get('numerical_policy') != numerics.POLICY or report.get('batch_invariant') is not True: + raise ValueError('The worker did not execute the selected H100 numerical policy.') + numerics.validate_reference_result(report.get('reference')) + + def _benchmark(self): + """Accept actual request/token counters and complete numeric validation.""" + start = time.monotonic() + try: + root = Path(self._args.cache_root).resolve() + root.mkdir(parents=True, exist_ok=True) + job = Path(tempfile.mkdtemp(prefix='v2lite-inference-', dir=str(root))) + logger.info('V2-Lite inference evidence and isolated cache: %s', job) + run_worker(self._worker_command(job), job / 'worker.log', self._args.duration - 20) + report = read_json(job / 'report.json') + validate_identity(report) + self._validate_numerical_report(report) + requests = self._args.num_steps * self._args.batch_size + steps = numeric_series(report, 'step_ms', self._args.num_steps) + inputs = numeric_series(report, 'input_token_counts', requests) + outputs = numeric_series(report, 'output_token_counts', requests) + prefills = numeric_series(report, 'request_prefill_ms', requests) + ttfts = numeric_series(report, 'ttft_ms', requests) + decode_count = sum(value > 1 for value in outputs) + tpots = numeric_series(report, 'decode_tpot_ms', decode_count) + if decode_count == 0 or report.get('request_count') != requests or report.get('num_gpus') != 1: + raise ValueError('Generation did not complete the requested replica/cache workload.') + if any(value != self._args.seq_len for value in inputs): + raise ValueError('Input token counts differ from the frozen prompt shape.') + if any(not value.is_integer() or value > self._args.max_new_tokens for value in outputs): + raise ValueError('Actual generated token counts are invalid.') + total = time.monotonic() - start + if total >= self._args.duration: + raise TimeoutError('Complete inference job exceeded its duration.') + for name, values in [ + ('step_time', steps), ('request_prefill_time', prefills), ('ttft', ttfts), ('decode_tpot', tpots), + ('input_token_count', inputs), ('output_token_count', outputs) + ]: + metric = 'bf16_inference_' + 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_inference_output_tokens_per_second', sum(outputs) * 1000 / sum(steps)) + self._result.add_result('successful_requests', requests) + self._result.add_result('actual_output_tokens', sum(outputs)) + self._result.add_result('end_to_end_seconds', total) + self._result.add_result('checkpoint_bytes', report['weight_bytes']) + if self._args.numerical_policy == numerics.POLICY: + self._result.add_result('numerical_reference_positions', report['reference']['positive_positions']) + self._result.add_result('numerical_fault_rejections', report['reference']['negative_positions']) + return True + except TimeoutError as error: + logger.error('V2-Lite inference timeout: %s', error) + self._result.set_return_code(ReturnCode.KILLED_BY_TIMEOUT) + return False + except (OSError, ValueError, RuntimeError) as error: + logger.error('V2-Lite inference failed: %s', error) + self._result.set_return_code(ReturnCode.RUNTIME_EXCEPTION_ERROR) + return False + + +BenchmarkRegistry.register_benchmark('deepseek-v2-lite-inference', DeepSeekV2LiteInference, platform=Platform.CUDA) +BenchmarkRegistry.register_benchmark('deepseek-v2-lite-inference', DeepSeekV2LiteInference, platform=Platform.ROCM) diff --git a/superbench/config/deepseek-v2-lite-h100-numerics.json b/superbench/config/deepseek-v2-lite-h100-numerics.json new file mode 100644 index 000000000..b245bd522 --- /dev/null +++ b/superbench/config/deepseek-v2-lite-h100-numerics.json @@ -0,0 +1,124 @@ +{ + "status": "qualified", + "calibrated_contract": { + "method": "bf16-input-matched-probability-log-v6", + "status": "candidate-not-heldout-qualified", + "reference_only": true, + "model_id": "deepseek-ai/DeepSeek-V2-Lite", + "revision": "604d5664dddd88a0433dbae533b7fe9472482de0", + "profile": { + "batch_size": 8, + "seq_len": 512, + "max_new_tokens": 64 + }, + "top_k": 20, + "limits": { + "max_probability_error": 0.07284170527726544, + "relative_probability_mass_error": 0.13143301942660637, + "normalized_logprob_error": 7.25253417079409 + }, + "probability_slack": 1e-06, + "calibration_cases_sha256": "0f853d935a28e6b4fbcf2454d47e0bf6872aa94aea931494f46d9f84a9df393d", + "script_sha256": "2dd64484cb0e0cbc00d726899c0b716f2c6326eb95b33ac9e2a6bdfd8f016222", + "runtime_identity": { + "torch_version": "2.13.0+cu130", + "transformers_version": "4.46.3", + "gpu_name": "NVIDIA H100 80GB HBM3", + "reference_loader_sha256": "19539a42ea67dc369b41c5ba5078ff3725dcac163057664937aa32413b5a49d6", + "tf32_allowed": false, + "bf16_reduced_precision_reduction": true + }, + "fp32_oracle": "full-prefix at every position; no reference KV cache", + "logprob_normalization": { + "atol_scale": 0.05, + "rtol_scale": 0.02 + }, + "qualification_offsets": [ + 0, + 1024, + 32768, + 98304, + 130560, + 131584 + ], + "qualification_stream": { + "num_warmup": 2, + "num_steps": 256 + }, + "continuation_modes": [ + "teacher-forced", + "fp32-greedy" + ], + "reference_validation_required": true, + "input_matched_limit_rule": "reference calibration budget + input-matched BF16 reference deviation", + "input_matched_reference": "Official BF16 cached execution in configured shape-matched batches", + "reference_holdout_corpora": [ + "retained-v5", + "fresh-v6" + ], + "qualification_required": [ + "different performance inputs", + "half-normalization faults", + "temperature faults", + "wrong-context faults", + "malformed/missing results" + ], + "frozen_limits_sha256": "f0916bfcdbfdac1ea3c888305cc0cb9641756b29559b57640cb8cbb02ee56533" + }, + "reference_validation": { + "report_sha256": "819ef3e6180130828c956d05a73b314244fcd142568dab2ba1b4153bf3386791", + "holdout_cases_sha256": "5c0cd12116cd876ffc01fcbd1d010e5df6226556705ec6701a0ea5ce3715631d", + "comparisons": 2176, + "non_anchor_comparisons": 1152 + }, + "qualification": [ + { + "profile_offset": 0, + "requests_sha256": "5bf572df5e5874bfb2e1c30c5778ff3cd93250e7d029d87f6967cd7706db6f35", + "report_sha256": "210d10db88b5f0ce01957047532fabcfd95cd2ea22772e939648f08088766f0b", + "positive_positions": 536, + "negative_positions": 1073, + "near_tie_positions": 0 + }, + { + "profile_offset": 1024, + "requests_sha256": "b12aeb6af0bb65fbb762e38c775e15dfcf16362491a37c138df7e60599f2876b", + "report_sha256": "7395f7d9e989ddac14e5ea528af8bd24fef9f09215e99bb9700a1aab8a3bfd6c", + "positive_positions": 536, + "negative_positions": 1073, + "near_tie_positions": 0 + }, + { + "profile_offset": 32768, + "requests_sha256": "8f0b5215ed3f5a5752bfa8157b86110cb806d644233d3f312e88adae04d57d5a", + "report_sha256": "9ffdf898774506893027f1991bb38f4f88b47318a9472dd28012a63b493249ed", + "positive_positions": 536, + "negative_positions": 1073, + "near_tie_positions": 0 + }, + { + "profile_offset": 98304, + "requests_sha256": "d352a40c0e315e01222910249f0de56de8185b544a1c96fb1629f1efa73b8c54", + "report_sha256": "5a6d0675c3a9ee5ce1e6a34224c041c7e315fa3c0e15d44ea3d8f52294a0f3b9", + "positive_positions": 536, + "negative_positions": 1073, + "near_tie_positions": 0 + }, + { + "profile_offset": 130560, + "requests_sha256": "df9b950e343ab6d7c0f77bfd563159d33e8bfb9793600b9fefc906413da58dd5", + "report_sha256": "dd0aa947578c603665e6701b3b50b7435dd8cf7a541cac4b351d4a3282c1ce9a", + "positive_positions": 536, + "negative_positions": 1073, + "near_tie_positions": 0 + }, + { + "profile_offset": 131584, + "requests_sha256": "e7d26e1f2316c46458e4c6ca884388c5af5a82ffdfbaca20e177a1ac1a55ee8f", + "report_sha256": "4b78db3a28ed12001d750a16e47f74c62e1692c2de3bcff781b41cf1a2150363", + "positive_positions": 536, + "negative_positions": 1073, + "near_tie_positions": 1 + } + ] +} diff --git a/superbench/config/deepseek-v2-lite-inference.yaml b/superbench/config/deepseek-v2-lite-inference.yaml new file mode 100644 index 000000000..ab4f7ca88 --- /dev/null +++ b/superbench/config/deepseek-v2-lite-inference.yaml @@ -0,0 +1,27 @@ +version: v0.12 +superbench: + enable: [deepseek-v2-lite-inference] + monitor: + enable: true + sample_duration: 1 + sample_interval: 1 + benchmarks: + deepseek-v2-lite-inference: + enable: true + modes: + - name: local + proc_num: 1 + parallel: false + prefix: CUDA_VISIBLE_DEVICES=0 + timeout: 3600 + parameters: + runtime_python: /opt/vllm/bin/python + reference_python: /opt/deepseek-reference/bin/python + cache_root: /data/deepseek-v2-lite + batch_size: 8 + seq_len: 512 + max_new_tokens: 64 + numerical_policy: h100_bf16_v6 + num_warmup: 2 + num_steps: 256 + duration: 3300 diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_inference_worker.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_inference_worker.py new file mode 100644 index 000000000..7cd946b9f --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_inference_worker.py @@ -0,0 +1,502 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""CPU tests for generation counters and the pinned engine timing contract.""" + +import importlib.util +import json +import sys +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + + +@pytest.fixture +def worker(monkeypatch): + """Load the standalone worker without requiring a vLLM or CUDA installation.""" + directory = Path(__file__).resolve().parents[3] / 'superbench/benchmarks/model_benchmarks' + monkeypatch.syspath_prepend(str(directory)) + spec = importlib.util.spec_from_file_location( + 'v2lite_generation_test', directory / 'deepseek_v2_lite_inference_worker.py' + ) + if spec is None or spec.loader is None: + raise RuntimeError('Cannot load the standalone generation worker.') + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def response(tokens=(7, 8)): + """Construct engine-response fixtures without simulating GPU success.""" + return SimpleNamespace( + finished=True, + prompt_token_ids=[1, 2, 3], + outputs=[ + SimpleNamespace( + token_ids=list(tokens), + finish_reason='length', + logprobs=[ + {key: SimpleNamespace(logprob=-0.5 if key == token else -2.0) + for key in set(range(20)) | {token}} for token in tokens + ] + ) + ], + metrics=SimpleNamespace( + is_corrupted=False, + num_generation_tokens=len(tokens), + scheduled_ts=10.0, + first_token_ts=10.25, + last_token_ts=10.5, + first_token_latency=0.4 + ), + ) + + +def test_actual_output_tokens_not_maximum(worker): + """Count emitted token IDs instead of treating max_tokens as completed work.""" + result = worker.output_record(response(), 64, [1, 2, 3], True) + assert result['token_ids'] == [7, 8] + assert len(result['token_ids']) == 2 + assert result['logprobs'][0]['7'] == result['logprobs'][1]['8'] == -0.5 + assert all(len(row) == 20 for row in result['logprobs']) + + +def test_eos_is_a_real_token(worker): + """An EOS-only request has one output token and no decode denominator.""" + output = response((100001, )) + output.outputs[0].finish_reason = 'stop' + output.metrics.last_token_ts = output.metrics.first_token_ts + assert worker.output_record(output, 64, [1, 2, 3])['token_ids'] == [100001] + assert worker.request_times(output) == (250.0, 400.0, None) + + +def test_pinned_engine_timestamps(worker): + """Derive durations from compatible monotonic timestamps and actual tokens.""" + assert worker.request_times(response()) == (250.0, 400.0, 250.0) + + +@pytest.mark.parametrize('tokens', [(), (1, 2, 3, 4, 5)]) +def test_invalid_token_counts(worker, tokens): + """Reject empty or over-limit outputs rather than inventing throughput.""" + with pytest.raises(RuntimeError, match='count'): + worker.output_record(response(tokens), 4, [1, 2, 3]) + + +@pytest.mark.parametrize('field,value', [('finished', False), ('prompt_token_ids', [])]) +def test_incomplete_requests(worker, field, value): + """Failed request batches do not count as complete model execution.""" + output = response() + setattr(output, field, value) + with pytest.raises(RuntimeError, match='unfinished'): + worker.output_record(output, 64, [1, 2, 3]) + + +def test_output_must_match_submitted_prompt(worker): + """Do not validate a correct response against a different request's tokens.""" + with pytest.raises(RuntimeError, match='different prompt'): + worker.output_record(response(), 64, [3, 2, 1]) + + +def test_missing_logprobs(worker): + """Missing numerical-reference evidence must fail explicitly.""" + output = response() + output.outputs[0].logprobs = None + with pytest.raises(RuntimeError, match='probabilities'): + worker.output_record(output, 64, [1, 2, 3], True) + + +def test_truncated_logprob_row_is_not_accepted(worker): + """Numerical validation must retain the requested top-20 positions, not only the chosen token.""" + output = response() + del output.outputs[0].logprobs[0][0] + with pytest.raises(RuntimeError, match='top-20'): + worker.output_record(output, 64, [1, 2, 3], True) + + +@pytest.mark.parametrize( + 'field,value', [ + ('is_corrupted', True), ('num_generation_tokens', 64), ('first_token_ts', 0.0), + ('first_token_latency', float('nan')), ('last_token_ts', 10.0) + ] +) +def test_invalid_statistics(worker, field, value): + """Never substitute zero/default durations or hide corrupted logits.""" + output = response() + setattr(output.metrics, field, value) + with pytest.raises(RuntimeError): + worker.request_times(output) + + +def test_measured_generation_excludes_warmup_and_counts_actual_tokens(worker, monkeypatch): + """Exclude distinct warmup timings and retain mixed EOS/multi-token measurements.""" + monkeypatch.setitem(sys.modules, 'torch', SimpleNamespace(cuda=SimpleNamespace(synchronize=lambda: None))) + monkeypatch.setitem(sys.modules, 'vllm', SimpleNamespace(SamplingParams=SimpleNamespace)) + clock = iter([0.0, 0.1, 1.0, 1.2, 2.0, 2.3]) + monkeypatch.setattr(worker.time, 'monotonic', lambda: next(clock)) + batches = iter( + [ + [(1, 0.05, 0.06, 0), (4, 0.075, 0.085, 0.015)], + [(1, 0.01, 0.015, 0), (3, 0.02, 0.025, 0.12)], + [(2, 0.03, 0.035, 0.08), (1, 0.04, 0.045, 0)], + ] + ) + submitted = [] + monkeypatch.setattr(worker.time, 'time', lambda: 1000.0 + 100 * len(submitted)) + + class Engine: + def generate(self, prompts, parameters, use_tqdm): + submitted.append(prompts) + outputs = [] + for prompt, (count, prefill, ttft, decode) in zip(prompts, next(batches)): + output = response((99, ) if count == 1 else tuple(range(7, 7 + count))) + output.prompt_token_ids = prompt['prompt_token_ids'] + output.metrics.first_token_ts = output.metrics.scheduled_ts + prefill + output.metrics.first_token_latency = ttft + output.metrics.last_token_ts = output.metrics.first_token_ts + decode + if count == 1: + output.outputs[0].finish_reason = 'stop' + outputs.append(output) + return outputs + + args = SimpleNamespace(num_warmup=1, num_steps=2, seq_len=32, batch_size=2, max_new_tokens=4) + report = worker.measured_generation(Engine(), [[1, 2, 3], [4, 5]], 99, args) + assert len(submitted) == 3 + assert report['step_ms'] == pytest.approx([200, 300]) + assert report['request_count'] == 4 + assert report['input_token_counts'] == [32, 32, 32, 32] + assert report['output_token_counts'] == [1, 3, 2, 1] + assert report['request_prefill_ms'] == pytest.approx([10, 20, 30, 40]) + assert report['ttft_ms'] == pytest.approx([15, 25, 35, 45]) + assert report['decode_tpot_ms'] == pytest.approx([60, 80]) + assert report['measurement_start_unix_seconds'] == 1100 + assert report['measurement_end_unix_seconds'] == 1300 + + +def test_measured_generation_rejects_missing_requests(worker, monkeypatch): + """A partial generation batch cannot become a valid throughput sample.""" + monkeypatch.setitem(sys.modules, 'torch', SimpleNamespace(cuda=SimpleNamespace(synchronize=lambda: None))) + monkeypatch.setitem(sys.modules, 'vllm', SimpleNamespace(SamplingParams=SimpleNamespace)) + engine = SimpleNamespace(generate=lambda *args, **kwargs: []) + args = SimpleNamespace(num_warmup=0, num_steps=1, seq_len=32, batch_size=2, max_new_tokens=4) + with pytest.raises(RuntimeError, match='fewer requests'): + worker.measured_generation(engine, [[1, 2, 3]], 99, args) + + +def test_numerical_checks_cover_real_profile_and_later_decode(worker, monkeypatch): + """Use a full performance-shaped batch and retain complete selected-token traces.""" + monkeypatch.setitem(sys.modules, 'vllm', SimpleNamespace(SamplingParams=SimpleNamespace)) + submitted = [] + + class Engine: + def generate(self, prompts, parameters, use_tqdm): + submitted.append((prompts, parameters)) + outputs = [] + for prompt in prompts: + output = response(tuple(range(64))) + output.prompt_token_ids = prompt['prompt_token_ids'] + outputs.append(output) + return outputs + + args = SimpleNamespace(seq_len=512, batch_size=8, max_new_tokens=64) + records = worker.profile_checks(Engine(), [[1, 2, 3], [4, 5]], 99, args) + prompts, parameters = submitted[0] + assert len(prompts) == 8 + assert all(len(prompt['prompt_token_ids']) == 512 for prompt in prompts) + assert parameters.max_tokens == 64 and parameters.logprobs == 20 + assert [record['profile_request_index'] for record in records] == [0, 7] + assert all(record['profile_batch_size'] == 8 for record in records) + assert all(len(record['token_ids']) == len(record['logprobs']) == 64 for record in records) + assert all(record['full_prefix_steps'] == [0, 1, 32, 63] for record in records) + + +def test_numerical_profile_checks_reject_partial_batch(worker, monkeypatch): + """Numerical sampling must not hide requests dropped from its full batch.""" + monkeypatch.setitem(sys.modules, 'vllm', SimpleNamespace(SamplingParams=SimpleNamespace)) + engine = SimpleNamespace(generate=lambda *args, **kwargs: []) + args = SimpleNamespace(seq_len=512, batch_size=8, max_new_tokens=64) + with pytest.raises(RuntimeError, match='lost a request'): + worker.profile_checks(engine, [[1, 2, 3]], 99, args) + + +@pytest.fixture +def main_driver(worker, tmp_path, monkeypatch): + """Exercise the full worker's control flow without real vLLM or GPU execution.""" + if sys.version_info < (3, 10): + pytest.skip('The standalone inference runtime requires Python 3.10 or later.') + import importlib.metadata + torch = pytest.importorskip('torch') + + version = importlib.metadata.version + monkeypatch.setattr(importlib.metadata, 'version', lambda name: '0.31.0' if name == 'vllm' else version(name)) + for variable in [ + 'TORCH_ALLOW_TF32_CUBLAS_OVERRIDE', 'NVIDIA_TF32_OVERRIDE', 'VLLM_FLOAT32_MATMUL_PRECISION', + 'TRITON_F32_DEFAULT', 'VLLM_RAISE_ON_LOGIT_NANS', 'VLLM_BATCH_INVARIANT', 'VLLM_MLA_DISABLE' + ]: + monkeypatch.setenv(variable, 'test-original') + monkeypatch.setattr(worker.signal, 'signal', Mock()) + monkeypatch.setattr(worker, 'configure_cache', Mock()) + download = Mock(return_value=tmp_path / 'checkpoint') + monkeypatch.setattr(worker, 'download_checkpoint', download) + monkeypatch.setattr(torch.cuda, 'is_available', lambda: True) + monkeypatch.setattr(torch.cuda, 'set_device', Mock()) + monkeypatch.setattr(torch.cuda, 'synchronize', Mock()) + monkeypatch.setattr(torch.cuda, 'empty_cache', Mock()) + monkeypatch.setattr(torch.cuda, 'get_device_name', lambda index: 'CPU orchestration fixture') + shutdown = Mock() + config = SimpleNamespace(dtype=torch.bfloat16, quantization=None) + tokenizer = SimpleNamespace(encode=lambda *args, **kwargs: [1, 2, 3], eos_token_id=99) + + def generate(prompts, parameters, use_tqdm): + outputs = [] + stop = hasattr(parameters, 'allowed_token_ids') + tokens = parameters.allowed_token_ids if stop else list(range(7, 7 + parameters.max_tokens)) + for prompt in prompts: + output = response(tuple(tokens)) + output.prompt_token_ids = prompt['prompt_token_ids'] + if stop: + output.outputs[0].finish_reason = 'stop' + output.metrics.last_token_ts = output.metrics.first_token_ts + outputs.append(output) + return outputs + + engine = SimpleNamespace( + llm_engine=SimpleNamespace(model_config=config, engine_core=SimpleNamespace(shutdown=shutdown)), + get_tokenizer=lambda: tokenizer, + generate=generate, + ) + factory = Mock(return_value=engine) + monkeypatch.setitem(sys.modules, 'vllm', SimpleNamespace(LLM=factory, SamplingParams=SimpleNamespace)) + + def reference(command, log, timeout): + assert timeout > 0 + assert shutdown.called + output = Path(command[command.index('--output') + 1]) + worker.write_json(output, {'correctness_passed': True, 'teardown_complete': True}) + + oracle = Mock(side_effect=reference) + monkeypatch.setattr(worker, 'run_worker', oracle) + output = tmp_path / 'report.json' + argv = [ + 'worker', + '--cache_dir', + str(tmp_path / 'cache'), + '--output', + str(output), + '--reference_python', + 'reference-python', + '--batch_size', + '2', + '--seq_len', + '64', + '--num_warmup', + '1', + '--num_steps', + '2', + '--max_new_tokens', + '4', + '--duration', + '60', + ] + monkeypatch.setattr(sys, 'argv', argv) + return SimpleNamespace( + output=output, + argv=argv, + factory=factory, + engine=engine, + config=config, + shutdown=shutdown, + oracle=oracle, + download=download, + torch=torch, + ) + + +def test_inference_main_keeps_precision_counts_and_reference_lifecycle(worker, main_driver): + """Check the selected policies and report only after shutdown and reference success.""" + state = main_driver + worker.main() + options = state.factory.call_args[1] + assert options['dtype'] == 'bfloat16' and options['quantization'] is None + assert options['hf_overrides'] == {'moe_router_dtype': 'float32'} + assert options['max_model_len'] == 68 and options['max_num_seqs'] == 2 + report = json.loads(state.output.read_text()) + assert report['status'] == 'success' and report['correctness_passed'] and report['teardown_complete'] + assert report['request_count'] == 4 and report['output_token_counts'] == [4] * 4 + assert report['router_dtype'] == 'float32' and report['float32_matmul_precision'] == 'highest' + assert report['numerical_policy'] == 'strict_fp32' and report['batch_invariant'] is False + state.shutdown.assert_called_once_with(timeout=10) + state.oracle.assert_called_once() + + +def test_nan_detection_is_enabled_before_vllm_import(worker, main_driver, monkeypatch): + """Reject a disabled inherited setting before the engine module is imported.""" + real_import = __import__ + engine_imports = [] + + def checked_import(name, *args, **kwargs): + if name == 'vllm': + assert worker.os.environ['VLLM_RAISE_ON_LOGIT_NANS'] == '1' + engine_imports.append(name) + return real_import(name, *args, **kwargs) + + monkeypatch.setattr('builtins.__import__', checked_import) + worker.main() + assert engine_imports + + +def test_corrupted_measured_generation_cannot_publish_success(worker, main_driver, monkeypatch): + """Corruption in unscored measured requests must prevent result publication.""" + generate = main_driver.engine.generate + + def corrupted_generation(*args, **kwargs): + outputs = generate(*args, **kwargs) + for output in outputs: + output.metrics.is_corrupted = True + return outputs + + monkeypatch.setattr(main_driver.engine, 'generate', corrupted_generation) + with pytest.raises(RuntimeError, match='logits were corrupted'): + worker.main() + main_driver.shutdown.assert_called_once() + main_driver.oracle.assert_not_called() + assert not main_driver.output.exists() + + +def test_engine_error_still_shuts_down(worker, main_driver, monkeypatch): + """Generation failure cannot leave the engine alive or produce performance success.""" + monkeypatch.setattr(main_driver.engine, 'generate', Mock(side_effect=RuntimeError('generation failed'))) + with pytest.raises(RuntimeError, match='generation failed'): + worker.main() + main_driver.shutdown.assert_called_once() + main_driver.oracle.assert_not_called() + assert not main_driver.output.exists() + + +def test_failed_reference_is_not_success(worker, main_driver): + """A numerically rejected generation run must not publish a success report.""" + main_driver.oracle.side_effect = RuntimeError('numerical gate failed') + with pytest.raises(RuntimeError, match='numerical gate'): + worker.main() + main_driver.shutdown.assert_called_once() + assert not main_driver.output.exists() + + +def test_wrong_engine_precision_is_rejected(worker, main_driver): + """Do not silently replace the BF16 performance workload with another precision.""" + main_driver.config.dtype = main_driver.torch.float32 + with pytest.raises(RuntimeError, match='unquantized BF16'): + worker.main() + main_driver.shutdown.assert_called_once() + assert not main_driver.output.exists() + + +def test_unsupported_engine_version_fails_before_download(worker, main_driver, monkeypatch): + """Version-specific timing and shutdown contracts must not silently drift.""" + import importlib.metadata + version = importlib.metadata.version + monkeypatch.setattr(importlib.metadata, 'version', lambda name: '0.32.0' if name == 'vllm' else version(name)) + with pytest.raises(RuntimeError, match='pinned vLLM'): + worker.main() + main_driver.download.assert_not_called() + + +def test_inference_does_not_fall_back_to_cpu(worker, main_driver, monkeypatch): + """Unavailable GPU execution is an explicit failure, not a replacement benchmark.""" + monkeypatch.setattr(main_driver.torch.cuda, 'is_available', lambda: False) + with pytest.raises(RuntimeError, match='GPU unavailable'): + worker.main() + main_driver.download.assert_not_called() + + +def test_reference_success_code_requires_correctness_flags(worker, main_driver): + """Returning from the oracle process is insufficient without its explicit checks.""" + def rejected(command, log, timeout): + output = Path(command[command.index('--output') + 1]) + worker.write_json(output, {'correctness_passed': False, 'teardown_complete': True}) + + main_driver.oracle.side_effect = rejected + with pytest.raises(RuntimeError, match='reference did not complete'): + worker.main() + assert not main_driver.output.exists() + + +@pytest.mark.parametrize( + 'override', [ + ['--batch_size', '0'], + ['--seq_len', '16'], + ['--num_steps', '0'], + ['--num_warmup', '-1'], + ['--max_new_tokens', '3'], + ['--gpu_memory_utilization', 'nan'], + ['--duration', '3600'], + ] +) +def test_inference_preflight_rejects_invalid_profile(worker, main_driver, monkeypatch, override): + """Invalid generation parameters must fail before download or engine creation.""" + monkeypatch.setattr(sys, 'argv', main_driver.argv + override) + with pytest.raises(ValueError): + worker.main() + main_driver.download.assert_not_called() + main_driver.factory.assert_not_called() + + +def h100_arguments(worker, main_driver): + """Select the frozen shape without changing the existing small fixture's defaults.""" + arguments = main_driver.argv + ['--numerical_policy', worker.numerics.POLICY] + for key, value in worker.numerics.PROFILE.items(): + arguments.extend(['--' + key, str(value)]) + return arguments + + +def test_h100_checks_retain_every_window_and_batch_row(worker, main_driver): + """The runtime replays all qualification windows, not only first/last rows.""" + args = SimpleNamespace(**worker.numerics.PROFILE) + documents, eos = [[1, 2, 3], [4, 5]], 99 + records = worker.qualified_checks(main_driver.engine, documents, eos, args) + assert len(records) == 84 + groups = worker.numerics.validate_requests(records, documents, eos) + assert list(groups) == list(worker.numerics.OFFSETS) + assert all(sum(len(record['token_ids']) for record in group) == 536 for group in groups.values()) + + +def test_h100_policy_uses_pinned_engine_settings_and_separate_reference(worker, main_driver, monkeypatch): + """Wire the explicit policy without replacing the measured BF16 model.""" + monkeypatch.setattr(sys, 'argv', h100_arguments(worker, main_driver)) + expected_gpu = worker.numerics.load_contract()['calibrated_contract']['runtime_identity']['gpu_name'] + monkeypatch.setattr(main_driver.torch.cuda, 'get_device_name', lambda index: expected_gpu) + main_driver.config.use_mla = True + validation = Mock() + monkeypatch.setattr(worker.numerics, 'validate_reference_result', validation) + worker.main() + report = json.loads(main_driver.output.read_text()) + assert report['numerical_policy'] == worker.numerics.POLICY and report['batch_invariant'] is True + assert main_driver.factory.call_args.kwargs['dtype'] == 'bfloat16' + command = main_driver.oracle.call_args.args[0] + assert command[1].endswith('deepseek_v2_lite_numerics.py') and '--mode' not in command + assert len(json.loads((main_driver.output.parent / 'reference-requests.json').read_text())) == 84 + validation.assert_called_once_with(report['reference']) + assert worker.os.environ['VLLM_BATCH_INVARIANT'] == '1' + assert worker.os.environ['VLLM_MLA_DISABLE'] == '0' + main_driver.shutdown.assert_called_once() + + +def test_h100_policy_rejects_another_gpu_before_download(worker, main_driver, monkeypatch): + """A qualified H100 policy cannot be silently reused on other hardware.""" + monkeypatch.setattr(sys, 'argv', h100_arguments(worker, main_driver)) + with pytest.raises(ValueError, match='qualified H100 hardware'): + worker.main() + main_driver.download.assert_not_called() + + +def test_h100_policy_rejects_expanded_kv_and_still_shuts_down(worker, main_driver, monkeypatch): + """Preserve the measured implementation as well as model dtype.""" + monkeypatch.setattr(sys, 'argv', h100_arguments(worker, main_driver)) + expected_gpu = worker.numerics.load_contract()['calibrated_contract']['runtime_identity']['gpu_name'] + monkeypatch.setattr(main_driver.torch.cuda, 'get_device_name', lambda index: expected_gpu) + main_driver.config.use_mla = False + with pytest.raises(RuntimeError, match='compressed-MLA'): + worker.main() + main_driver.shutdown.assert_called_once() + main_driver.oracle.assert_not_called() diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_numerics.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_numerics.py new file mode 100644 index 000000000..963f58eb7 --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_numerics.py @@ -0,0 +1,555 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""CPU controls for the input-matched policy, not hardware qualification.""" + +import hashlib +import importlib.util +import inspect +import json +import math +import sys +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + + +@pytest.fixture +def numerics(monkeypatch): + """Load the standalone reference without importing the engine.""" + directory = Path(__file__).resolve().parents[3] / 'superbench/benchmarks/model_benchmarks' + monkeypatch.syspath_prepend(str(directory)) + spec = importlib.util.spec_from_file_location('v2lite_numerics_test', directory / 'deepseek_v2_lite_numerics.py') + if spec is None or spec.loader is None: + raise RuntimeError('Cannot load the standalone numerical reference.') + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def budgets(): + """Use deliberately small synthetic bounds for arithmetic controls.""" + return { + 'max_probability_error': 0.02, + 'relative_probability_mass_error': 0.03, + 'normalized_logprob_error': 0.5, + } + + +@pytest.fixture +def policy_file(numerics, tmp_path, monkeypatch): + """Create qualified-shaped test evidence without claiming GPU execution.""" + monkeypatch.setattr(numerics, '__file__', str(tmp_path / 'superbench/benchmarks/model_benchmarks/reference.py')) + path = tmp_path / 'superbench/config/deepseek-v2-lite-h100-numerics.json' + path.parent.mkdir(parents=True) + candidate = { + 'method': numerics.METHOD, + 'reference_only': True, + 'input_matched_limit_rule': numerics.LIMIT_RULE, + 'qualification_offsets': list(numerics.OFFSETS), + 'profile': {key: numerics.PROFILE[key] + for key in ('batch_size', 'seq_len', 'max_new_tokens')}, + 'qualification_stream': {key: numerics.PROFILE[key] + for key in ('num_warmup', 'num_steps')}, + } + candidate['frozen_limits_sha256'] = numerics.canonical_hash(candidate) + contract = { + 'status': 'qualified', + 'calibrated_contract': candidate, + 'qualification': [{ + 'profile_offset': offset + } for offset in numerics.OFFSETS], + 'reference_validation': { + 'non_anchor_comparisons': 1 + }, + } + + def save(): + path.write_text(json.dumps(contract)) + monkeypatch.setattr(numerics, 'CONTRACT_SHA256', hashlib.sha256(path.read_bytes()).hexdigest()) + + save() + return SimpleNamespace(path=path, contract=contract, candidate=candidate, save=save) + + +def test_frozen_profile_is_explicit_and_legacy_policy_is_unchanged(numerics): + """Do not apply one H100 qualification to other shapes or the default policy.""" + numerics.validate_profile(SimpleNamespace(numerical_policy='strict_fp32', batch_size=1)) + args = SimpleNamespace(numerical_policy=numerics.POLICY, **numerics.PROFILE) + numerics.validate_profile(args) + args.num_steps -= 1 + with pytest.raises(ValueError, match='complete frozen'): + numerics.validate_profile(args) + with pytest.raises(ValueError, match='Unknown'): + numerics.validate_profile(SimpleNamespace(numerical_policy='other')) + + +def test_contract_requires_installed_qualification(numerics, monkeypatch): + """An unfinished policy cannot start a reference workload.""" + monkeypatch.setattr(numerics, 'CONTRACT_SHA256', '') + with pytest.raises(RuntimeError, match='qualified contract'): + numerics.load_contract() + + +def test_contract_is_bound_to_exact_file_bytes(numerics, policy_file): + """Even a semantically equivalent substituted policy requires a new identity.""" + assert numerics.load_contract() == policy_file.contract + policy_file.path.write_text(policy_file.path.read_text() + '\n') + with pytest.raises(ValueError, match='changed'): + numerics.load_contract() + + +@pytest.mark.parametrize('fault', ['status', 'method', 'shape', 'stream', 'offsets', 'evidence', 'anchor-only', 'hash']) +def test_contract_rejects_incomplete_qualification(numerics, policy_file, fault): + """Validate semantics as well as a matching artifact digest.""" + candidate, contract = policy_file.candidate, policy_file.contract + if fault == 'status': + contract['status'] = 'candidate' + elif fault == 'method': + candidate['method'] = 'unqualified-method' + elif fault == 'shape': + candidate['profile']['batch_size'] = 1 + elif fault == 'stream': + candidate['qualification_stream']['num_steps'] = 1 + elif fault == 'offsets': + candidate['qualification_offsets'].pop() + elif fault == 'evidence': + contract['qualification'].pop() + elif fault == 'anchor-only': + contract['reference_validation']['non_anchor_comparisons'] = 0 + else: + candidate['frozen_limits_sha256'] = 'changed' + if fault != 'hash': + candidate['frozen_limits_sha256'] = numerics.canonical_hash( + {key: value + for key, value in candidate.items() if key != 'frozen_limits_sha256'} + ) + policy_file.save() + with pytest.raises(ValueError, match='qualification'): + numerics.load_contract() + + +@pytest.mark.parametrize( + 'expected,actual', [ + ([], []), + ([-1.0], []), + ([float('nan')], [-1.0]), + ([-1.0], [float('inf')]), + ([-1.0], [True]), + ([-1.0], [0.1]), + ([-1000.0], [-1000.0]), + ([0.0, 0.0], [0.0, 0.0]), + ] +) +def test_invalid_probability_data_is_rejected(numerics, expected, actual): + """Reject malformed, nonfinite and unnormalized probabilities explicitly.""" + with pytest.raises(ValueError): + numerics.probability_errors(expected, actual) + + +def test_probability_mass_and_log_metrics_retain_every_token(numerics): + """Detect normalization defects even when the greedy token is unchanged.""" + expected = [math.log(0.6), math.log(0.3)] + actual = [value - math.log(2) for value in expected] + errors = numerics.probability_errors(expected, actual) + assert errors['max_probability_error'] == pytest.approx(0.3) + assert errors['relative_probability_mass_error'] == pytest.approx(0.5) + assert errors['max_logprob_error'] == pytest.approx(math.log(2)) + assert errors['normalized_logprob_error'] > 0 + + +def test_input_matched_limits_are_reference_only(numerics): + """Keep calibration unchanged and fail if uncertainty admits half normalization.""" + calibrated = budgets() + original = dict(calibrated) + reference = {metric: 0.01 for metric in numerics.METRICS} + assert numerics.input_matched_limits(calibrated, reference) == { + metric: original[metric] + reference[metric] + for metric in numerics.METRICS + } + assert calibrated == original + reference['relative_probability_mass_error'] = 0.5 + with pytest.raises(ValueError, match='half-normalization'): + numerics.input_matched_limits(calibrated, reference) + reference['relative_probability_mass_error'] = float('nan') + with pytest.raises(ValueError, match='input-matched'): + numerics.input_matched_limits(calibrated, reference) + reference['relative_probability_mass_error'] = 0 + calibrated['normalized_logprob_error'] = 0 + with pytest.raises(ValueError, match='budget'): + numerics.input_matched_limits(calibrated, reference) + + +def test_greedy_rules_and_invalid_bounds(numerics): + """Near ties do not waive reported-greedy or probability-gap checks.""" + expected = {0: math.log(0.9), 1: math.log(0.1)} + result = numerics.score_probabilities(expected, expected, 1, 0, budgets()) + assert not result['accepted'] and not result['greedy_match'] + assert 'reported token is not greedy' in result['failures'] + assert 'greedy choice exceeds calibrated uncertainty' in result['failures'] + assert numerics.score_probabilities(expected, expected, 0, 0, budgets())['accepted'] + with pytest.raises(ValueError, match='Incomplete'): + numerics.score_probabilities(expected, {0: expected[0]}, 0, 0, budgets()) + limits = budgets() + limits['normalized_logprob_error'] = float('inf') + with pytest.raises(ValueError, match='bound'): + numerics.score_probabilities(expected, expected, 0, 0, limits) + + +def test_top_k_shape_bounds_and_tail_fault(numerics): + """A tiny tail still has to reject the fixed temperature fault.""" + torch = pytest.importorskip('torch') + logits = torch.full((32, ), -40.0) + logits[0] = 0 + expected = logits.log_softmax(-1) + wrong = (expected / 2).log_softmax(-1) + ids = wrong.topk(20).indices.tolist() + observed = {str(key): wrong[key].item() for key in ids} + result = numerics.evaluate_logits(expected, observed, 0, budgets()) + assert not result['accepted'] and 'normalized_logprob_error' in result['failures'] + with pytest.raises(ValueError, match='top-20'): + numerics.evaluate_logits(expected, {'0': 0.0}, 0, budgets()) + observed['1000'] = observed.pop(str(ids[-1])) + with pytest.raises(ValueError, match='out of range'): + numerics.evaluate_logits(expected, observed, 0, budgets()) + missing = {str(key): -10.0 for key in range(1, 21)} + assert not numerics.evaluate_logits(expected, missing, 1, budgets())['accepted'] + duplicate = {str(key): -10.0 for key in range(20)} + duplicate['00'] = -10.0 + with pytest.raises(ValueError, match='duplicated'): + numerics.evaluate_logits(expected, duplicate, 0, budgets()) + + +@pytest.fixture +def cpu_reference(monkeypatch): + """Exercise reference tensor operations on CPU with explicit fake device transport.""" + torch = pytest.importorskip('torch') + tensor, ones = torch.tensor, torch.ones + + def cpu_tensor(*args, **kwargs): + if kwargs.get('device') == 'cuda': + kwargs['device'] = 'cpu' + return tensor(*args, **kwargs) + + def cpu_ones(*args, **kwargs): + if kwargs.get('device') == 'cuda': + kwargs['device'] = 'cpu' + return ones(*args, **kwargs) + + monkeypatch.setattr(torch, 'tensor', cpu_tensor) + monkeypatch.setattr(torch, 'ones', cpu_ones) + return torch + + +def test_complete_prefix_and_cached_reference_shapes(numerics, cpu_reference): + """Check all attention-mask lengths and cache positions without a GPU.""" + torch = cpu_reference + calls = [] + + def model(input_ids, attention_mask, use_cache, past_key_values=None): + calls.append((input_ids.shape, attention_mask.shape, use_cache, past_key_values)) + logits = torch.arange(24, dtype=torch.float32).reshape(1, 1, 24) + return SimpleNamespace( + logits=logits.expand(input_ids.shape[0], input_ids.shape[1], 24), past_key_values=len(calls) + ) + + cases = [{'id': str(index), 'prompt_token_ids': [1, 2, 3], 'continuation_ids': [4, 5]} for index in range(3)] + full = numerics.full_logits(model, [[1, 2, 3]]) + assert full.shape == (1, 24) and calls[-1][2:] == (False, None) + values = numerics.collect_matched_bf16(model, cases, 2) + assert set(values) == {'0', '1', '2'} and all(value.shape == (2, 24) for value in values.values()) + assert calls[1][0:2] == (torch.Size([2, 3]), torch.Size([2, 3])) + assert calls[2][0:2] == (torch.Size([2, 1]), torch.Size([2, 4])) + assert calls[2][3] is not None + errors = numerics.tensor_errors(values['0'][0], values['1'][0]) + assert errors['greedy_match'] and all(errors[metric] == 0 for metric in numerics.METRICS) + with pytest.raises(ValueError, match='uniquely'): + numerics.configured_batches(cases + cases, 2) + mismatched = [cases[0], dict(cases[1], continuation_ids=[4])] + with pytest.raises(ValueError, match='matching sequence'): + list(numerics.cached_logits(model, mismatched)) + + +def test_reference_rejects_nonfinite_and_incomplete_output(numerics, cpu_reference, monkeypatch): + """Reference failures cannot create success-shaped numerical evidence.""" + torch = cpu_reference + + def model(**kwargs): + return SimpleNamespace(logits=torch.full((1, 2, 24), float('nan')), past_key_values=1) + + cases = [{'id': '0', 'prompt_token_ids': [1, 2], 'continuation_ids': [3]}] + with pytest.raises(RuntimeError, match='Nonfinite'): + numerics.full_logits(model, [[1, 2]]) + with pytest.raises(RuntimeError, match='Nonfinite'): + list(numerics.cached_logits(model, cases)) + monkeypatch.setattr(numerics, 'cached_logits', lambda *args: iter([])) + with pytest.raises(ValueError, match='Incomplete'): + numerics.collect_matched_bf16(model, cases, 1) + monkeypatch.setattr(numerics, 'cached_logits', lambda *args: iter([(1, torch.zeros((1, 24)))])) + with pytest.raises(ValueError, match='out-of-order'): + numerics.collect_matched_bf16(model, cases, 1) + + +def request_sets(numerics): + """Create token-shaped fixtures, not reference or engine measurements.""" + documents, eos, records = [[1, 2, 3], [4, 5, 6]], 99, [] + short = [ + numerics.packed_tokens(documents, eos, length, 1, index * 7)[0] for index, length in enumerate((16, 23, 32)) + ] + for offset in numerics.OFFSETS: + prompts = short * 2 + numerics.packed_tokens(documents, eos, 512, 8, offset) + for index, prompt in enumerate(prompts): + count = 4 if index < 6 else 64 + row = { + 'prompt_token_ids': prompt, + 'token_ids': [1] * count, + 'logprobs': [{} for _ in range(count)], + 'numerical_set_offset': offset, + } + if index >= 6: + row.update(profile_request_index=index - 6, profile_batch_size=8) + records.append(row) + return documents, eos, records + + +@pytest.mark.parametrize('fault', ['missing-window', 'wrong-prompt', 'short-decode', 'lost-row', 'bad-token', 'trace']) +def test_frozen_request_sets_cannot_drop_positions(numerics, fault): + """Require all six windows and every configured-batch row.""" + documents, eos, requests = request_sets(numerics) + groups = numerics.validate_requests(requests, documents, eos) + assert list(groups) == list(numerics.OFFSETS) + if fault == 'missing-window': + requests.pop() + elif fault == 'wrong-prompt': + requests[0]['prompt_token_ids'] = [7] + elif fault == 'short-decode': + for row in requests[:14]: + row['token_ids'] = row['token_ids'][:1] + row['logprobs'] = row['logprobs'][:1] + elif fault == 'lost-row': + requests[6]['profile_request_index'] = 2 + elif fault == 'bad-token': + requests[0]['token_ids'][0] = True + else: + requests[0]['logprobs'].pop() + with pytest.raises(ValueError): + numerics.validate_requests(requests, documents, eos) + + +@pytest.mark.parametrize('corrupt', [False, True]) +def test_group_scoring_retains_all_positive_and_fault_positions(numerics, monkeypatch, corrupt): + """A good synthetic pair must reject every fault; a corrupted pair must fail.""" + torch = pytest.importorskip('torch') + vectors = [torch.arange(32, dtype=torch.float32), torch.arange(31, -1, -1, dtype=torch.float32)] + expected = [value.log_softmax(-1) for value in vectors] + requests, matched = [], {} + for index in range(2): + ids = expected[index].topk(20).indices.tolist() + observed = {str(key): expected[index][key].item() for key in ids} + if corrupt: + observed = {key: value - math.log(2) for key, value in observed.items()} + requests.append( + { + 'prompt_token_ids': [index], + 'token_ids': [expected[index].argmax().item()] * 2, + 'logprobs': [observed, observed], + } + ) + matched['request-{}'.format(index)] = torch.stack([expected[index], expected[index]]) + monkeypatch.setattr(numerics, 'full_logits', lambda model, rows: vectors[rows[0][0]].unsqueeze(0)) + result = numerics.evaluate_group(None, requests, matched, budgets()) + assert result['positive_positions'] == 4 and result['negative_positions'] == 9 + assert len(result['positive_failures']) == (4 if corrupt else 0) + assert not result['negative_failures'] + assert {row['fault'] + for row in result['all_negative_records']} == { + 'half-normalization', + 'temperature-two', + 'last-request-context-for-first', + } + + +@pytest.mark.parametrize('failure', [False, True]) +def test_reference_models_are_sequential_and_always_released(numerics, monkeypatch, failure): + """Exercise lifecycle plumbing with explicit CPU-only model doubles.""" + if sys.version_info < (3, 10): + pytest.skip('The standalone reference runtime requires Python 3.10 or later.') + torch = pytest.importorskip('torch') + import deepseek_v2_lite_reference as reference + + loaded = [] + + def load_model(checkpoint, dtype): + loaded.append(dtype) + model = SimpleNamespace() + model.cuda = lambda: model + model.eval = lambda: model + return model + + monkeypatch.setattr(reference, 'load_model', load_model) + monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: ([[1, 2]], 99)) + monkeypatch.setattr(numerics, 'validate_requests', lambda *args: {0: [{'prompt_token_ids': [1], 'token_ids': [2]}]}) + monkeypatch.setattr(numerics, 'collect_matched_bf16', lambda *args: {}) + monkeypatch.setattr(torch, 'set_num_threads', Mock()) + monkeypatch.setattr(torch, 'set_float32_matmul_precision', Mock()) + monkeypatch.setattr(torch.cuda, 'set_device', Mock()) + monkeypatch.setattr(torch.cuda, 'get_device_name', lambda index: 'synthetic-h100') + release = Mock() + monkeypatch.setattr(torch.cuda, 'empty_cache', release) + monkeypatch.setattr(torch.cuda, 'synchronize', Mock()) + from importlib.metadata import version + identity = { + 'torch_version': torch.__version__, + 'transformers_version': version('transformers'), + 'gpu_name': 'synthetic-h100', + 'reference_loader_sha256': hashlib.sha256(inspect.getsource(load_model).encode()).hexdigest(), + 'tf32_allowed': False, + 'bf16_reduced_precision_reduction': torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction, + } + contract = { + 'calibrated_contract': { + 'runtime_identity': identity, + 'limits': budgets(), + 'frozen_limits_sha256': 'fixture' + } + } + evaluation = Mock( + side_effect=RuntimeError('reference failed') if failure else None, + return_value={ + 'positive_positions': 1, + 'negative_positions': 3, + 'positive_failures': [], + 'negative_failures': [] + }, + ) + monkeypatch.setattr(numerics, 'evaluate_group', evaluation) + if failure: + with pytest.raises(RuntimeError, match='reference failed'): + numerics.run_reference(Path('fixture'), [1], contract) + else: + result = numerics.run_reference(Path('fixture'), [1], contract) + assert result['correctness_passed'] is True and result['teardown_complete'] is True + assert loaded == [torch.bfloat16, torch.float32] + assert release.call_count == 2 + identity['gpu_name'] = 'different-hardware' + with pytest.raises(ValueError, match='runtime or hardware'): + numerics.run_reference(Path('fixture'), [1], contract) + + +@pytest.mark.parametrize('passed', [True, False]) +def test_reference_cli_preserves_rejection_evidence(numerics, monkeypatch, tmp_path, passed): + """A rejected report is saved but the process must still fail explicitly.""" + requests, output = tmp_path / 'requests.json', tmp_path / 'reference.json' + requests.write_text('[]') + monkeypatch.setattr( + sys, 'argv', [ + 'reference', + '--checkpoint', + str(tmp_path), + '--requests', + str(requests), + '--output', + str(output), + ] + ) + monkeypatch.setattr(numerics, 'load_contract', lambda: {'fixture': True}) + monkeypatch.setattr(numerics, 'run_reference', lambda *args: {'correctness_passed': passed}) + validate = Mock() + monkeypatch.setattr(numerics, 'validate_reference_result', validate) + if passed: + numerics.main() + else: + with pytest.raises(RuntimeError, match='rejected'): + numerics.main() + assert json.loads(output.read_text())['correctness_passed'] is passed + assert numerics.os.environ['NVIDIA_TF32_OVERRIDE'] == '0' + assert validate.call_count == int(passed) + + +def serialized_reference(numerics): + """Build complete control-flow evidence with explicit synthetic accepted/rejected flags.""" + windows = {} + for offset in numerics.OFFSETS: + positives, negatives = [], [] + for request in range(14): + count = 4 if request < 6 else 64 + for step in range(count): + positives.append({'request': request, 'step': step, 'accepted': True}) + negatives.extend( + [ + { + 'request': request, + 'step': step, + 'accepted': False, + 'fault': fault + } for fault in ('half-normalization', 'temperature-two') + ] + ) + negatives.append({'request': 0, 'step': 0, 'accepted': False, 'fault': 'last-request-context-for-first'}) + windows[str(offset)] = { + 'positive_positions': len(positives), + 'negative_positions': len(negatives), + 'positive_failures': [], + 'negative_failures': [], + 'all_positive_records': positives, + 'all_negative_records': negatives, + } + return { + 'correctness_passed': True, + 'teardown_complete': True, + 'numerical_policy': numerics.POLICY, + 'contract_sha256': numerics.CONTRACT_SHA256, + 'profile_offsets': list(numerics.OFFSETS), + 'request_count': 84, + 'positive_positions': 3216, + 'negative_positions': 6438, + 'windows': windows, + } + + +@pytest.mark.parametrize( + 'fault', [ + 'identity', + 'missing-window', + 'invalid-window', + 'missing-position', + 'accepted-fault', + 'failed-positive', + 'bad-index', + 'duplicate-position', + 'missing-step', + 'wrong-fault', + 'totals', + ] +) +def test_serialized_reference_cannot_fabricate_complete_success(numerics, fault): + """Validate all per-window records rather than trusting a summary flag.""" + report = serialized_reference(numerics) + numerics.validate_reference_result(report) + window = report['windows']['0'] + overrides = {'identity': ('contract_sha256', 'another-policy'), 'totals': ('positive_positions', 3215)} + if fault in overrides: + key, value = overrides[fault] + report[key] = value + elif fault == 'missing-window': + report['windows'].pop('0') + elif fault == 'invalid-window': + report['windows']['0'] = None + elif fault == 'missing-position': + window['all_positive_records'].pop() + elif fault == 'accepted-fault': + window['all_negative_records'][0]['accepted'] = True + elif fault == 'failed-positive': + window['all_positive_records'][0]['accepted'] = False + elif fault == 'bad-index': + window['all_positive_records'][0]['step'] = True + elif fault == 'duplicate-position': + window['all_positive_records'][0] = dict(window['all_positive_records'][1]) + elif fault == 'missing-step': + window['all_positive_records'][0]['step'] = 5 + else: + window['all_negative_records'][-1]['fault'] = 'substituted-fault' + with pytest.raises(ValueError): + numerics.validate_reference_result(report) diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_reference.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_reference.py new file mode 100644 index 000000000..50a88fc02 --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_reference.py @@ -0,0 +1,377 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""CPU control-flow checks, not certification of full-model reference numerics.""" + +import importlib.util +import json +import sys +import weakref +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +torch = pytest.importorskip('torch') + + +@pytest.fixture +def reference(monkeypatch): + """Load the standalone oracle and redirect only test tensor creation to CPU.""" + directory = Path(__file__).resolve().parents[3] / 'superbench/benchmarks/model_benchmarks' + monkeypatch.syspath_prepend(str(directory)) + spec = importlib.util.spec_from_file_location('v2lite_reference_test', directory / 'deepseek_v2_lite_reference.py') + if spec is None or spec.loader is None: + raise RuntimeError('Cannot load the standalone reference.') + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + tensor = torch.tensor + + def cpu_tensor(data, *args, **kwargs): + if kwargs.get('device') == 'cuda': + kwargs['device'] = 'cpu' + return tensor(data, *args, **kwargs) + + monkeypatch.setattr(torch, 'tensor', cpu_tensor) + return module + + +class ReferenceFixture: + """Expose token-independent logits while checking cached attention shapes.""" + def __init__(self): + """Track cache and full-prefix calls separately.""" + self.calls = [] + + def eval(self): + """Retain the minimal evaluation interface used by the oracle.""" + return self + + def __call__(self, input_ids, attention_mask, past_key_values=None, use_cache=True): + """Require a mask for all past and current positions, including one-token decode.""" + length = input_ids.shape[1] + total = length + (past_key_values or 0) + assert attention_mask.shape == (1, total) + assert attention_mask.all().item() + self.calls.append((length, total, past_key_values, use_cache)) + logits = torch.tensor([0.0, 1.0, 2.0, 3.0]).reshape(1, 1, 4).repeat(1, length, 1) + return SimpleNamespace(logits=logits, past_key_values=total if use_cache else None) + + +def request_fixture(): + """Provide exact fixture probabilities rather than a model-quality claim.""" + probabilities = torch.tensor([0.0, 1.0, 2.0, 3.0]).log_softmax(-1).tolist() + return { + 'prompt_token_ids': [1, 2], + 'token_ids': [3, 3], + 'logprobs': [{str(index): value + for index, value in enumerate(probabilities)} for _ in range(2)], + } + + +def test_cached_decode_mask_covers_full_prefix(reference): + """The second cache call has one input token but a three-position mask.""" + model = ReferenceFixture() + result = reference.inference_reference(model, [request_fixture()]) + assert model.calls == [(2, 2, None, True), (2, 2, None, False), (1, 3, 2, True), (3, 3, None, False)] + assert len(result['comparisons']) == 2 + assert all(row['cache_max_abs_error'] == 0 for row in result['comparisons']) + + +@pytest.mark.parametrize('requests', [[], [{'prompt_token_ids': [], 'token_ids': [], 'logprobs': []}]]) +def test_incomplete_reference_requests_fail(reference, requests): + """Never accept an empty or truncated numerical workload.""" + with pytest.raises(ValueError, match='nonempty|Incomplete'): + reference.inference_reference(ReferenceFixture(), requests) + + +def test_reference_requires_greedy_token_agreement(reference): + """Finite probabilities alone must not certify an incorrect generated token.""" + request = request_fixture() + request['token_ids'][0] = 1 + with pytest.raises(RuntimeError, match='greedy token'): + reference.inference_reference(ReferenceFixture(), [request]) + + +def test_reference_does_not_ignore_probability_mismatch(reference): + """Keep the numerical gate even when all generated tokens are correct.""" + request = request_fixture() + request['logprobs'][0]['3'] += 1.0 + with pytest.raises(AssertionError, match='request 0 step 0'): + reference.inference_reference(ReferenceFixture(), [request]) + + +def test_long_decode_checks_every_engine_token_with_bounded_full_prefix_calls(reference): + """Only full-prefix recomputation is sampled, never engine probability validation.""" + request = request_fixture() + request['token_ids'] *= 4 + request['logprobs'] *= 4 + request['full_prefix_steps'] = [0, 1, 4, 7] + model = ReferenceFixture() + result = reference.inference_reference(model, [request]) + assert len(result['comparisons']) == 8 + assert len(model.calls) == 12 + assert [row['step'] for row in result['comparisons'] if row['full_prefix_checked']] == [0, 1, 4, 7] + assert all(row['cache_max_abs_error'] is None for row in result['comparisons'] if not row['full_prefix_checked']) + request['logprobs'][2] = dict(request['logprobs'][2], **{'3': 0.0}) + with pytest.raises(AssertionError, match='request 0 step 2'): + reference.inference_reference(ReferenceFixture(), [request]) + + +@pytest.mark.parametrize('positions', [[], [0], [1], [0, 0, 1], [1, 0], [0, 2], [False, 1]]) +def test_invalid_full_prefix_sampling_fails(reference, positions): + """Do not accept malformed or first/final-step-incomplete numerical evidence.""" + request = request_fixture() + request['full_prefix_steps'] = positions + with pytest.raises(ValueError, match='reference positions'): + reference.inference_reference(ReferenceFixture(), [request]) + + +class TrainingReferenceFixture: + """Small autograd fixture for global-batch partitioning, not GPU model validation.""" + def __init__(self): + """Create the named parameters required by reference sampling.""" + names = [ + 'model.embed_tokens.weight', + 'model.layers.0.self_attn.q_proj.weight', + 'model.layers.0.self_attn.kv_a_proj_with_mqa.weight', + 'model.layers.0.mlp.down_proj.weight', + 'model.layers.1.mlp.gate.weight', + 'model.layers.1.mlp.experts.0.down_proj.weight', + ] + self.parameters = {name: torch.nn.Parameter(torch.ones(2, 2)) for name in names} + self.batches = [] + self.checkpointing = False + + def train(self): + """Expose the reference model's training-mode interface.""" + return self + + def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs): + """Require the memory-bounded nonreentrant reference policy.""" + assert gradient_checkpointing_kwargs == {'use_reentrant': False} + self.checkpointing = True + + def named_parameters(self): + """Expose stable names for independently selected gradient probes.""" + return self.parameters.items() + + def get_parameter(self, name): + """Look up the same parameter on each logical rank batch.""" + return self.parameters[name] + + def zero_grad(self, set_to_none): + """Discard local gradients before the next reference batch.""" + assert set_to_none + for parameter in self.parameters.values(): + parameter.grad = None + + def __call__(self, input_ids, labels, use_cache): + """Produce input-dependent gradients that differ between rank batches.""" + assert not use_cache and torch.equal(input_ids, labels) + self.batches.append(input_ids.clone()) + loss = sum(parameter.sum() for parameter in self.parameters.values()) * input_ids.float().mean() + return SimpleNamespace(loss=loss) + + +def test_training_reference_averages_distinct_real_profile_rank_batches(reference, monkeypatch): + """Check different rank inputs and float32 gradient averaging rather than replicated tokens.""" + monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: ([[1, 2, 4, 8]], 16)) + model = TrainingReferenceFixture() + result = reference.training_reference(model, 'unused', batch_size=2, seq_len=32, world_size=3) + expected = torch.tensor(result['tokens']).float().mean().item() + assert model.checkpointing + assert len(result['tokens']) == 6 and all(len(row) == 32 for row in result['tokens']) + assert len(model.batches) == 3 and not torch.equal(model.batches[0], model.batches[1]) + assert result['world_size'] == 3 and result['batch_size'] == 2 and result['seq_len'] == 32 + assert result['loss'] == pytest.approx(sum(result['loss_per_rank']) / 3) + for probe in result['gradients'].values(): + assert probe['values'] == pytest.approx([expected] * len(probe['indices'])) + assert all(parameter.grad is None for parameter in model.parameters.values()) + + +def test_reference_preserves_exact_rank_microbatch_shape(reference, monkeypatch): + """Do not introduce BF16 batch-regrouping differences while checking distributed gradients.""" + monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: ([[1, 2, 4, 8]], 16)) + model = TrainingReferenceFixture() + result = reference.training_reference(model, 'unused', batch_size=3, seq_len=32, world_size=2) + assert [batch.shape[0] for batch in model.batches] == [3, 3] + assert all(batch.shape[1] == 32 for batch in model.batches) + assert torch.equal(torch.cat(model.batches), torch.tensor(result['tokens'])) + expected = torch.tensor(result['tokens']).float().mean().item() + assert result['reference_microbatch_size'] == 3 + assert result['loss'] == pytest.approx(expected * 24) + for probe in result['gradients'].values(): + assert probe['values'] == pytest.approx([expected] * len(probe['indices'])) + + +def test_targeted_reference_matches_full_backward_without_unneeded_gradients(reference, monkeypatch): + """Preserve full-model derivatives while avoiding storage for unsampled parameter gradients.""" + documents = [[1, 2, 4, 8]] + monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: (documents, 16)) + model = TrainingReferenceFixture() + ignored = torch.nn.Parameter(torch.tensor([2.0])) + model.parameters['model.layers.2.unprobed.weight'] = ignored + tokens = reference.packed_tokens(documents, 16, 32, 6) + expected = {} + for rank in range(2): + model.zero_grad(set_to_none=True) + inputs = torch.tensor(tokens[rank * 3:(rank + 1) * 3]) + model(input_ids=inputs, labels=inputs, use_cache=False).loss.backward() + for name, parameter in model.parameters.items(): + expected[name] = expected.get(name, torch.zeros_like(parameter)) + parameter.grad.detach() / 2 + model.zero_grad(set_to_none=True) + grad = Mock(wraps=torch.autograd.grad) + monkeypatch.setattr(torch.autograd, 'grad', grad) + result = reference.training_reference(model, 'unused', batch_size=3, seq_len=32, world_size=2) + assert grad.call_count == 2 + for call in grad.call_args_list: + assert all(parameter is not ignored for parameter in call[0][1]) + for name, probe in result['gradients'].items(): + assert probe['values'] == pytest.approx(expected[name].flatten()[probe['indices']].tolist()) + assert all(parameter.requires_grad and parameter.grad is None for parameter in model.parameters.values()) + + +def test_reference_does_not_retain_unused_model_outputs(reference, monkeypatch): + """Release returned vocabulary tensors before accumulating full-model gradients.""" + monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: ([[1, 2, 4, 8]], 16)) + + class OutputFixture(TrainingReferenceFixture): + def __call__(self, input_ids, labels, use_cache): + output = super().__call__(input_ids, labels, use_cache) + logits = torch.ones(8, 8) + self.logits_reference = weakref.ref(logits) + return SimpleNamespace(loss=output.loss, logits=logits) + + model = OutputFixture() + + def check_released(gradient): + assert model.logits_reference() is None + return gradient + + next(iter(model.parameters.values())).register_hook(check_released) + reference.training_reference(model, 'unused', batch_size=2, seq_len=32, world_size=2) + + +@pytest.mark.parametrize('batch_size,seq_len,world_size', [(0, 32, 1), (1, 16, 1), (1, 32, 0)]) +def test_training_reference_rejects_invalid_profile(reference, batch_size, seq_len, world_size): + """Invalid global-batch definitions must fail before any model work.""" + with pytest.raises(ValueError, match='reference profile'): + reference.training_reference(TrainingReferenceFixture(), 'unused', batch_size, seq_len, world_size) + + +@pytest.fixture +def loading_contract(reference, tmp_path, monkeypatch): + """Mock library boundaries while exercising all loader identity checks.""" + if sys.version_info < (3, 10): + pytest.skip('The standalone model runtime requires Python 3.10 or later.') + import importlib.metadata + from deepseek_v2_lite_utils import EXPECTED_CONFIG + + (tmp_path / 'config.json').write_text(json.dumps(dict(EXPECTED_CONFIG, model_type='deepseek_v2'))) + parameter = SimpleNamespace(numel=lambda: reference.PARAMETER_COUNT, requires_grad=True) + model = SimpleNamespace(parameters=lambda: [parameter]) + loading = {key: [] for key in ['missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs']} + loader = Mock(return_value=(model, loading)) + tokenizer = SimpleNamespace(encode=Mock(return_value=[1, 2]), eos_token_id=9) + tokenizer_loader = Mock(return_value=tokenizer) + monkeypatch.setitem( + sys.modules, 'transformers', + SimpleNamespace( + AutoModelForCausalLM=SimpleNamespace(from_pretrained=loader), + AutoTokenizer=SimpleNamespace(from_pretrained=tokenizer_loader), + ) + ) + version = importlib.metadata.version + monkeypatch.setattr( + importlib.metadata, 'version', lambda name: '4.46.3' if name == 'transformers' else version(name) + ) + monkeypatch.setattr(torch.cuda, 'is_available', lambda: True) + return SimpleNamespace( + path=tmp_path, + model=model, + parameter=parameter, + loading=loading, + loader=loader, + tokenizer=tokenizer, + tokenizer_loader=tokenizer_loader, + ) + + +def test_official_loader_contract(reference, loading_contract): + """Require local official-code loading and complete loading diagnostics.""" + item = loading_contract + assert reference.load_model(str(item.path), torch.bfloat16) is item.model + options = item.loader.call_args[1] + assert options['torch_dtype'] == torch.bfloat16 + assert options['local_files_only'] and options['trust_remote_code'] and options['use_safetensors'] + assert options['attn_implementation'] == 'eager' and options['output_loading_info'] + documents, eos = reference.fixed_documents(str(item.path)) + assert len(documents) == len(reference.FIXED_TEXTS) and eos == 9 + assert item.tokenizer_loader.call_args[1]['local_files_only'] + assert item.tokenizer.encode.call_count == len(reference.FIXED_TEXTS) + + +@pytest.mark.parametrize('field', ['missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs']) +def test_loader_diagnostics_cannot_be_ignored(reference, loading_contract, field): + """Partial or incompatible loading must fail before reference execution.""" + loading_contract.loading[field] = ['invalid checkpoint'] + with pytest.raises(RuntimeError, match='checkpoint loading'): + reference.load_model(str(loading_contract.path), torch.bfloat16) + + +@pytest.mark.parametrize('failure', ['count', 'frozen', 'gpu', 'version']) +def test_loader_rejects_wrong_model_or_runtime(reference, loading_contract, monkeypatch, failure): + """Do not replace full-model GPU verification with a smaller or unsupported runtime.""" + item = loading_contract + if failure == 'count': + item.parameter.numel = lambda: 1 + elif failure == 'frozen': + item.parameter.requires_grad = False + elif failure == 'gpu': + monkeypatch.setattr(torch.cuda, 'is_available', lambda: False) + else: + import importlib.metadata + monkeypatch.setattr(importlib.metadata, 'version', lambda name: '0.0') + with pytest.raises(RuntimeError): + reference.load_model(str(item.path), torch.bfloat16) + + +@pytest.mark.parametrize('mode', ['training', 'inference']) +def test_reference_entrypoint_uses_expected_dtype_and_teardown(reference, tmp_path, monkeypatch, mode): + """Exercise orchestration with fake model work, not GPU numerical acceptance.""" + model = Mock() + model.cuda.return_value = model + loader = Mock(return_value=model) + monkeypatch.setattr(reference, 'load_model', loader) + monkeypatch.setattr(reference, 'training_reference', Mock(return_value={'loss': 1.0})) + monkeypatch.setattr(reference, 'inference_reference', Mock(return_value={'comparisons': []})) + monkeypatch.setattr(torch.cuda, 'set_device', Mock()) + monkeypatch.setattr(torch.cuda, 'synchronize', Mock()) + cleanup = Mock() + monkeypatch.setattr(torch.cuda, 'empty_cache', cleanup) + monkeypatch.setattr(torch.backends.cuda.matmul, 'allow_tf32', False) + monkeypatch.setenv('TORCH_ALLOW_TF32_CUBLAS_OVERRIDE', '0') + requests = tmp_path / 'requests.json' + requests.write_text('[]') + output = tmp_path / 'report.json' + monkeypatch.setattr( + sys, 'argv', [ + 'reference', + '--checkpoint', + str(tmp_path), + '--mode', + mode, + '--requests', + str(requests), + '--output', + str(output), + ] + ) + reference.main() + report = json.loads(output.read_text()) + expected = torch.bfloat16 if mode == 'training' else torch.float32 + assert loader.call_args[0][1] == expected + assert report['reference_dtype'] == str(expected) + assert report['correctness_passed'] and report['teardown_complete'] and not report['tf32_allowed'] + cleanup.assert_called_once() diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_utils.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_utils.py new file mode 100644 index 000000000..f6ff3756f --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_utils.py @@ -0,0 +1,345 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""CPU-only tests for the standalone worker contract, without framework imports.""" + +import copy +import ctypes +import hashlib +import importlib.util +import math +import os +import signal +import sys +import time +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +WORKER_PATH = Path(__file__).resolve().parents[3] / 'superbench/benchmarks/model_benchmarks/deepseek_v2_lite_utils.py' +SPEC = importlib.util.spec_from_file_location('deepseek_v2_lite_utils_test', WORKER_PATH) +if SPEC is None or SPEC.loader is None: + raise RuntimeError('Cannot load the standalone worker utilities.') +utils = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(utils) + + +def test_checkpoint_identity(): + """Reject architecture proxies and quantization.""" + config = dict(utils.EXPECTED_CONFIG, model_type='deepseek_v2') + utils.validate_config(config) + config['hidden_size'] = 1024 + with pytest.raises(ValueError, match='hidden_size'): + utils.validate_config(config) + config['hidden_size'] = 2048 + config['quantization_config'] = {'quant_method': 'fp8'} + with pytest.raises(ValueError, match='quantized'): + utils.validate_config(config) + assert utils.WEIGHT_BYTES == 31413626576 + + +@pytest.mark.parametrize('field,value', [('seq_aux', False), ('aux_loss_alpha', 0.1), ('attention_dropout', 0.1)]) +def test_fixed_training_semantics_are_part_of_model_identity(field, value): + """Do not silently change the official auxiliary-loss or dropout configuration.""" + config = dict(utils.EXPECTED_CONFIG, model_type='deepseek_v2') + config[field] = value + with pytest.raises(ValueError, match=field): + utils.validate_config(config) + + +def test_packed_text_is_reproducible(): + """Pack actual token inputs with EOS separators, not padding or mock execution.""" + documents = [[1, 2], [3, 4, 5]] + expected = [[1, 2, 9, 3], [4, 5, 9, 1]] + assert utils.packed_tokens(documents, 9, 4, 2) == expected + assert utils.packed_tokens(documents, 9, 4, 2) == expected + assert utils.packed_tokens(documents, 9, 4, 2, offset=1) != expected + + +@pytest.mark.parametrize('documents,length,count', [([], 4, 1), ([[]], 4, 1), ([[True]], 4, 1), ([[1]], 1, 1)]) +def test_invalid_text_inputs(documents, length, count): + """Surface malformed inputs instead of returning an empty batch.""" + with pytest.raises(ValueError): + utils.packed_tokens(documents, 9, length, count) + + +def test_cold_cache_isolated(tmp_path, monkeypatch): + """Reject cache reuse without deleting shared contents.""" + shared = tmp_path / 'shared' + shared.mkdir() + sentinel = shared / 'keep' + sentinel.write_text('unrelated data') + monkeypatch.setenv('HF_HOME', str(shared)) + cache = tmp_path / 'cold' + utils.configure_cache(cache) + assert sentinel.read_text() == 'unrelated data' + assert utils.os.environ['HF_HOME'] == str(cache / 'hf') + assert utils.os.environ['HF_XET_CACHE'] == str(cache / 'xet') + (cache / 'present').touch() + with pytest.raises(ValueError, match='empty'): + utils.configure_cache(cache) + + +@pytest.mark.parametrize('values', [[math.nan], [math.inf], [-1], [0], [True], [], ['1']]) +def test_invalid_metric_series(values): + """Never accept NaNs, sentinels, incomplete samples or success-shaped defaults.""" + with pytest.raises(ValueError): + utils.numeric_series({'step_ms': values}, 'step_ms', 1) + + +def test_report_requires_correctness_and_teardown(): + """Require model identity, not just a successful process exit.""" + report = dict(utils.identity_report(), status='success', correctness_passed=True, teardown_complete=True) + utils.validate_identity(report) + incorrect = copy.deepcopy(report) + incorrect['parameter_count'] = 100 + with pytest.raises(ValueError, match='contract'): + utils.validate_identity(incorrect) + report['correctness_passed'] = False + with pytest.raises(ValueError, match='Correctness'): + utils.validate_identity(report) + + +@pytest.mark.parametrize('length', [1, 512, 209715200, 15706484224]) +def test_large_tensor_probe_indices(length): + """FP32-rounded endpoints must never index beyond a real full-model tensor.""" + indices = utils.uniform_indices(length) + assert len(indices) == 256 + assert indices[0] == 0 and indices[-1] == length - 1 + assert all(0 <= index < length for index in indices) + + +def test_atomic_json_rejects_nonfinite_values(tmp_path): + """A malformed report must not replace a complete report.""" + path = tmp_path / 'report.json' + utils.write_json(path, {'value': 1}) + with pytest.raises(ValueError): + utils.write_json(path, {'value': math.nan}) + assert utils.read_json(path) == {'value': 1} + path.write_text('{"value": NaN}') + with pytest.raises(ValueError, match='Nonfinite'): + utils.read_json(path) + + +def test_worker_failure_is_explicit(tmp_path): + """Reject nonzero exit codes even if the worker writes a result-like message.""" + with pytest.raises(RuntimeError, match='code 7'): + utils.run_worker([sys.executable, '-c', 'print("success"); raise SystemExit(7)'], tmp_path / 'worker.log', 5) + assert 'success' in (tmp_path / 'worker.log').read_text() + + +def test_timeout_reaps_worker(tmp_path): + """A timeout must terminate the created process rather than leave a worker.""" + pid_file = tmp_path / 'pid' + command = [ + sys.executable, + '-c', + 'import os,time; from pathlib import Path; Path({!r}).write_text(str(os.getpid())); time.sleep(60)'.format( + str(pid_file) + ), + ] + with pytest.raises(TimeoutError, match='deadline'): + utils.run_worker(command, tmp_path / 'worker.log', 1) + pid = int(pid_file.read_text()) + with pytest.raises(ProcessLookupError): + utils.os.kill(pid, 0) + + +def test_worker_argv_is_not_a_shell(tmp_path): + """Preserve argument boundaries rather than reinterpret shell metacharacters.""" + output = tmp_path / 'argv' + value = 'a=b; this is one value' + utils.run_worker( + [ + sys.executable, '-c', 'import sys; from pathlib import Path; Path(sys.argv[1]).write_text(sys.argv[2])', + str(output), value + ], tmp_path / 'worker.log', 5 + ) + assert output.read_text() == value + + +def test_success_with_live_child_is_rejected(tmp_path): + """A leader's exit code zero is insufficient when its child remains alive.""" + command = [ + sys.executable, + '-c', + 'import subprocess,sys; subprocess.Popen([sys.executable,"-c","import time; time.sleep(60)"])', + ] + with pytest.raises(RuntimeError, match='descendant processes'): + utils.run_worker(command, tmp_path / 'worker.log', 5) + + +@pytest.mark.parametrize('launcher_exits', [False, True]) +def test_separate_session_child_is_reaped(tmp_path, launcher_exits): + """Own escaped rank sessions even when their launcher exits or ignores termination.""" + pid_file = tmp_path / 'rank.pid' + rank = ( + 'import os,signal,time; from pathlib import Path; ' + 'signal.signal(signal.SIGTERM, signal.SIG_IGN); ' + 'Path({!r}).write_text(str(os.getpid())); time.sleep(60)' + ).format(str(pid_file)) + launcher = ( + 'import signal,subprocess,sys,time; from pathlib import Path; ' + 'signal.signal(signal.SIGTERM, signal.SIG_IGN); ' + 'subprocess.Popen([sys.executable, "-c", {!r}], start_new_session=True); ' + 'ready=Path({!r})\n' + 'while not ready.exists(): time.sleep(0.01)\n' + '{}' + ).format(rank, str(pid_file), 'sys.exit(0)' if launcher_exits else 'time.sleep(60)') + try: + expected = RuntimeError if launcher_exits else TimeoutError + with pytest.raises(expected): + utils.run_worker([sys.executable, '-c', launcher], tmp_path / 'worker.log', 5 if launcher_exits else 1) + pid = int(pid_file.read_text()) + with pytest.raises(ProcessLookupError): + os.kill(pid, 0) + finally: + if pid_file.exists(): + pid = int(pid_file.read_text()) + try: + os.kill(pid, signal.SIGKILL) + except ProcessLookupError: + pass + + +def test_worker_signal_does_not_kill_unrelated_process(tmp_path): + """Timeout cleanup must be scoped to the supervised job, not the controller's children.""" + unrelated = utils.subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)']) + try: + with pytest.raises(TimeoutError): + utils.run_worker([sys.executable, '-c', 'import time; time.sleep(60)'], tmp_path / 'worker.log', 0.2) + assert unrelated.poll() is None + finally: + unrelated.terminate() + unrelated.wait(timeout=5) + + +def test_controller_death_reaps_owned_worker(tmp_path): + """A killed controller must not leave its independently supervised job alive.""" + pid_file = tmp_path / 'worker.pid' + worker = ('import os,time; from pathlib import Path; ' + 'Path({!r}).write_text(str(os.getpid())); time.sleep(60)').format(str(pid_file)) + controller = ( + 'import sys; from pathlib import Path; sys.path.insert(0, {!r}); ' + 'from deepseek_v2_lite_utils import run_worker; ' + 'run_worker([sys.executable, "-c", {!r}], Path({!r}), 60)' + ).format(str(WORKER_PATH.parent), worker, str(tmp_path / 'worker.log')) + process = utils.subprocess.Popen([sys.executable, '-c', controller]) + try: + deadline = time.monotonic() + 5 + while not pid_file.exists() and time.monotonic() < deadline: + time.sleep(0.02) + assert pid_file.exists() + pid = int(pid_file.read_text()) + process.kill() + process.wait(timeout=5) + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + try: + os.kill(pid, 0) + except ProcessLookupError: + break + time.sleep(0.02) + else: + pytest.fail('The worker survived its controller.') + finally: + if process.poll() is None: + process.kill() + process.wait(timeout=5) + if pid_file.exists(): + try: + os.kill(int(pid_file.read_text()), signal.SIGKILL) + except ProcessLookupError: + pass + + +@pytest.fixture +def checkpoint_files(tmp_path, monkeypatch): + """Create small real files to test the checkpoint integrity contract.""" + root = tmp_path / 'checkpoint' + root.mkdir() + contents = b'CPU checkpoint integrity fixture' + shard = root / 'weights.safetensors' + shard.write_bytes(contents) + monkeypatch.setattr(utils, 'WEIGHT_FILES', { + shard.name: (len(contents), hashlib.sha256(contents).hexdigest()), + }) + utils.write_json(root / 'config.json', dict(utils.EXPECTED_CONFIG, model_type='deepseek_v2')) + utils.write_json(root / 'model.safetensors.index.json', {'weight_map': {'fixture.weight': shard.name}}) + return root, shard + + +def test_checkpoint_files_are_verified(checkpoint_files): + """Check file sizes, index membership and SHA256 without claiming model execution.""" + root, _ = checkpoint_files + utils.verify_checkpoint(root) + + +@pytest.mark.parametrize('failure', ['missing', 'size', 'hash', 'index']) +def test_invalid_checkpoint_files_fail(checkpoint_files, failure): + """Corrupted, missing or misindexed shards must never become a valid checkpoint.""" + root, shard = checkpoint_files + if failure == 'missing': + shard.unlink() + elif failure == 'size': + shard.write_bytes(b'short') + elif failure == 'hash': + shard.write_bytes(b'x' * shard.stat().st_size) + else: + utils.write_json(root / 'model.safetensors.index.json', {'weight_map': {'fixture.weight': 'other'}}) + with pytest.raises(ValueError): + utils.verify_checkpoint(root) + + +def test_download_uses_pinned_public_identity_and_then_verifies(checkpoint_files, monkeypatch): + """Disable implicit credentials and require the downloaded shard contract.""" + root, shard = checkpoint_files + download = Mock() + monkeypatch.setitem(sys.modules, 'huggingface_hub', SimpleNamespace(snapshot_download=download)) + assert utils.download_checkpoint(root.parent) == root + arguments = download.call_args[1] + assert arguments['repo_id'] == utils.MODEL_ID + assert arguments['revision'] == utils.REVISION + assert arguments['token'] is False + assert arguments['local_dir'] == str(root) + assert shard.name in arguments['allow_patterns'] + + +@pytest.mark.parametrize('length,count', [(0, 2), (1, 1)]) +def test_invalid_probe_dimensions_fail(length, count): + """Reject undefined probe endpoints instead of silently selecting positions.""" + with pytest.raises(ValueError, match='tensor length'): + utils.uniform_indices(length, count) + + +@pytest.mark.parametrize('timeout', [0, -1, float('nan')]) +def test_invalid_worker_deadline_fails_before_launch(tmp_path, timeout): + """A nonfinite or expired budget must not start a worker.""" + with pytest.raises(TimeoutError): + utils.run_worker([sys.executable, '-c', 'pass'], tmp_path / 'worker.log', timeout) + + +def test_empty_worker_command_fails(tmp_path): + """Do not launch a supervisor with no defined workload.""" + with pytest.raises(ValueError, match='command'): + utils.run_worker([], tmp_path / 'worker.log', 1) + + +def test_worker_interrupt_is_failure(): + """A termination request must unwind the worker's normal success path.""" + with pytest.raises(TimeoutError, match='interrupted'): + utils.interrupt_worker(signal.SIGTERM, None) + + +def test_supervisor_requires_kernel_ownership_support(monkeypatch): + """Fail before spawning when kernel ownership setup is unavailable.""" + monkeypatch.setattr(utils.signal, 'signal', Mock()) + monkeypatch.setattr(ctypes, 'CDLL', lambda *args, **kwargs: SimpleNamespace(prctl=lambda *args: -1)) + monkeypatch.setattr(ctypes, 'get_errno', lambda: 13) + spawn = Mock() + monkeypatch.setattr(utils.subprocess, 'Popen', spawn) + with pytest.raises(OSError): + utils.supervise_worker([sys.executable, '-c', 'pass'], 1, os.getppid()) + spawn.assert_not_called() diff --git a/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py b/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py new file mode 100644 index 000000000..0e9539a8b --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py @@ -0,0 +1,153 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""CPU adapter tests for the standalone complete-generation profile.""" + +from pathlib import Path +from unittest.mock import Mock + +import pytest + +from superbench.benchmarks import BenchmarkType, ReturnCode +from superbench.benchmarks.model_benchmarks import vllm_deepseek_v2_lite as adapter +from superbench.benchmarks.model_benchmarks.deepseek_v2_lite_utils import identity_report, write_json + + +@pytest.fixture +def benchmark(tmp_path, monkeypatch): + """Use one local replica and an isolated output root.""" + monkeypatch.delenv('WORLD_SIZE', raising=False) + monkeypatch.delenv('OMPI_COMM_WORLD_SIZE', raising=False) + return adapter.DeepSeekV2LiteInference( + 'deepseek-v2-lite-inference', + '--cache_root "{}" --num_steps 2 --batch_size 2 --seq_len 64 --duration 60'.format(tmp_path), + ) + + +def successful_worker(command, log, timeout): + """Provide validated-shaped fixtures, not actual GPU measurements.""" + output = Path(command[command.index('--output') + 1]) + report = dict( + identity_report(), + status='success', + correctness_passed=True, + teardown_complete=True, + step_ms=[10.0, 20.0], + input_token_counts=[64, 64, 64, 64], + output_token_counts=[1, 4, 3, 2], + request_prefill_ms=[1.0] * 4, + ttft_ms=[2.0] * 4, + decode_tpot_ms=[3.0] * 3, + request_count=4, + num_gpus=1, + ) + write_json(output, report) + + +def test_counts_and_model_result_shape(benchmark, monkeypatch): + """Account for ten real output tokens, not four times the requested maximum.""" + monkeypatch.setattr(adapter, 'run_worker', successful_worker) + assert benchmark.run() + assert benchmark.type == BenchmarkType.MODEL + assert benchmark.return_code == ReturnCode.SUCCESS + assert benchmark.result['actual_output_tokens'] == [10.0] + assert benchmark.result['bf16_inference_output_tokens_per_second'] == [10 * 1000 / 30] + assert benchmark.raw_data['bf16_inference_output_token_count'] == [[1.0, 4.0, 3.0, 2.0]] + + +@pytest.mark.parametrize( + 'parameters', [ + '--seq_len 0', '--batch_size 0', '--max_new_tokens 1', '--num_steps 0', '--num_warmup -1', + '--gpu_memory_utilization nan', '--duration 3600', '--run_count 2', '--precision float16' + ] +) +def test_invalid_profiles(parameters): + """Reject unsupported precisions, dimensions and multi-profile timing.""" + instance = adapter.DeepSeekV2LiteInference('deepseek-v2-lite-inference', parameters) + assert not instance.run() + assert instance.return_code == ReturnCode.INVALID_ARGUMENT + + +@pytest.mark.parametrize( + 'field,value', [ + ('output_token_counts', [1, 4, 3, 65]), ('output_token_counts', [1, 4, 3, 1.5]), + ('input_token_counts', [63, 64, 64, 64]), ('ttft_ms', [0] * 4), ('decode_tpot_ms', [3.0] * 4), + ('correctness_passed', False), ('teardown_complete', False) + ] +) +def test_reject_invalid_generation_reports(benchmark, monkeypatch, field, value): + """Validate output shapes and thresholds instead of accepting exit code zero.""" + def invalid_worker(command, log, timeout): + successful_worker(command, log, timeout) + output = Path(command[command.index('--output') + 1]) + report = adapter.read_json(output) + report[field] = value + write_json(output, report) + + monkeypatch.setattr(adapter, 'run_worker', invalid_worker) + assert not benchmark.run() + assert benchmark.return_code == ReturnCode.RUNTIME_EXCEPTION_ERROR + + +def test_deadline_failure(benchmark, monkeypatch): + """A watchdog exit cannot be reported as a successful under-hour run.""" + def timeout(command, log, seconds): + raise TimeoutError('whole job deadline') + + monkeypatch.setattr(adapter, 'run_worker', timeout) + assert not benchmark.run() + assert benchmark.return_code == ReturnCode.KILLED_BY_TIMEOUT + + +def test_h100_policy_cannot_use_an_unqualified_shape(benchmark): + """Keep calibration/profile compatibility fail-closed in the frontend.""" + instance = adapter.DeepSeekV2LiteInference('deepseek-v2-lite-inference', '--numerical_policy h100_bf16_v6') + assert not instance.run() + assert instance.return_code == ReturnCode.INVALID_ARGUMENT + + +@pytest.mark.parametrize('fault', [None, 'policy', 'batch-invariance', 'reference']) +def test_h100_adapter_requires_matching_numerical_evidence(tmp_path, monkeypatch, fault): + """Validate the selected policy before publishing performance or numerical counters.""" + arguments = '--cache_root "{}" --numerical_policy h100_bf16_v6 --num_steps 256'.format(tmp_path) + instance = adapter.DeepSeekV2LiteInference('deepseek-v2-lite-inference', arguments) + validator = Mock(side_effect=ValueError('bad reference') if fault == 'reference' else None) + monkeypatch.setattr(adapter.numerics, 'validate_reference_result', validator) + + def worker(command, log, timeout): + assert command[command.index('--numerical_policy') + 1] == adapter.numerics.POLICY + report = dict( + identity_report(), + status='success', + correctness_passed=True, + teardown_complete=True, + step_ms=[10.0] * 256, + input_token_counts=[512] * 2048, + output_token_counts=[64] * 2048, + request_prefill_ms=[1.0] * 2048, + ttft_ms=[2.0] * 2048, + decode_tpot_ms=[3.0] * 2048, + request_count=2048, + num_gpus=1, + numerical_policy=adapter.numerics.POLICY, + batch_invariant=True, + reference={ + 'positive_positions': 3216, + 'negative_positions': 6438 + }, + ) + if fault == 'policy': + report['numerical_policy'] = 'strict_fp32' + if fault == 'batch-invariance': + report['batch_invariant'] = False + write_json(Path(command[command.index('--output') + 1]), report) + + monkeypatch.setattr(adapter, 'run_worker', worker) + assert instance.run() is (fault is None) + if fault is None: + assert instance.return_code == ReturnCode.SUCCESS + assert instance.result['numerical_reference_positions'] == [3216] + assert instance.result['numerical_fault_rejections'] == [6438] + validator.assert_called_once_with({'positive_positions': 3216, 'negative_positions': 6438}) + else: + assert instance.return_code == ReturnCode.RUNTIME_EXCEPTION_ERROR From 89cfb7afd04046029d450891fcfc6303e0f8fd29 Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Wed, 28 Oct 2026 18:17:50 +0000 Subject: [PATCH 2/8] Benchmarks - Remove the per-run V2-Lite inference model cache Delete each run's downloaded checkpoint cache after the worker exits, on success, failure or timeout, while keeping its report and logs. A cleanup error is logged without discarding a validated measurement; a runner timeout during cleanup is still reported as a timeout. Require cache_root instead of defaulting to a relative directory inside the SuperBench output tree. Declare numerical_policy as a string so `sb benchmark list-parameters` can render it. Describe the validated H100 scope in the documentation, and mark the numerics module's script-mode import for type checking without changing executable code. Refer to the numerical contract by path, because the docs build cannot bundle a linked JSON file. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../benchmarks/model-benchmarks.md | 16 ++-- .../deepseek_v2_lite_numerics.py | 2 +- .../model_benchmarks/vllm_deepseek_v2_lite.py | 34 +++++++- .../test_vllm_deepseek_v2_lite.py | 81 ++++++++++++++++++- 4 files changed, 120 insertions(+), 13 deletions(-) diff --git a/docs/user-tutorial/benchmarks/model-benchmarks.md b/docs/user-tutorial/benchmarks/model-benchmarks.md index 6692c5147..eafd869a4 100644 --- a/docs/user-tutorial/benchmarks/model-benchmarks.md +++ b/docs/user-tutorial/benchmarks/model-benchmarks.md @@ -188,7 +188,7 @@ enabled; all-first-token-EOS output does not satisfy the cached-decode workload. #### Validation Status -This remains a draft implementation. The explicit `h100_bf16_v6` numerical +The explicit `h100_bf16_v6` numerical method has passed independent-reference checks and all six preregistered H100 engine windows: 3,216 positive positions pass and all 6,438 fixed fault cases are rejected. The recorded public runtime completed a download-inclusive cold @@ -196,8 +196,8 @@ bootstrap in 1323.74 seconds. Its opt-in internal package then passed three ordinary-entrypoint cold repetitions in 1339.17, 1342.39 and 1329.00 seconds, with complete diagnosis, 97.85-98.32% mean GPU busy and a maximum throughput deviation of 0.334% from the median. Each repetition includes all numerical checks. -These results qualify the recorded local source/image/profile snapshot, not an -unchanged older PR head, a later rebuilt image, another SKU or production deployment. +These results apply to the recorded Standard_ND96isrf_H100_v5 source, image and +profile, not to a rebuilt image, another SKU or production deployment. Do not replace numerical validation with matching generated tokens or exit code zero. The adapter default remains `numerical_policy=strict_fp32`, preserving the @@ -206,7 +206,7 @@ H100, batch 8, sequence 512, maximum decode 64, two warmup batches and 256 measured batches. It uses compiled, batch-invariant BF16 inference with the compressed-MLA implementation; there is no FP32 measured-model fallback. -The [shipped numerical contract](../../../superbench/config/deepseek-v2-lite-h100-numerics.json) +The shipped numerical contract, `superbench/config/deepseek-v2-lite-h100-numerics.json`, is bound to an exact SHA256 by the worker. After engine shutdown, independent official BF16 cached execution measures the precision discrepancy on the same fixed input prefixes; an FP32 model then recomputes every complete prefix. @@ -307,8 +307,12 @@ not a claim that the model intrinsically requires H100 or eight GPUs. #### Timing And Metrics -Every invocation uses a new empty HF/Hub/Xet/module cache without deleting shared -caches. One `duration <3600s` covers model download, complete weight hashes, +`cache_root` is required. Every invocation creates a new directory under it with +an empty HF/Hub/Xet/module cache, its report and logs. After the worker exits, +the adapter deletes that 31.4GB model cache and keeps the report and logs; +shared caches outside `cache_root` are not touched. + +One `duration <3600s` covers model download, complete weight hashes, loading, graph/kernel preparation, warmup, measured generation, reference checks, result writing and worker teardown. The controller reserves cleanup time and rejects watchdog exits. Image pulls, dependency installation and controller diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_numerics.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_numerics.py index 2b2ed6e4b..a046e2ff2 100644 --- a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_numerics.py +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_numerics.py @@ -15,7 +15,7 @@ if __package__: from .deepseek_v2_lite_utils import packed_tokens, read_json, write_json else: - from deepseek_v2_lite_utils import packed_tokens, read_json, write_json + from deepseek_v2_lite_utils import packed_tokens, read_json, write_json # type: ignore[no-redef] METHOD = 'bf16-input-matched-probability-log-v6' POLICY = 'h100_bf16_v6' diff --git a/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py b/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py index a11c6551d..4c8b57c9f 100644 --- a/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py +++ b/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py @@ -4,6 +4,7 @@ """SuperBench adapter for isolated official-checkpoint V2-Lite generation.""" import os +import shutil import statistics import sys import tempfile @@ -19,6 +20,22 @@ ) +def _remove_model_cache(cache): + """Delete one run's downloaded model cache after its worker exits, keeping reports and logs.""" + if not cache.exists(): + return + start = time.monotonic() + try: + shutil.rmtree(cache) + except TimeoutError: + # The SuperBench SIGTERM handler raises TimeoutError, an OSError subclass; keep it fatal. + raise + except OSError as error: + logger.error('Failed to remove the V2-Lite model cache %s: %s', cache, error) + return + logger.info('Removed the V2-Lite model cache %s in %.1f seconds.', cache, time.monotonic() - start) + + class DeepSeekV2LiteInference(Benchmark): """Benchmark one BF16 inference replica, not a training or forward-only loop.""" def __init__(self, name, parameters=''): @@ -32,20 +49,29 @@ def add_parser_arguments(self): self._parser.set_defaults(duration=3300) self._parser.add_argument('--runtime_python', type=str, default=sys.executable) self._parser.add_argument('--reference_python', type=str, default='/opt/deepseek-reference/bin/python') - self._parser.add_argument('--cache_root', type=str, default='model-cache') + self._parser.add_argument( + '--cache_root', + type=str, + default=None, + help='Required directory for per-run reports, logs and the temporary model cache.', + ) self._parser.add_argument('--batch_size', type=int, default=8) self._parser.add_argument('--seq_len', type=int, default=512) self._parser.add_argument('--max_new_tokens', type=int, default=64) self._parser.add_argument('--num_warmup', type=int, default=2) self._parser.add_argument('--num_steps', type=int, default=8) self._parser.add_argument('--gpu_memory_utilization', type=float, default=0.8) - self._parser.add_argument('--numerical_policy', choices=numerics.POLICIES, default='strict_fp32') + self._parser.add_argument('--numerical_policy', type=str, choices=numerics.POLICIES, default='strict_fp32') def _preprocess(self): """Reject duplicate launchers and unsupported profile settings explicitly.""" if not super()._preprocess(): return False args = self._args + if not args.cache_root: + logger.error('V2-Lite inference requires cache_root for its per-run model cache, reports and logs.') + self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) + return False try: world_size = int(os.environ.get('WORLD_SIZE', os.environ.get('OMPI_COMM_WORLD_SIZE', '1'))) except ValueError: @@ -109,6 +135,7 @@ def _validate_numerical_report(self, report): def _benchmark(self): """Accept actual request/token counters and complete numeric validation.""" start = time.monotonic() + job = None try: root = Path(self._args.cache_root).resolve() root.mkdir(parents=True, exist_ok=True) @@ -159,6 +186,9 @@ def _benchmark(self): logger.error('V2-Lite inference failed: %s', error) self._result.set_return_code(ReturnCode.RUNTIME_EXCEPTION_ERROR) return False + finally: + if job is not None: + _remove_model_cache(job / 'cache') BenchmarkRegistry.register_benchmark('deepseek-v2-lite-inference', DeepSeekV2LiteInference, platform=Platform.CUDA) diff --git a/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py b/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py index 0e9539a8b..e9a09a60b 100644 --- a/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py +++ b/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py @@ -61,13 +61,31 @@ def test_counts_and_model_result_shape(benchmark, monkeypatch): '--gpu_memory_utilization nan', '--duration 3600', '--run_count 2', '--precision float16' ] ) -def test_invalid_profiles(parameters): +def test_invalid_profiles(tmp_path, parameters): """Reject unsupported precisions, dimensions and multi-profile timing.""" - instance = adapter.DeepSeekV2LiteInference('deepseek-v2-lite-inference', parameters) + instance = adapter.DeepSeekV2LiteInference( + 'deepseek-v2-lite-inference', '--cache_root "{}" {}'.format(tmp_path, parameters) + ) + assert not instance.run() + assert instance.return_code == ReturnCode.INVALID_ARGUMENT + + +def test_cache_root_is_required(): + """Refuse to choose an implicit location for the per-run model cache.""" + instance = adapter.DeepSeekV2LiteInference('deepseek-v2-lite-inference', '--num_steps 2') assert not instance.run() assert instance.return_code == ReturnCode.INVALID_ARGUMENT +def test_parameters_render_in_help(): + """Keep every option compatible with the typed SuperBench help formatter.""" + instance = adapter.DeepSeekV2LiteInference('deepseek-v2-lite-inference') + instance.add_parser_arguments() + settings = instance.get_configurable_settings() + assert '--numerical_policy' in settings + assert '--cache_root' in settings + + @pytest.mark.parametrize( 'field,value', [ ('output_token_counts', [1, 4, 3, 65]), ('output_token_counts', [1, 4, 3, 1.5]), @@ -99,9 +117,64 @@ def timeout(command, log, seconds): assert benchmark.return_code == ReturnCode.KILLED_BY_TIMEOUT -def test_h100_policy_cannot_use_an_unqualified_shape(benchmark): +@pytest.mark.parametrize('outcome', ['success', 'failure', 'timeout']) +def test_model_cache_is_removed_after_every_run(benchmark, monkeypatch, outcome): + """Delete the per-run checkpoint cache on every exit path while keeping reports and logs.""" + jobs = [] + + def worker(command, log, timeout): + cache = Path(command[command.index('--cache_dir') + 1]) + (cache / 'checkpoint').mkdir(parents=True) + (cache / 'checkpoint' / 'model-00001-of-000004.safetensors').write_bytes(b'weights') + log.write_text('worker log\n') + jobs.append(cache.parent) + if outcome == 'failure': + raise RuntimeError('worker failed') + if outcome == 'timeout': + raise TimeoutError('whole job deadline') + successful_worker(command, log, timeout) + + monkeypatch.setattr(adapter, 'run_worker', worker) + assert benchmark.run() is (outcome == 'success') + assert not (jobs[0] / 'cache').exists() + assert (jobs[0] / 'worker.log').read_text() == 'worker log\n' + assert (jobs[0] / 'report.json').is_file() is (outcome == 'success') + + +def test_cache_removal_failure_keeps_a_valid_measurement(benchmark, monkeypatch): + """Log a cleanup error without discarding metrics that were already validated.""" + caches = [] + + def worker(command, log, timeout): + cache = Path(command[command.index('--cache_dir') + 1]) + cache.mkdir(parents=True) + caches.append(cache) + successful_worker(command, log, timeout) + + monkeypatch.setattr(adapter, 'run_worker', worker) + monkeypatch.setattr(adapter.shutil, 'rmtree', Mock(side_effect=PermissionError('read-only cache'))) + assert benchmark.run() + assert benchmark.return_code == ReturnCode.SUCCESS + assert caches[0].is_dir() + + +def test_sigterm_during_cache_removal_still_reports_timeout(benchmark, monkeypatch): + """A runner timeout during cleanup must not be reported as a completed run.""" + def worker(command, log, timeout): + Path(command[command.index('--cache_dir') + 1]).mkdir(parents=True) + successful_worker(command, log, timeout) + + monkeypatch.setattr(adapter, 'run_worker', worker) + monkeypatch.setattr(adapter.shutil, 'rmtree', Mock(side_effect=TimeoutError('Killed by SIGTERM or timeout!'))) + benchmark.run() + assert benchmark.return_code == ReturnCode.KILLED_BY_TIMEOUT + + +def test_h100_policy_cannot_use_an_unqualified_shape(benchmark, tmp_path): """Keep calibration/profile compatibility fail-closed in the frontend.""" - instance = adapter.DeepSeekV2LiteInference('deepseek-v2-lite-inference', '--numerical_policy h100_bf16_v6') + instance = adapter.DeepSeekV2LiteInference( + 'deepseek-v2-lite-inference', '--cache_root "{}" --numerical_policy h100_bf16_v6'.format(tmp_path) + ) assert not instance.run() assert instance.return_code == ReturnCode.INVALID_ARGUMENT From 2f41595721da12f66cf7f8a4a2e36623b21a68f6 Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Thu, 29 Oct 2026 20:06:19 +0000 Subject: [PATCH 3/8] Benchmarks - Bound V2-Lite inference cache cleanup Include model-cache cleanup in the download-inclusive deadline and end-to-end timing. Bound and reap the cleanup process on timeout, retain failure-path cleanup, and finalize success only afterward. Clarify the strict FP32 and input-matched H100 numerical guarantees and add lifecycle regression coverage. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../benchmarks/model-benchmarks.md | 52 +++++---- .../model_benchmarks/vllm_deepseek_v2_lite.py | 83 +++++++++----- .../test_vllm_deepseek_v2_lite.py | 107 +++++++++++++++++- 3 files changed, 189 insertions(+), 53 deletions(-) diff --git a/docs/user-tutorial/benchmarks/model-benchmarks.md b/docs/user-tutorial/benchmarks/model-benchmarks.md index eafd869a4..7ddcf1fd0 100644 --- a/docs/user-tutorial/benchmarks/model-benchmarks.md +++ b/docs/user-tutorial/benchmarks/model-benchmarks.md @@ -269,20 +269,30 @@ read-only and provide a writable, dedicated result/cache directory. #### Correctness And Lifecycle The engine exercises variable-length batched prompts, single requests and forced -EOS termination. Outputs must match the submitted prompt token IDs. A separate -unsharded official-code FP32 reference, with TF32 disabled, then checks -prefill and multiple decode steps on the same token prefixes, comparing cached -and complete-prefix logits across the vocabulary and sampled engine top-token -log probabilities and requires greedy token agreement. Sampled engine -probabilities do not constitute an exhaustive -comparison of the engine's full vocabulary logits or all expert routing paths. -Correctness, complete requests, finite timestamps and actual token counts must -all pass; a plausible generated sentence or process exit zero is insufficient. -Numerical records must contain the requested top-20 log probabilities, not only -the selected token. For long selected requests, every generated token is checked -against the cached FP32 reference; full-prefix recomputation checks the first, -second, middle and final positions. A position without full-prefix recomputation -is explicitly marked rather than reporting a fabricated zero cache error. +EOS termination. Outputs must match the submitted prompt token IDs. The numerical +checks depend on the selected policy: + +- `strict_fp32` (adapter default) uses a separate unsharded official-code FP32 + reference with TF32 disabled and requires exact greedy-token agreement. + For long selected requests, every generated position is checked; cached FP32 + execution supplies the reference between full-prefix checks at the first, + second, middle and final positions. Those full-prefix checks also compare + cached and complete-prefix logits across the vocabulary. Positions without + full-prefix recomputation are marked rather than given a fabricated zero + cache error. +- `h100_bf16_v6` (supplied H100 profile) measures the input-matched discrepancy + with official BF16 cached execution and recomputes every retained prefix in + FP32, not just selected full-prefix positions. It can accept a different + greedy token when the token is greedy for the engine and its FP32 probability + gap is within the input-matched bound. All three numerical metrics and the + required fault rejections must also pass. A successful H100 check therefore + does not imply exact agreement with FP32-generated tokens. + +Both policies require the requested top-20 engine log probabilities, not only +the selected token. These records are not an exhaustive comparison of the +engine's full-vocabulary logits or all expert routing paths. Correctness, +complete requests, finite timestamps and actual token counts must all pass; +a plausible generated sentence or process exit zero is insufficient. Engine model residency is BF16, with no quantized or offloaded fallback. The router uses FP32 to match the official gate. NVIDIA TF32, vLLM FP32 matmul @@ -309,13 +319,17 @@ not a claim that the model intrinsically requires H100 or eight GPUs. `cache_root` is required. Every invocation creates a new directory under it with an empty HF/Hub/Xet/module cache, its report and logs. After the worker exits, -the adapter deletes that 31.4GB model cache and keeps the report and logs; -shared caches outside `cache_root` are not touched. +the adapter attempts to delete that 31.4GB model cache within the remaining +job budget, including on failure paths, and keeps the report and logs. +Shared caches outside `cache_root` are not touched. A cleanup timeout fails the +run; other filesystem errors are logged without discarding validated measurements. +Failed or interrupted cleanup can leave a cache at the logged path. One `duration <3600s` covers model download, complete weight hashes, loading, graph/kernel preparation, warmup, measured generation, reference checks, -result writing and worker teardown. The controller reserves cleanup time and -rejects watchdog exits. Image pulls, dependency installation and controller +result writing, worker teardown and model-cache cleanup. The controller finalizes +the total elapsed time and success result after cleanup and rejects watchdog +exits. Image pulls, dependency installation and controller installation are separate preparation steps, not certified by the model-cold timer. @@ -334,7 +348,7 @@ clock. CPU regression tests cover warmup exclusion and mixed EOS/decode counts. | `bf16_inference_decode_tpot` | ms/token | First-to-last-token span divided by actual decode intervals | | `successful_requests` | requests | Completed measured requests | | `actual_output_tokens` | tokens | Actual measured output IDs, not the configured maximum | -| `end_to_end_seconds` | s | Complete worker launch through teardown/report validation | +| `end_to_end_seconds` | s | Complete invocation through report validation and model-cache cleanup | Request prefill/decode timestamps are not isolated GPU kernel timings. One-token EOS requests contribute to total tokens and latency but not to TPOT. diff --git a/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py b/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py index 4c8b57c9f..3980b8f20 100644 --- a/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py +++ b/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py @@ -4,8 +4,8 @@ """SuperBench adapter for isolated official-checkpoint V2-Lite generation.""" import os -import shutil import statistics +import subprocess import sys import tempfile import time @@ -20,20 +20,37 @@ ) -def _remove_model_cache(cache): - """Delete one run's downloaded model cache after its worker exits, keeping reports and logs.""" - if not cache.exists(): - return +def _remove_model_cache(cache: Path, deadline: float) -> None: + """Delete one run's model cache within the remaining budget, keeping reports and logs.""" 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: - shutil.rmtree(cache) + subprocess.run( + [ + sys.executable, '-c', + 'import os, shutil, sys\nif os.path.exists(sys.argv[1]):\n shutil.rmtree(sys.argv[1])', + 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('Removed the V2-Lite model cache %s in %.1f seconds.', cache, time.monotonic() - start) + logger.info('V2-Lite model cache cleanup completed for %s in %.1f seconds.', cache, time.monotonic() - start) class DeepSeekV2LiteInference(Benchmark): @@ -132,33 +149,42 @@ def _validate_numerical_report(self, report): raise ValueError('The worker did not execute the selected H100 numerical policy.') numerics.validate_reference_result(report.get('reference')) + def _validate_generation_counts(self, report, inputs, outputs): + """Check the frozen request shape and return the number of requests with decode intervals.""" + requests = self._args.num_steps * self._args.batch_size + decode_count = sum(value > 1 for value in outputs) + if decode_count == 0 or report.get('request_count') != requests or report.get('num_gpus') != 1: + raise ValueError('Generation did not complete the requested replica/cache workload.') + if any(value != self._args.seq_len for value in inputs): + raise ValueError('Input token counts differ from the frozen prompt shape.') + if any(not value.is_integer() or value > self._args.max_new_tokens for value in outputs): + raise ValueError('Actual generated token counts are invalid.') + return decode_count + def _benchmark(self): """Accept actual request/token counters and complete numeric validation.""" start = time.monotonic() - job = None + deadline = start + self._args.duration try: root = Path(self._args.cache_root).resolve() root.mkdir(parents=True, exist_ok=True) job = Path(tempfile.mkdtemp(prefix='v2lite-inference-', dir=str(root))) - logger.info('V2-Lite inference evidence and isolated cache: %s', job) - run_worker(self._worker_command(job), job / 'worker.log', self._args.duration - 20) - report = read_json(job / 'report.json') - validate_identity(report) - self._validate_numerical_report(report) - requests = self._args.num_steps * self._args.batch_size - steps = numeric_series(report, 'step_ms', self._args.num_steps) - inputs = numeric_series(report, 'input_token_counts', requests) - outputs = numeric_series(report, 'output_token_counts', requests) - prefills = numeric_series(report, 'request_prefill_ms', requests) - ttfts = numeric_series(report, 'ttft_ms', requests) - decode_count = sum(value > 1 for value in outputs) - tpots = numeric_series(report, 'decode_tpot_ms', decode_count) - if decode_count == 0 or report.get('request_count') != requests or report.get('num_gpus') != 1: - raise ValueError('Generation did not complete the requested replica/cache workload.') - if any(value != self._args.seq_len for value in inputs): - raise ValueError('Input token counts differ from the frozen prompt shape.') - if any(not value.is_integer() or value > self._args.max_new_tokens for value in outputs): - raise ValueError('Actual generated token counts are invalid.') + try: + logger.info('V2-Lite inference evidence and isolated cache: %s', job) + run_worker(self._worker_command(job), job / 'worker.log', deadline - time.monotonic() - 20) + report = read_json(job / 'report.json') + validate_identity(report) + self._validate_numerical_report(report) + requests = self._args.num_steps * self._args.batch_size + steps = numeric_series(report, 'step_ms', self._args.num_steps) + inputs = numeric_series(report, 'input_token_counts', requests) + outputs = numeric_series(report, 'output_token_counts', requests) + prefills = numeric_series(report, 'request_prefill_ms', requests) + ttfts = numeric_series(report, 'ttft_ms', requests) + decode_count = self._validate_generation_counts(report, inputs, outputs) + tpots = numeric_series(report, 'decode_tpot_ms', decode_count) + finally: + _remove_model_cache(job / 'cache', deadline) total = time.monotonic() - start if total >= self._args.duration: raise TimeoutError('Complete inference job exceeded its duration.') @@ -186,9 +212,6 @@ def _benchmark(self): logger.error('V2-Lite inference failed: %s', error) self._result.set_return_code(ReturnCode.RUNTIME_EXCEPTION_ERROR) return False - finally: - if job is not None: - _remove_model_cache(job / 'cache') BenchmarkRegistry.register_benchmark('deepseek-v2-lite-inference', DeepSeekV2LiteInference, platform=Platform.CUDA) diff --git a/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py b/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py index e9a09a60b..de3174659 100644 --- a/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py +++ b/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py @@ -3,7 +3,11 @@ """CPU adapter tests for the standalone complete-generation profile.""" +import subprocess +import sys +import time from pathlib import Path +from types import SimpleNamespace from unittest.mock import Mock import pytest @@ -141,9 +145,15 @@ def worker(command, log, timeout): assert (jobs[0] / 'report.json').is_file() is (outcome == 'success') -def test_cache_removal_failure_keeps_a_valid_measurement(benchmark, monkeypatch): +@pytest.mark.parametrize( + 'failure', + [PermissionError('read-only cache'), + subprocess.CalledProcessError(1, ['cleanup'], output='read-only cache')] +) +def test_cache_removal_failure_keeps_a_valid_measurement(benchmark, monkeypatch, failure): """Log a cleanup error without discarding metrics that were already validated.""" caches = [] + log_error = Mock() def worker(command, log, timeout): cache = Path(command[command.index('--cache_dir') + 1]) @@ -152,10 +162,13 @@ def worker(command, log, timeout): successful_worker(command, log, timeout) monkeypatch.setattr(adapter, 'run_worker', worker) - monkeypatch.setattr(adapter.shutil, 'rmtree', Mock(side_effect=PermissionError('read-only cache'))) + monkeypatch.setattr(adapter.subprocess, 'run', Mock(side_effect=failure)) + monkeypatch.setattr(adapter.logger, 'error', log_error) assert benchmark.run() assert benchmark.return_code == ReturnCode.SUCCESS assert caches[0].is_dir() + log_error.assert_called_once() + assert 'read-only cache' in str(log_error.call_args[0][-1]) def test_sigterm_during_cache_removal_still_reports_timeout(benchmark, monkeypatch): @@ -165,9 +178,95 @@ def worker(command, log, timeout): successful_worker(command, log, timeout) monkeypatch.setattr(adapter, 'run_worker', worker) - monkeypatch.setattr(adapter.shutil, 'rmtree', Mock(side_effect=TimeoutError('Killed by SIGTERM or timeout!'))) - benchmark.run() + monkeypatch.setattr(adapter.subprocess, 'run', Mock(side_effect=TimeoutError('Killed by SIGTERM or timeout!'))) + assert not benchmark.run() assert benchmark.return_code == ReturnCode.KILLED_BY_TIMEOUT + assert 'end_to_end_seconds' not in benchmark.result + + +@pytest.mark.parametrize('cleanup_seconds', [7, 50, 70]) +def test_cache_cleanup_counts_toward_the_job_deadline(benchmark, monkeypatch, cleanup_seconds): + """Include cleanup in elapsed time and reject the exact deadline as well as an overrun.""" + clock = [100.0] + run_cleanup = subprocess.run + + def worker(command, log, timeout): + assert timeout == 40 + Path(command[command.index('--cache_dir') + 1]).mkdir(parents=True) + successful_worker(command, log, timeout) + clock[0] += 10 + + def cleanup(command, **kwargs): + assert kwargs['timeout'] == 50 + result = run_cleanup(command, **kwargs) + clock[0] += cleanup_seconds + return result + + monkeypatch.setattr(adapter, 'time', SimpleNamespace(monotonic=lambda: clock[0])) + monkeypatch.setattr(adapter, 'run_worker', worker) + monkeypatch.setattr(adapter.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_inference_output_tokens_per_second'] == [10 * 1000 / 30] + else: + assert benchmark.return_code == ReturnCode.KILLED_BY_TIMEOUT + assert 'end_to_end_seconds' not in benchmark.result + assert 'bf16_inference_output_tokens_per_second' not in benchmark.result + + +def test_cache_cleanup_does_not_start_after_the_deadline(benchmark, monkeypatch): + """Retain the cache with an explicit timeout instead of starting unbounded cleanup.""" + clock = [100.0] + cleanup = Mock() + caches = [] + + def worker(command, log, timeout): + cache = Path(command[command.index('--cache_dir') + 1]) + cache.mkdir(parents=True) + caches.append(cache) + successful_worker(command, log, timeout) + clock[0] += 60 + + monkeypatch.setattr(adapter, 'time', SimpleNamespace(monotonic=lambda: clock[0])) + monkeypatch.setattr(adapter, 'run_worker', worker) + monkeypatch.setattr(adapter.subprocess, 'run', cleanup) + assert not benchmark.run() + assert benchmark.return_code == ReturnCode.KILLED_BY_TIMEOUT + assert caches[0].is_dir() + cleanup.assert_not_called() + + +@pytest.mark.parametrize('interrupted', [False, True]) +def test_cache_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(adapter.subprocess, 'Popen', stalled_cleanup) + start = time.monotonic() + try: + with pytest.raises(TimeoutError): + adapter._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) def test_h100_policy_cannot_use_an_unqualified_shape(benchmark, tmp_path): From 49a43209722030e9a621fea708f3f459615b1fd4 Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Thu, 29 Oct 2026 21:42:38 +0000 Subject: [PATCH 4/8] Benchmarks - Keep V2-Lite inference failures during cache cleanup Move bounded model-cache removal into a module shared with the training benchmark. Successful runs still finish cleanup within the duration, and a cleanup timeout still fails the run. After a failed or timed-out run, cleanup may continue until the job deadline or for 60 seconds, whichever ends later, and an unfinished cleanup is logged instead of replacing the original error. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../benchmarks/model-benchmarks.md | 13 ++- .../deepseek_v2_lite_cache.py | 60 ++++++++++ .../model_benchmarks/vllm_deepseek_v2_lite.py | 43 ++----- .../test_deepseek_v2_lite_cache.py | 110 ++++++++++++++++++ .../test_vllm_deepseek_v2_lite.py | 92 ++++++++------- 5 files changed, 233 insertions(+), 85 deletions(-) create mode 100644 superbench/benchmarks/model_benchmarks/deepseek_v2_lite_cache.py create mode 100644 tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_cache.py diff --git a/docs/user-tutorial/benchmarks/model-benchmarks.md b/docs/user-tutorial/benchmarks/model-benchmarks.md index 7ddcf1fd0..403e717c1 100644 --- a/docs/user-tutorial/benchmarks/model-benchmarks.md +++ b/docs/user-tutorial/benchmarks/model-benchmarks.md @@ -319,11 +319,14 @@ not a claim that the model intrinsically requires H100 or eight GPUs. `cache_root` is required. Every invocation creates a new directory under it with an empty HF/Hub/Xet/module cache, its report and logs. After the worker exits, -the adapter attempts to delete that 31.4GB model cache within the remaining -job budget, including on failure paths, and keeps the report and logs. -Shared caches outside `cache_root` are not touched. A cleanup timeout fails the -run; other filesystem errors are logged without discarding validated measurements. -Failed or interrupted cleanup can leave a cache at the logged path. +the adapter deletes that 31.4GB model cache and keeps the report and logs; +shared caches outside `cache_root` are not touched. On a successful run, cleanup +must finish within `duration`; otherwise the run fails as a timeout. After a +failed or timed-out run, cleanup may continue until the job deadline or for +60 seconds, whichever ends later; an unfinished cleanup is logged without +replacing the original error. Other filesystem errors are logged without +discarding validated measurements. Interrupted cleanup can leave a cache at the +logged path. One `duration <3600s` covers model download, complete weight hashes, loading, graph/kernel preparation, warmup, measured generation, reference checks, 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/vllm_deepseek_v2_lite.py b/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py index 3980b8f20..07b9266cb 100644 --- a/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py +++ b/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py @@ -5,7 +5,6 @@ import os import statistics -import subprocess import sys import tempfile import time @@ -15,44 +14,14 @@ from superbench.benchmarks.base import Benchmark from superbench.common.utils import logger from superbench.benchmarks.model_benchmarks import deepseek_v2_lite_numerics as numerics +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_utils import ( numeric_series, read_json, run_worker, validate_identity ) -def _remove_model_cache(cache: Path, deadline: float) -> None: - """Delete one run's model cache within the remaining budget, keeping reports and logs.""" - 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: - subprocess.run( - [ - sys.executable, '-c', - 'import os, shutil, sys\nif os.path.exists(sys.argv[1]):\n shutil.rmtree(sys.argv[1])', - 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) - - class DeepSeekV2LiteInference(Benchmark): """Benchmark one BF16 inference replica, not a training or forward-only loop.""" def __init__(self, name, parameters=''): @@ -183,8 +152,10 @@ def _benchmark(self): ttfts = numeric_series(report, 'ttft_ms', requests) decode_count = self._validate_generation_counts(report, inputs, outputs) tpots = numeric_series(report, 'decode_tpot_ms', decode_count) - finally: - _remove_model_cache(job / 'cache', deadline) + 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 inference job exceeded its duration.') diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_cache.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_cache.py new file mode 100644 index 000000000..46a2a0b8b --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_cache.py @@ -0,0 +1,110 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""CPU tests for bounded removal of one V2-Lite run's model cache.""" + +import subprocess +import sys +import time +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +from superbench.benchmarks.model_benchmarks import deepseek_v2_lite_cache as cleanup + + +def test_removes_only_the_run_cache(tmp_path): + """Delete the downloaded checkpoint while keeping the run's report and logs.""" + cache = tmp_path / 'cache' + (cache / 'checkpoint').mkdir(parents=True) + (cache / 'checkpoint' / 'model-00001-of-000004.safetensors').write_bytes(b'weights') + (tmp_path / 'report.json').write_text('{}') + cleanup.remove_model_cache(cache, time.monotonic() + 30) + assert not cache.exists() + assert (tmp_path / 'report.json').is_file() + + +def test_missing_cache_is_not_an_error(tmp_path): + """A run that failed before downloading has no cache to remove.""" + cleanup.remove_model_cache(tmp_path / 'cache', time.monotonic() + 30) + assert not (tmp_path / 'cache').exists() + + +def test_cleanup_does_not_start_without_budget(tmp_path, monkeypatch): + """Never start an unbounded deletion after the deadline.""" + run = Mock() + monkeypatch.setattr(cleanup.subprocess, 'run', run) + with pytest.raises(TimeoutError, match='No time remains'): + cleanup.remove_model_cache(tmp_path / 'cache', time.monotonic()) + run.assert_not_called() + + +@pytest.mark.parametrize( + 'failure', + [PermissionError('read-only cache'), + subprocess.CalledProcessError(1, ['cleanup'], output='read-only cache')] +) +def test_filesystem_errors_are_logged(tmp_path, monkeypatch, failure): + """Report a cleanup error without treating it as a failed measurement.""" + log_error = Mock() + monkeypatch.setattr(cleanup.subprocess, 'run', Mock(side_effect=failure)) + monkeypatch.setattr(cleanup.logger, 'error', log_error) + cleanup.remove_model_cache(tmp_path / 'cache', time.monotonic() + 30) + log_error.assert_called_once() + assert 'read-only cache' in str(log_error.call_args[0][-1]) + + +@pytest.mark.parametrize('interrupted', [False, True]) +def test_cleanup_timeout_reaps_its_process(tmp_path, monkeypatch, interrupted): + """Stop and reap a real stalled cleanup child on either its deadline or controller interruption.""" + cache = tmp_path / 'cache' + cache.mkdir() + children = [] + popen = subprocess.Popen + + def stalled_cleanup(command, **kwargs): + child = popen([sys.executable, '-c', 'import time; time.sleep(30)'], **kwargs) + children.append(child) + if interrupted: + monkeypatch.setattr(child, 'communicate', Mock(side_effect=TimeoutError('controller interrupted'))) + return child + + monkeypatch.setattr(cleanup.subprocess, 'Popen', stalled_cleanup) + start = time.monotonic() + try: + with pytest.raises(TimeoutError): + cleanup.remove_model_cache(cache, start + 0.25) + assert time.monotonic() - start < 3 + assert len(children) == 1 + assert children[0].returncode is not None + assert cache.is_dir() + finally: + for child in children: + if child.poll() is None: + child.kill() + child.wait(timeout=5) + + +@pytest.mark.parametrize('deadline,budget', [(400.0, cleanup.FAILURE_CLEANUP_GRACE_SECONDS), (1000.0, 500.0)]) +def test_failure_cleanup_uses_the_remaining_budget_or_grace(tmp_path, monkeypatch, deadline, budget): + """Give a failed run's cleanup the rest of its budget, or a fixed grace once that budget is spent.""" + run = Mock() + monkeypatch.setattr(cleanup, 'time', SimpleNamespace(monotonic=lambda: 500.0)) + monkeypatch.setattr(cleanup.subprocess, 'run', run) + cleanup.remove_model_cache_after_failure(tmp_path / 'cache', deadline) + assert run.call_args[1]['timeout'] == budget + + +@pytest.mark.parametrize( + 'failure', [subprocess.TimeoutExpired(['cleanup'], 1), + TimeoutError('Killed by SIGTERM or timeout!')] +) +def test_failure_cleanup_never_raises_a_timeout(tmp_path, monkeypatch, failure): + """Log an unfinished cleanup so that the failed run keeps its original error.""" + log_error = Mock() + monkeypatch.setattr(cleanup.subprocess, 'run', Mock(side_effect=failure)) + monkeypatch.setattr(cleanup.logger, 'error', log_error) + cleanup.remove_model_cache_after_failure(tmp_path / 'cache', time.monotonic()) + log_error.assert_called_once() + assert 'after a failed run' in log_error.call_args[0][0] diff --git a/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py b/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py index de3174659..6a6f000e2 100644 --- a/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py +++ b/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py @@ -4,8 +4,6 @@ """CPU adapter tests for the standalone complete-generation profile.""" import subprocess -import sys -import time from pathlib import Path from types import SimpleNamespace from unittest.mock import Mock @@ -13,6 +11,7 @@ import pytest from superbench.benchmarks import BenchmarkType, ReturnCode +from superbench.benchmarks.model_benchmarks import deepseek_v2_lite_cache as cache_cleanup from superbench.benchmarks.model_benchmarks import vllm_deepseek_v2_lite as adapter from superbench.benchmarks.model_benchmarks.deepseek_v2_lite_utils import identity_report, write_json @@ -162,7 +161,7 @@ def worker(command, log, timeout): successful_worker(command, log, timeout) monkeypatch.setattr(adapter, 'run_worker', worker) - monkeypatch.setattr(adapter.subprocess, 'run', Mock(side_effect=failure)) + monkeypatch.setattr(cache_cleanup.subprocess, 'run', Mock(side_effect=failure)) monkeypatch.setattr(adapter.logger, 'error', log_error) assert benchmark.run() assert benchmark.return_code == ReturnCode.SUCCESS @@ -177,11 +176,13 @@ def worker(command, log, timeout): Path(command[command.index('--cache_dir') + 1]).mkdir(parents=True) successful_worker(command, log, timeout) + cleanup = Mock(side_effect=TimeoutError('Killed by SIGTERM or timeout!')) monkeypatch.setattr(adapter, 'run_worker', worker) - monkeypatch.setattr(adapter.subprocess, 'run', Mock(side_effect=TimeoutError('Killed by SIGTERM or timeout!'))) + monkeypatch.setattr(cache_cleanup.subprocess, 'run', cleanup) assert not benchmark.run() assert benchmark.return_code == ReturnCode.KILLED_BY_TIMEOUT assert 'end_to_end_seconds' not in benchmark.result + assert cleanup.call_count == 2 @pytest.mark.parametrize('cleanup_seconds', [7, 50, 70]) @@ -202,9 +203,11 @@ def cleanup(command, **kwargs): clock[0] += cleanup_seconds return result - monkeypatch.setattr(adapter, 'time', SimpleNamespace(monotonic=lambda: clock[0])) + 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(adapter.subprocess, 'run', cleanup) + monkeypatch.setattr(cache_cleanup.subprocess, 'run', cleanup) assert benchmark.run() is (cleanup_seconds < 50) if cleanup_seconds < 50: assert benchmark.return_code == ReturnCode.SUCCESS @@ -216,11 +219,12 @@ def cleanup(command, **kwargs): assert 'bf16_inference_output_tokens_per_second' not in benchmark.result -def test_cache_cleanup_does_not_start_after_the_deadline(benchmark, monkeypatch): - """Retain the cache with an explicit timeout instead of starting unbounded cleanup.""" +def test_cleanup_after_the_deadline_uses_the_failure_grace(benchmark, monkeypatch): + """Fail an overrun job, then still remove its cache within the bounded failure grace.""" clock = [100.0] - cleanup = Mock() + timeouts = [] caches = [] + run_cleanup = subprocess.run def worker(command, log, timeout): cache = Path(command[command.index('--cache_dir') + 1]) @@ -229,44 +233,44 @@ def worker(command, log, timeout): successful_worker(command, log, timeout) clock[0] += 60 - monkeypatch.setattr(adapter, 'time', SimpleNamespace(monotonic=lambda: clock[0])) + def cleanup(command, **kwargs): + timeouts.append(kwargs['timeout']) + return run_cleanup(command, **kwargs) + + fake_time = SimpleNamespace(monotonic=lambda: clock[0]) + monkeypatch.setattr(adapter, 'time', fake_time) + monkeypatch.setattr(cache_cleanup, 'time', fake_time) monkeypatch.setattr(adapter, 'run_worker', worker) - monkeypatch.setattr(adapter.subprocess, 'run', cleanup) + monkeypatch.setattr(cache_cleanup.subprocess, 'run', cleanup) assert not benchmark.run() assert benchmark.return_code == ReturnCode.KILLED_BY_TIMEOUT - assert caches[0].is_dir() - cleanup.assert_not_called() - - -@pytest.mark.parametrize('interrupted', [False, True]) -def test_cache_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(adapter.subprocess, 'Popen', stalled_cleanup) - start = time.monotonic() - try: - with pytest.raises(TimeoutError): - adapter._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) + assert 'end_to_end_seconds' not in benchmark.result + assert timeouts == [cache_cleanup.FAILURE_CLEANUP_GRACE_SECONDS] + assert not caches[0].exists() + + +@pytest.mark.parametrize( + 'failure,code', [ + (RuntimeError('worker failed'), ReturnCode.RUNTIME_EXCEPTION_ERROR), + (TimeoutError('whole job deadline'), ReturnCode.KILLED_BY_TIMEOUT), + ] +) +def test_unfinished_failure_cleanup_keeps_the_original_error(benchmark, monkeypatch, failure, code): + """Report the worker failure rather than a later cleanup timeout, and log both.""" + log_error = Mock() + + def worker(command, log, timeout): + Path(command[command.index('--cache_dir') + 1]).mkdir(parents=True) + raise failure + + monkeypatch.setattr(adapter, 'run_worker', worker) + monkeypatch.setattr(cache_cleanup.subprocess, 'run', Mock(side_effect=subprocess.TimeoutExpired(['cleanup'], 1))) + monkeypatch.setattr(adapter.logger, 'error', log_error) + assert not benchmark.run() + assert benchmark.return_code == code + messages = [call[0][0] % call[0][1:] for call in log_error.call_args_list] + assert any(str(failure) in message for message in messages) + assert any('after a failed run' in message for message in messages) def test_h100_policy_cannot_use_an_unqualified_shape(benchmark, tmp_path): From 6a2488ffbf3001167db6596dd0b51fb767b3029f Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:54:03 +0000 Subject: [PATCH 5/8] Docs - Condense V2-Lite inference documentation Keep only what users need to run the benchmark and interpret its results: the workload and checks, numerical policies and validated scope, usage, cache cleanup and duration. Drop validation timings and implementation details, which remain in the pull request and code. List every reported metric under its full result name. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../benchmarks/model-benchmarks.md | 229 ++++-------------- 1 file changed, 49 insertions(+), 180 deletions(-) diff --git a/docs/user-tutorial/benchmarks/model-benchmarks.md b/docs/user-tutorial/benchmarks/model-benchmarks.md index 403e717c1..3a2d4209b 100644 --- a/docs/user-tutorial/benchmarks/model-benchmarks.md +++ b/docs/user-tutorial/benchmarks/model-benchmarks.md @@ -163,90 +163,34 @@ Run GPT pretrain tasks with float32, float16, bfloat16 precisions with [Megatron | megatron-gpt/${precision}_train_mem_allocated | GB | The average GPU memory allocated per iteration. | | megatron-gpt/${precision}_train_max_mem_allocated | GB | The average maximum GPU memory allocated per iteration. | -## Official-checkpoint V2-Lite Generative Inference +## DeepSeek-V2-Lite Inference ### `deepseek-v2-lite-inference` -This opt-in standalone MODEL benchmark loads the complete official -`deepseek-ai/DeepSeek-V2-Lite` checkpoint at -`604d5664dddd88a0433dbae533b7fe9472482de0`, with four BF16 weight files totaling -31,413,626,576 bytes. It benchmarks prefill and multi-token cached generation, -not repeated forward passes on randomly initialized weights. No Megatron, -training implementation, quantization or CPU offload is required. - -Use the -[`inference profile`](../../../superbench/config/deepseek-v2-lite-inference.yaml) -as its own entry, with one local controller and one GPU inference replica. -The supplied profile explicitly selects the qualified H100 numerical policy; -it is not a generic CUDA/ROCm acceptance profile. -`batch_size` is the number of simultaneous requests in each measured batch. -The versioned, small fixed-text fixture controls prompt token lengths; it is -not a model-quality or production-request-distribution benchmark. -Generated counts come from actual output token IDs, including EOS when emitted, -not `batch_size * max_new_tokens`. EOS and maximum-length termination remain -enabled; all-first-token-EOS output does not satisfy the cached-decode workload. - -#### Validation Status - -The explicit `h100_bf16_v6` numerical -method has passed independent-reference checks and all six preregistered H100 -engine windows: 3,216 positive positions pass and all 6,438 fixed fault cases -are rejected. The recorded public runtime completed a download-inclusive cold -bootstrap in 1323.74 seconds. Its opt-in internal package then passed three -ordinary-entrypoint cold repetitions in 1339.17, 1342.39 and 1329.00 seconds, -with complete diagnosis, 97.85-98.32% mean GPU busy and a maximum throughput -deviation of 0.334% from the median. Each repetition includes all numerical checks. -These results apply to the recorded Standard_ND96isrf_H100_v5 source, image and -profile, not to a rebuilt image, another SKU or production deployment. -Do not replace numerical validation with matching generated tokens or exit code zero. - -The adapter default remains `numerical_policy=strict_fp32`, preserving the -original pointwise FP32 checks. `h100_bf16_v6` is explicitly restricted to one -H100, batch 8, sequence 512, maximum decode 64, two warmup batches and 256 -measured batches. It uses compiled, batch-invariant BF16 inference with the -compressed-MLA implementation; there is no FP32 measured-model fallback. - -The shipped numerical contract, `superbench/config/deepseek-v2-lite-h100-numerics.json`, -is bound to an exact SHA256 by the worker. After engine shutdown, independent -official BF16 cached execution measures the precision discrepancy on the same -fixed input prefixes; an FP32 model then recomputes every complete prefix. -For each of the three probability/mass/normalized-log metrics, the budget is -the independently calibrated reference budget plus that input's measured -BF16/FP32 discrepancy. Engine probabilities never determine their own budget. -The same budget must reject half-normalization, temperature-two and wrong-context -faults. Excessive reference uncertainty fails explicitly rather than passing. - -Every runtime numerical check retains all requests and positions at offsets -`0, 1024, 32768, 98304, 130560, 131584`, including short variable-length and -single-request cases. These are windows of one fixed stream, not statistically -independent datasets. Reference qualification also uses retained and fresh -reference-only corpora; 1,152 non-anchor comparisons supplement the canonical -cached-batch anchors. This empirical contract is not a universal BF16 error bound. - -#### Isolated Runtime - -The engine requires vLLM 0.31.0 and a compatible CUDA/ROCm/PyTorch installation. -Do not install vLLM over the existing SuperBench training environment. -Set `runtime_python` to the interpreter in its separate engine environment. -Set `reference_python` to a separate environment containing the pinned -[`official-code reference packages`](../../../dockerfile/requirements/deepseek-v2-lite-reference.txt). -The controller only imports standard-library worker helpers, not vLLM. - -The optional -[`model runtime Dockerfile`](../../../dockerfile/deepseek-v2-lite-inference.dockerfile) -installs the Python SuperBench controller and its `sb` entrypoint in the -reference-compatible environment without replacing the engine's Transformers. -`/opt/vllm/bin/python` selects the engine interpreter; -`/opt/deepseek-reference/bin/python` selects the reference/controller interpreter. -The -[`controller lock`](../../../dockerfile/requirements/deepseek-v2-lite-controller.txt) -retains the base GPU Torch/torchvision installation; its regeneration command is -in the [lock inputs](../../../dockerfile/requirements/deepseek-v2-lite-controller.in). -This is an opt-in model runtime, not the standard compiled microbenchmark image. -CUDA/ROCm registration is not certification of every GPU/runtime combination. -The build checks both interpreters' framework versions and Torch/NumPy array -interoperability. Controller/reference package pins must not replace the engine's -own environment. +#### Introduction + +Run BF16 generative inference with the official +[DeepSeek-V2-Lite](https://huggingface.co/deepseek-ai/DeepSeek-V2-Lite) checkpoint at revision +`604d5664dddd88a0433dbae533b7fe9472482de0` on one GPU with vLLM 0.31.0. Each measured batch sends +`batch_size` fixed-text prompts of `seq_len` tokens and greedily generates up to `max_new_tokens` +tokens per prompt, stopping early at EOS. The job downloads the checkpoint and verifies the SHA256 of +its 31.4GB of weight files. Before measurement, the engine also answers fixed check requests; after +the engine shuts down, an independent official-code reference checks those outputs. Any failed check +fails the run. + +`numerical_policy` defaults to `strict_fp32`, which requires the checked tokens to match the greedy +tokens of an FP32 reference exactly. The supplied profile selects `h100_bf16_v6`, which also accepts a +different token if it is the engine's greedy choice and its FP32 probability gap is within a bound +calibrated from official BF16 execution on the same input. A pass therefore does not imply exact FP32 +token agreement. `h100_bf16_v6` accepts only the supplied profile's parameters and has been validated +only on one H100 80GB GPU. The FP32 reference needs an 80GB-class GPU. + +#### Usage + +Run the [inference profile](../../../superbench/config/deepseek-v2-lite-inference.yaml) as its own +benchmark entry with one local process (`proc_num: 1`). The +[model runtime Dockerfile](../../../dockerfile/deepseek-v2-lite-inference.dockerfile) provides +separate vLLM and reference environments: ```bash docker build -f dockerfile/deepseek-v2-lite-inference.dockerfile -t sb-v2lite-inference . @@ -257,103 +201,28 @@ docker run --rm --gpus device=0 --shm-size 32g \ -C superbench.benchmarks.deepseek-v2-lite-inference.parameters.cache_root=/results/model-cache ``` -For a separately prepared native installation: -```bash -sb exec --config-file superbench/config/deepseek-v2-lite-inference.yaml -``` +Outside Docker, set `runtime_python` to a vLLM 0.31.0 environment and `reference_python` to a separate +environment with the [reference packages](../../../dockerfile/requirements/deepseek-v2-lite-reference.txt). + +`cache_root` is required. Each run downloads the checkpoint into a new directory under it and deletes +that model cache at the end, keeping the report and logs. If deletion fails, the cache path is logged +for manual removal. `duration` must be below 3600 seconds and covers the whole job, from download to +cache deletion. + +#### Metrics -The command assumes SuperBench and both worker environments are already prepared -and accessible on the same host. In a container, mount the updated checkout -read-only and provide a writable, dedicated result/cache directory. - -#### Correctness And Lifecycle - -The engine exercises variable-length batched prompts, single requests and forced -EOS termination. Outputs must match the submitted prompt token IDs. The numerical -checks depend on the selected policy: - -- `strict_fp32` (adapter default) uses a separate unsharded official-code FP32 - reference with TF32 disabled and requires exact greedy-token agreement. - For long selected requests, every generated position is checked; cached FP32 - execution supplies the reference between full-prefix checks at the first, - second, middle and final positions. Those full-prefix checks also compare - cached and complete-prefix logits across the vocabulary. Positions without - full-prefix recomputation are marked rather than given a fabricated zero - cache error. -- `h100_bf16_v6` (supplied H100 profile) measures the input-matched discrepancy - with official BF16 cached execution and recomputes every retained prefix in - FP32, not just selected full-prefix positions. It can accept a different - greedy token when the token is greedy for the engine and its FP32 probability - gap is within the input-matched bound. All three numerical metrics and the - required fault rejections must also pass. A successful H100 check therefore - does not imply exact agreement with FP32-generated tokens. - -Both policies require the requested top-20 engine log probabilities, not only -the selected token. These records are not an exhaustive comparison of the -engine's full-vocabulary logits or all expert routing paths. Correctness, -complete requests, finite timestamps and actual token counts must all pass; -a plausible generated sentence or process exit zero is insufficient. - -Engine model residency is BF16, with no quantized or offloaded fallback. -The router uses FP32 to match the official gate. NVIDIA TF32, vLLM FP32 matmul -precision and Triton FP32 arithmetic are explicitly controlled; these settings -do not turn the BF16 performance workload into full-FP32 inference. -The worker enables `VLLM_RAISE_ON_LOGIT_NANS` before importing vLLM, so NaN -logits fail the run even during measured requests that do not collect log -probabilities. Corrupted request statistics also prevent a successful report. -Inter-request prefix caching and chunked prefill are disabled for this initial -profile; within-request decode state is retained. Changing those policies or -using tensor/expert parallelism requires a separately named validation profile. - -vLLM 0.31.0 reports engine-core monotonic timestamps and provides explicit worker -joining through its engine-core client. This version-specific access is -intentional: incompatible metrics or shutdown APIs fail rather than supplying -default timings. The engine is shut down before the independent reference is -loaded, so their full model copies do not simultaneously consume GPU memory. -The FP32 reference has approximately 62.8GB of parameter storage alone, so this -initial complete validation profile needs an 80GB-class GPU even if the BF16 -engine could fit on a smaller device. That is a reference-profile requirement, -not a claim that the model intrinsically requires H100 or eight GPUs. - -#### Timing And Metrics - -`cache_root` is required. Every invocation creates a new directory under it with -an empty HF/Hub/Xet/module cache, its report and logs. After the worker exits, -the adapter deletes that 31.4GB model cache and keeps the report and logs; -shared caches outside `cache_root` are not touched. On a successful run, cleanup -must finish within `duration`; otherwise the run fails as a timeout. After a -failed or timed-out run, cleanup may continue until the job deadline or for -60 seconds, whichever ends later; an unfinished cleanup is logged without -replacing the original error. Other filesystem errors are logged without -discarding validated measurements. Interrupted cleanup can leave a cache at the -logged path. - -One `duration <3600s` covers model download, complete weight hashes, -loading, graph/kernel preparation, warmup, measured generation, reference checks, -result writing, worker teardown and model-cache cleanup. The controller finalizes -the total elapsed time and success result after cleanup and rejects watchdog -exits. Image pulls, dependency installation and controller -installation are separate preparation steps, not certified by the model-cold -timer. - -A dedicated Linux child supervisor reaps worker descendants even when they start -separate sessions. A successful launcher exit with surviving children is rejected. -Worker measurement-phase Unix timestamps allow external telemetry to exclude -setup, correctness and warmup; the timed generation durations use a monotonic -clock. CPU regression tests cover warmup exclusion and mixed EOS/decode counts. - -| Metric | Unit | Scope | -| --- | --- | --- | -| `bf16_inference_step_time` | ms | Mean complete synchronized generation batch | -| `bf16_inference_output_tokens_per_second` | tokens/s | Actual outputs divided by measured batch time | -| `bf16_inference_request_prefill_time` | ms | Engine scheduled-to-first-token interval | -| `bf16_inference_ttft` | ms | Engine first-token latency, including frontend/queue effects | -| `bf16_inference_decode_tpot` | ms/token | First-to-last-token span divided by actual decode intervals | -| `successful_requests` | requests | Completed measured requests | -| `actual_output_tokens` | tokens | Actual measured output IDs, not the configured maximum | -| `end_to_end_seconds` | s | Complete invocation through report validation and model-cache cleanup | - -Request prefill/decode timestamps are not isolated GPU kernel timings. -One-token EOS requests contribute to total tokens and latency but not to TPOT. -Keep cold-start time, steady per-GPU utilization and model quality separate; -GPU device busy time is not MFU. +| Name | Unit | Description | +|---|---|---| +| deepseek-v2-lite-inference/bf16_inference_step_time | time (ms) | The average time to generate one measured batch. | +| deepseek-v2-lite-inference/bf16_inference_output_tokens_per_second | throughput (tokens/s) | Generated tokens divided by the total measured batch time. | +| deepseek-v2-lite-inference/bf16_inference_request_prefill_time | time (ms) | The average time from scheduling a request to its first token. | +| deepseek-v2-lite-inference/bf16_inference_ttft | time (ms) | The average time from request arrival to its first token, including queueing. | +| deepseek-v2-lite-inference/bf16_inference_decode_tpot | time (ms) | The average time per output token after the first; requests with one output token are excluded. | +| deepseek-v2-lite-inference/bf16_inference_input_token_count | count | The average number of prompt tokens per request. | +| deepseek-v2-lite-inference/bf16_inference_output_token_count | count | The average number of generated tokens per request, including EOS. | +| deepseek-v2-lite-inference/successful_requests | count | The number of completed measured requests. | +| deepseek-v2-lite-inference/actual_output_tokens | count | The total number of generated tokens in measured batches. | +| deepseek-v2-lite-inference/end_to_end_seconds | time (s) | The complete job time, including checkpoint download and cache deletion. | +| deepseek-v2-lite-inference/checkpoint_bytes | size (bytes) | The total size of the checkpoint weight files. | +| deepseek-v2-lite-inference/numerical_reference_positions | count | `h100_bf16_v6` only: the number of generated positions that passed the reference check. | +| deepseek-v2-lite-inference/numerical_fault_rejections | count | `h100_bf16_v6` only: the number of injected faults that the check rejected. | From bf572398f2337e1199771224a4b69fe8bb5daf0e Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Fri, 30 Oct 2026 01:05:34 +0000 Subject: [PATCH 6/8] Benchmarks - Move DeepSeek-V2-Lite helpers into a subpackage Group the V2-Lite worker, reference, numerical policy, utility and cache modules under superbench/benchmarks/model_benchmarks/deepseek_v2_lite/; the adapter stays flat like the other model benchmarks. Workers start as `python -m deepseek_v2_lite.` with the package parent on PYTHONPATH and use package-relative imports, so worker interpreters still need no SuperBench install. The H100 numerical contract moves unchanged next to numerics.py. Merge the tests into one file for this benchmark and one for the shared helpers, and drop tests that repeat another test's coverage or check trivial guards. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- MANIFEST.in | 2 +- .../deepseek_v2_lite/__init__.py | 8 + .../cache.py} | 0 .../deepseek_v2_lite/h100_bf16_v6.json} | 0 .../inference_worker.py} | 10 +- .../numerics.py} | 12 +- .../reference.py} | 2 +- .../utils.py} | 14 +- .../model_benchmarks/vllm_deepseek_v2_lite.py | 18 +- .../model_benchmarks/test_deepseek_v2_lite.py | 715 +++++++++++++ .../test_deepseek_v2_lite_cache.py | 110 -- .../test_deepseek_v2_lite_inference_worker.py | 502 --------- .../test_deepseek_v2_lite_numerics.py | 555 ---------- .../test_deepseek_v2_lite_reference.py | 377 ------- .../test_deepseek_v2_lite_utils.py | 345 ------ .../test_vllm_deepseek_v2_lite.py | 994 ++++++++++++++++-- 16 files changed, 1665 insertions(+), 1999 deletions(-) create mode 100644 superbench/benchmarks/model_benchmarks/deepseek_v2_lite/__init__.py rename superbench/benchmarks/model_benchmarks/{deepseek_v2_lite_cache.py => deepseek_v2_lite/cache.py} (100%) rename superbench/{config/deepseek-v2-lite-h100-numerics.json => benchmarks/model_benchmarks/deepseek_v2_lite/h100_bf16_v6.json} (100%) rename superbench/benchmarks/model_benchmarks/{deepseek_v2_lite_inference_worker.py => deepseek_v2_lite/inference_worker.py} (97%) rename superbench/benchmarks/model_benchmarks/{deepseek_v2_lite_numerics.py => deepseek_v2_lite/numerics.py} (98%) rename superbench/benchmarks/model_benchmarks/{deepseek_v2_lite_reference.py => deepseek_v2_lite/reference.py} (99%) rename superbench/benchmarks/model_benchmarks/{deepseek_v2_lite_utils.py => deepseek_v2_lite/utils.py} (96%) create mode 100644 tests/benchmarks/model_benchmarks/test_deepseek_v2_lite.py delete mode 100644 tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_cache.py delete mode 100644 tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_inference_worker.py delete mode 100644 tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_numerics.py delete mode 100644 tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_reference.py delete mode 100644 tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_utils.py diff --git a/MANIFEST.in b/MANIFEST.in index 7fab786c5..1b29ff6d4 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,4 +1,4 @@ include LICENSE README.md -include superbench/config/deepseek-v2-lite-h100-numerics.json +include superbench/benchmarks/model_benchmarks/deepseek_v2_lite/h100_bf16_v6.json recursive-include superbench *.py *.j2 *.yaml global-exclude *.py[cod] __pycache__ diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/__init__.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/__init__.py new file mode 100644 index 000000000..9cc630068 --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/__init__.py @@ -0,0 +1,8 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""DeepSeek-V2-Lite workers and helpers. + +Workers run as ``python -m deepseek_v2_lite.`` in interpreters without SuperBench, so every module +except ``cache`` imports only the standard library and this package at load time. +""" diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_cache.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/cache.py similarity index 100% rename from superbench/benchmarks/model_benchmarks/deepseek_v2_lite_cache.py rename to superbench/benchmarks/model_benchmarks/deepseek_v2_lite/cache.py diff --git a/superbench/config/deepseek-v2-lite-h100-numerics.json b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/h100_bf16_v6.json similarity index 100% rename from superbench/config/deepseek-v2-lite-h100-numerics.json rename to superbench/benchmarks/model_benchmarks/deepseek_v2_lite/h100_bf16_v6.json diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_inference_worker.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/inference_worker.py similarity index 97% rename from superbench/benchmarks/model_benchmarks/deepseek_v2_lite_inference_worker.py rename to superbench/benchmarks/model_benchmarks/deepseek_v2_lite/inference_worker.py index fc312c3e5..b488bd8ac 100644 --- a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_inference_worker.py +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/inference_worker.py @@ -11,8 +11,8 @@ import time from pathlib import Path -import deepseek_v2_lite_numerics as numerics -from deepseek_v2_lite_utils import ( +from . import numerics +from .utils import ( FIXED_TEXTS, configure_cache, download_checkpoint, identity_report, interrupt_worker, packed_tokens, read_json, run_worker, write_json ) @@ -294,14 +294,12 @@ def main(): reference_start = time.monotonic() reference_command = ( [ - args.reference_python, - str(Path(__file__).with_name('deepseek_v2_lite_numerics.py')), '--checkpoint', + args.reference_python, '-m', 'deepseek_v2_lite.numerics', '--checkpoint', str(checkpoint), '--requests', str(requests), '--output', str(reference) ] if contract else [ - args.reference_python, - str(Path(__file__).with_name('deepseek_v2_lite_reference.py')), '--checkpoint', + args.reference_python, '-m', 'deepseek_v2_lite.reference', '--checkpoint', str(checkpoint), '--mode', 'inference', '--requests', str(requests), '--output', str(reference) diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_numerics.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/numerics.py similarity index 98% rename from superbench/benchmarks/model_benchmarks/deepseek_v2_lite_numerics.py rename to superbench/benchmarks/model_benchmarks/deepseek_v2_lite/numerics.py index a046e2ff2..a32b72375 100644 --- a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_numerics.py +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/numerics.py @@ -12,10 +12,7 @@ import os from pathlib import Path -if __package__: - from .deepseek_v2_lite_utils import packed_tokens, read_json, write_json -else: - from deepseek_v2_lite_utils import packed_tokens, read_json, write_json # type: ignore[no-redef] +from .utils import packed_tokens, read_json, write_json METHOD = 'bf16-input-matched-probability-log-v6' POLICY = 'h100_bf16_v6' @@ -46,7 +43,7 @@ def load_contract(): """Require the shipped, qualified artifact rather than caller-supplied tolerances.""" if not CONTRACT_SHA256: raise RuntimeError('The H100 numerical policy has not been installed as a qualified contract.') - path = Path(__file__).resolve().parents[2] / 'config/deepseek-v2-lite-h100-numerics.json' + path = Path(__file__).with_name('h100_bf16_v6.json') content = path.read_bytes() if hashlib.sha256(content).hexdigest() != CONTRACT_SHA256: raise ValueError('The qualified H100 numerical contract changed.') @@ -402,10 +399,7 @@ def run_reference(checkpoint, requests, contract): """Keep measured BF16 inference separate from both independent reference models.""" import torch from importlib.metadata import version - if __package__: - from .deepseek_v2_lite_reference import fixed_documents, load_model - else: - from deepseek_v2_lite_reference import fixed_documents, load_model + from .reference import fixed_documents, load_model torch.backends.cuda.matmul.allow_tf32 = False torch.set_float32_matmul_precision('highest') diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_reference.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/reference.py similarity index 99% rename from superbench/benchmarks/model_benchmarks/deepseek_v2_lite_reference.py rename to superbench/benchmarks/model_benchmarks/deepseek_v2_lite/reference.py index 1d6e05a6b..313d2c89b 100644 --- a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_reference.py +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/reference.py @@ -8,7 +8,7 @@ import os from pathlib import Path -from deepseek_v2_lite_utils import ( +from .utils import ( FIXED_TEXTS, PARAMETER_COUNT, packed_tokens, read_json, uniform_indices, validate_config, write_json ) diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_utils.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/utils.py similarity index 96% rename from superbench/benchmarks/model_benchmarks/deepseek_v2_lite_utils.py rename to superbench/benchmarks/model_benchmarks/deepseek_v2_lite/utils.py index ca73360ef..0a44520ef 100644 --- a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite_utils.py +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/utils.py @@ -12,7 +12,7 @@ import sys import time from pathlib import Path -from typing import Dict, List, Sequence +from typing import Dict, List, Optional, Sequence MODEL_ID = 'deepseek-ai/DeepSeek-V2-Lite' REVISION = '604d5664dddd88a0433dbae533b7fe9472482de0' @@ -283,7 +283,15 @@ def interrupt_worker(signum, frame) -> None: raise TimeoutError('Model worker interrupted by signal {}.'.format(signum)) -def run_worker(command: List[str], log: Path, timeout: float) -> None: +def worker_environment() -> Dict[str, str]: + """Let worker interpreters without SuperBench import this package by module name.""" + environment = dict(os.environ) + paths = [str(Path(__file__).resolve().parents[1]), environment.get('PYTHONPATH', '')] + environment['PYTHONPATH'] = os.pathsep.join(path for path in paths if path) + return environment + + +def run_worker(command: List[str], log: Path, timeout: float, env: Optional[Dict[str, str]] = None) -> None: """Supervise the whole worker tree under one deadline, preserving failure logs.""" if not math.isfinite(timeout) or timeout <= 0: raise TimeoutError('No time remains for the worker.') @@ -300,7 +308,7 @@ def run_worker(command: List[str], log: Path, timeout: float) -> None: *command, ] with log.open('w') as stream: - process = subprocess.Popen(supervisor, stdout=stream, stderr=subprocess.STDOUT, start_new_session=True) + process = subprocess.Popen(supervisor, stdout=stream, stderr=subprocess.STDOUT, start_new_session=True, env=env) try: try: code = process.wait(timeout=timeout + 20) diff --git a/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py b/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py index 07b9266cb..27bdd7d08 100644 --- a/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py +++ b/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py @@ -13,12 +13,12 @@ from superbench.benchmarks import BenchmarkRegistry, BenchmarkType, Platform, ReturnCode from superbench.benchmarks.base import Benchmark from superbench.common.utils import logger -from superbench.benchmarks.model_benchmarks import deepseek_v2_lite_numerics as numerics -from superbench.benchmarks.model_benchmarks.deepseek_v2_lite_cache import ( +from superbench.benchmarks.model_benchmarks.deepseek_v2_lite import numerics +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_utils import ( - numeric_series, read_json, run_worker, validate_identity +from superbench.benchmarks.model_benchmarks.deepseek_v2_lite.utils import ( + numeric_series, read_json, run_worker, validate_identity, worker_environment ) @@ -86,7 +86,8 @@ def _worker_command(self, job): args = self._args return [ args.runtime_python, - str(Path(__file__).with_name('deepseek_v2_lite_inference_worker.py')), + '-m', + 'deepseek_v2_lite.inference_worker', '--cache_dir', str(job / 'cache'), '--output', @@ -140,7 +141,12 @@ def _benchmark(self): job = Path(tempfile.mkdtemp(prefix='v2lite-inference-', dir=str(root))) try: logger.info('V2-Lite inference evidence and isolated cache: %s', job) - run_worker(self._worker_command(job), job / 'worker.log', deadline - time.monotonic() - 20) + run_worker( + self._worker_command(job), + job / 'worker.log', + deadline - time.monotonic() - 20, + env=worker_environment(), + ) report = read_json(job / 'report.json') validate_identity(report) self._validate_numerical_report(report) diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite.py new file mode 100644 index 000000000..3934bc0fb --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite.py @@ -0,0 +1,715 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""CPU tests for the shared DeepSeek-V2-Lite helpers: checkpoint, worker supervision, cache and reference.""" + +import copy +import ctypes +import hashlib +import json +import math +import os +import signal +import subprocess +import sys +import time +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +from superbench.benchmarks.model_benchmarks.deepseek_v2_lite import ( + cache as cleanup, reference as reference_module, utils +) + +torch = pytest.importorskip('torch') + + +# Checkpoint identity, fixed inputs and worker supervision. +def test_checkpoint_identity(): + """Reject architecture proxies and quantization.""" + config = dict(utils.EXPECTED_CONFIG, model_type='deepseek_v2') + utils.validate_config(config) + config['hidden_size'] = 1024 + with pytest.raises(ValueError, match='hidden_size'): + utils.validate_config(config) + config['hidden_size'] = 2048 + config['quantization_config'] = {'quant_method': 'fp8'} + with pytest.raises(ValueError, match='quantized'): + utils.validate_config(config) + assert utils.WEIGHT_BYTES == 31413626576 + + +def test_packed_text_is_reproducible(): + """Pack actual token inputs with EOS separators, not padding or mock execution.""" + documents = [[1, 2], [3, 4, 5]] + expected = [[1, 2, 9, 3], [4, 5, 9, 1]] + assert utils.packed_tokens(documents, 9, 4, 2) == expected + assert utils.packed_tokens(documents, 9, 4, 2) == expected + assert utils.packed_tokens(documents, 9, 4, 2, offset=1) != expected + + +@pytest.mark.parametrize('documents,length,count', [([], 4, 1), ([[]], 4, 1), ([[True]], 4, 1), ([[1]], 1, 1)]) +def test_invalid_text_inputs(documents, length, count): + """Surface malformed inputs instead of returning an empty batch.""" + with pytest.raises(ValueError): + utils.packed_tokens(documents, 9, length, count) + + +def test_cold_cache_isolated(tmp_path, monkeypatch): + """Reject cache reuse without deleting shared contents.""" + shared = tmp_path / 'shared' + shared.mkdir() + sentinel = shared / 'keep' + sentinel.write_text('unrelated data') + monkeypatch.setenv('HF_HOME', str(shared)) + cache = tmp_path / 'cold' + utils.configure_cache(cache) + assert sentinel.read_text() == 'unrelated data' + assert utils.os.environ['HF_HOME'] == str(cache / 'hf') + assert utils.os.environ['HF_XET_CACHE'] == str(cache / 'xet') + (cache / 'present').touch() + with pytest.raises(ValueError, match='empty'): + utils.configure_cache(cache) + + +def test_report_requires_correctness_and_teardown(): + """Require model identity, not just a successful process exit.""" + report = dict(utils.identity_report(), status='success', correctness_passed=True, teardown_complete=True) + utils.validate_identity(report) + incorrect = copy.deepcopy(report) + incorrect['parameter_count'] = 100 + with pytest.raises(ValueError, match='contract'): + utils.validate_identity(incorrect) + report['correctness_passed'] = False + with pytest.raises(ValueError, match='Correctness'): + utils.validate_identity(report) + + +@pytest.mark.parametrize('length', [1, 512, 209715200, 15706484224]) +def test_large_tensor_probe_indices(length): + """FP32-rounded endpoints must never index beyond a real full-model tensor.""" + indices = utils.uniform_indices(length) + assert len(indices) == 256 + assert indices[0] == 0 and indices[-1] == length - 1 + assert all(0 <= index < length for index in indices) + + +def test_atomic_json_rejects_nonfinite_values(tmp_path): + """A malformed report must not replace a complete report.""" + path = tmp_path / 'report.json' + utils.write_json(path, {'value': 1}) + with pytest.raises(ValueError): + utils.write_json(path, {'value': math.nan}) + assert utils.read_json(path) == {'value': 1} + path.write_text('{"value": NaN}') + with pytest.raises(ValueError, match='Nonfinite'): + utils.read_json(path) + + +def test_worker_failure_is_explicit(tmp_path): + """Reject nonzero exit codes even if the worker writes a result-like message.""" + with pytest.raises(RuntimeError, match='code 7'): + utils.run_worker([sys.executable, '-c', 'print("success"); raise SystemExit(7)'], tmp_path / 'worker.log', 5) + assert 'success' in (tmp_path / 'worker.log').read_text() + + +def test_timeout_reaps_worker(tmp_path): + """A timeout must terminate the created process rather than leave a worker.""" + pid_file = tmp_path / 'pid' + command = [ + sys.executable, + '-c', + 'import os,time; from pathlib import Path; Path({!r}).write_text(str(os.getpid())); time.sleep(60)'.format( + str(pid_file) + ), + ] + with pytest.raises(TimeoutError, match='deadline'): + utils.run_worker(command, tmp_path / 'worker.log', 1) + pid = int(pid_file.read_text()) + with pytest.raises(ProcessLookupError): + utils.os.kill(pid, 0) + + +def test_success_with_live_child_is_rejected(tmp_path): + """A leader's exit code zero is insufficient when its child remains alive.""" + command = [ + sys.executable, + '-c', + 'import subprocess,sys; subprocess.Popen([sys.executable,"-c","import time; time.sleep(60)"])', + ] + with pytest.raises(RuntimeError, match='descendant processes'): + utils.run_worker(command, tmp_path / 'worker.log', 5) + + +@pytest.mark.parametrize('launcher_exits', [False, True]) +def test_separate_session_child_is_reaped(tmp_path, launcher_exits): + """Own escaped rank sessions even when their launcher exits or ignores termination.""" + pid_file = tmp_path / 'rank.pid' + rank = ( + 'import os,signal,time; from pathlib import Path; ' + 'signal.signal(signal.SIGTERM, signal.SIG_IGN); ' + 'Path({!r}).write_text(str(os.getpid())); time.sleep(60)' + ).format(str(pid_file)) + launcher = ( + 'import signal,subprocess,sys,time; from pathlib import Path; ' + 'signal.signal(signal.SIGTERM, signal.SIG_IGN); ' + 'subprocess.Popen([sys.executable, "-c", {!r}], start_new_session=True); ' + 'ready=Path({!r})\n' + 'while not ready.exists(): time.sleep(0.01)\n' + '{}' + ).format(rank, str(pid_file), 'sys.exit(0)' if launcher_exits else 'time.sleep(60)') + try: + expected = RuntimeError if launcher_exits else TimeoutError + with pytest.raises(expected): + utils.run_worker([sys.executable, '-c', launcher], tmp_path / 'worker.log', 5 if launcher_exits else 1) + pid = int(pid_file.read_text()) + with pytest.raises(ProcessLookupError): + os.kill(pid, 0) + finally: + if pid_file.exists(): + pid = int(pid_file.read_text()) + try: + os.kill(pid, signal.SIGKILL) + except ProcessLookupError: + pass + + +def test_worker_signal_does_not_kill_unrelated_process(tmp_path): + """Timeout cleanup must be scoped to the supervised job, not the controller's children.""" + unrelated = utils.subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)']) + try: + with pytest.raises(TimeoutError): + utils.run_worker([sys.executable, '-c', 'import time; time.sleep(60)'], tmp_path / 'worker.log', 0.2) + assert unrelated.poll() is None + finally: + unrelated.terminate() + unrelated.wait(timeout=5) + + +def test_controller_death_reaps_owned_worker(tmp_path): + """A killed controller must not leave its independently supervised job alive.""" + pid_file = tmp_path / 'worker.pid' + worker = ('import os,time; from pathlib import Path; ' + 'Path({!r}).write_text(str(os.getpid())); time.sleep(60)').format(str(pid_file)) + controller = ( + 'import sys; from pathlib import Path; sys.path.insert(0, {!r}); ' + 'from deepseek_v2_lite.utils import run_worker; ' + 'run_worker([sys.executable, "-c", {!r}], Path({!r}), 60)' + ).format(str(Path(utils.__file__).resolve().parents[1]), worker, str(tmp_path / 'worker.log')) + process = utils.subprocess.Popen([sys.executable, '-c', controller]) + try: + deadline = time.monotonic() + 5 + while not pid_file.exists() and time.monotonic() < deadline: + time.sleep(0.02) + assert pid_file.exists() + pid = int(pid_file.read_text()) + process.kill() + process.wait(timeout=5) + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + try: + os.kill(pid, 0) + except ProcessLookupError: + break + time.sleep(0.02) + else: + pytest.fail('The worker survived its controller.') + finally: + if process.poll() is None: + process.kill() + process.wait(timeout=5) + if pid_file.exists(): + try: + os.kill(int(pid_file.read_text()), signal.SIGKILL) + except ProcessLookupError: + pass + + +@pytest.fixture +def checkpoint_files(tmp_path, monkeypatch): + """Create small real files to test the checkpoint integrity contract.""" + root = tmp_path / 'checkpoint' + root.mkdir() + contents = b'CPU checkpoint integrity fixture' + shard = root / 'weights.safetensors' + shard.write_bytes(contents) + monkeypatch.setattr(utils, 'WEIGHT_FILES', { + shard.name: (len(contents), hashlib.sha256(contents).hexdigest()), + }) + utils.write_json(root / 'config.json', dict(utils.EXPECTED_CONFIG, model_type='deepseek_v2')) + utils.write_json(root / 'model.safetensors.index.json', {'weight_map': {'fixture.weight': shard.name}}) + return root, shard + + +@pytest.mark.parametrize('failure', ['missing', 'size', 'hash', 'index']) +def test_invalid_checkpoint_files_fail(checkpoint_files, failure): + """Corrupted, missing or misindexed shards must never become a valid checkpoint.""" + root, shard = checkpoint_files + if failure == 'missing': + shard.unlink() + elif failure == 'size': + shard.write_bytes(b'short') + elif failure == 'hash': + shard.write_bytes(b'x' * shard.stat().st_size) + else: + utils.write_json(root / 'model.safetensors.index.json', {'weight_map': {'fixture.weight': 'other'}}) + with pytest.raises(ValueError): + utils.verify_checkpoint(root) + + +def test_download_uses_pinned_public_identity_and_then_verifies(checkpoint_files, monkeypatch): + """Disable implicit credentials and require the downloaded shard contract.""" + root, shard = checkpoint_files + download = Mock() + monkeypatch.setitem(sys.modules, 'huggingface_hub', SimpleNamespace(snapshot_download=download)) + assert utils.download_checkpoint(root.parent) == root + arguments = download.call_args[1] + assert arguments['repo_id'] == utils.MODEL_ID + assert arguments['revision'] == utils.REVISION + assert arguments['token'] is False + assert arguments['local_dir'] == str(root) + assert shard.name in arguments['allow_patterns'] + + +@pytest.mark.parametrize('timeout', [0, -1, float('nan')]) +def test_invalid_worker_deadline_fails_before_launch(tmp_path, timeout): + """A nonfinite or expired budget must not start a worker.""" + with pytest.raises(TimeoutError): + utils.run_worker([sys.executable, '-c', 'pass'], tmp_path / 'worker.log', timeout) + + +def test_worker_interrupt_is_failure(): + """A termination request must unwind the worker's normal success path.""" + with pytest.raises(TimeoutError, match='interrupted'): + utils.interrupt_worker(signal.SIGTERM, None) + + +def test_supervisor_requires_kernel_ownership_support(monkeypatch): + """Fail before spawning when kernel ownership setup is unavailable.""" + monkeypatch.setattr(utils.signal, 'signal', Mock()) + monkeypatch.setattr(ctypes, 'CDLL', lambda *args, **kwargs: SimpleNamespace(prctl=lambda *args: -1)) + monkeypatch.setattr(ctypes, 'get_errno', lambda: 13) + spawn = Mock() + monkeypatch.setattr(utils.subprocess, 'Popen', spawn) + with pytest.raises(OSError): + utils.supervise_worker([sys.executable, '-c', 'pass'], 1, os.getppid()) + spawn.assert_not_called() + + +# Per-run model cache removal. +def test_removes_only_the_run_cache(tmp_path): + """Delete the downloaded checkpoint while keeping the run's report and logs.""" + cache = tmp_path / 'cache' + (cache / 'checkpoint').mkdir(parents=True) + (cache / 'checkpoint' / 'model-00001-of-000004.safetensors').write_bytes(b'weights') + (tmp_path / 'report.json').write_text('{}') + cleanup.remove_model_cache(cache, time.monotonic() + 30) + assert not cache.exists() + assert (tmp_path / 'report.json').is_file() + + +def test_cleanup_does_not_start_without_budget(tmp_path, monkeypatch): + """Never start an unbounded deletion after the deadline.""" + run = Mock() + monkeypatch.setattr(cleanup.subprocess, 'run', run) + with pytest.raises(TimeoutError, match='No time remains'): + cleanup.remove_model_cache(tmp_path / 'cache', time.monotonic()) + run.assert_not_called() + + +@pytest.mark.parametrize( + 'failure', + [PermissionError('read-only cache'), + subprocess.CalledProcessError(1, ['cleanup'], output='read-only cache')] +) +def test_filesystem_errors_are_logged(tmp_path, monkeypatch, failure): + """Report a cleanup error without treating it as a failed measurement.""" + log_error = Mock() + monkeypatch.setattr(cleanup.subprocess, 'run', Mock(side_effect=failure)) + monkeypatch.setattr(cleanup.logger, 'error', log_error) + cleanup.remove_model_cache(tmp_path / 'cache', time.monotonic() + 30) + log_error.assert_called_once() + assert 'read-only cache' in str(log_error.call_args[0][-1]) + + +@pytest.mark.parametrize('interrupted', [False, True]) +def test_cleanup_timeout_reaps_its_process(tmp_path, monkeypatch, interrupted): + """Stop and reap a real stalled cleanup child on either its deadline or controller interruption.""" + cache = tmp_path / 'cache' + cache.mkdir() + children = [] + popen = subprocess.Popen + + def stalled_cleanup(command, **kwargs): + child = popen([sys.executable, '-c', 'import time; time.sleep(30)'], **kwargs) + children.append(child) + if interrupted: + monkeypatch.setattr(child, 'communicate', Mock(side_effect=TimeoutError('controller interrupted'))) + return child + + monkeypatch.setattr(cleanup.subprocess, 'Popen', stalled_cleanup) + start = time.monotonic() + try: + with pytest.raises(TimeoutError): + cleanup.remove_model_cache(cache, start + 0.25) + assert time.monotonic() - start < 3 + assert len(children) == 1 + assert children[0].returncode is not None + assert cache.is_dir() + finally: + for child in children: + if child.poll() is None: + child.kill() + child.wait(timeout=5) + + +@pytest.mark.parametrize('deadline,budget', [(400.0, cleanup.FAILURE_CLEANUP_GRACE_SECONDS), (1000.0, 500.0)]) +def test_failure_cleanup_uses_the_remaining_budget_or_grace(tmp_path, monkeypatch, deadline, budget): + """Give a failed run's cleanup the rest of its budget, or a fixed grace once that budget is spent.""" + run = Mock() + monkeypatch.setattr(cleanup, 'time', SimpleNamespace(monotonic=lambda: 500.0)) + monkeypatch.setattr(cleanup.subprocess, 'run', run) + cleanup.remove_model_cache_after_failure(tmp_path / 'cache', deadline) + assert run.call_args[1]['timeout'] == budget + + +@pytest.mark.parametrize( + 'failure', [subprocess.TimeoutExpired(['cleanup'], 1), + TimeoutError('Killed by SIGTERM or timeout!')] +) +def test_failure_cleanup_never_raises_a_timeout(tmp_path, monkeypatch, failure): + """Log an unfinished cleanup so that the failed run keeps its original error.""" + log_error = Mock() + monkeypatch.setattr(cleanup.subprocess, 'run', Mock(side_effect=failure)) + monkeypatch.setattr(cleanup.logger, 'error', log_error) + cleanup.remove_model_cache_after_failure(tmp_path / 'cache', time.monotonic()) + log_error.assert_called_once() + assert 'after a failed run' in log_error.call_args[0][0] + + +# Official-code reference. +@pytest.fixture +def reference(monkeypatch): + """Return the reference and redirect only test tensor creation to CPU.""" + tensor = torch.tensor + + def cpu_tensor(data, *args, **kwargs): + if kwargs.get('device') == 'cuda': + kwargs['device'] = 'cpu' + return tensor(data, *args, **kwargs) + + monkeypatch.setattr(torch, 'tensor', cpu_tensor) + return reference_module + + +class ReferenceFixture: + """Expose token-independent logits while checking cached attention shapes.""" + def __init__(self): + """Track cache and full-prefix calls separately.""" + self.calls = [] + + def eval(self): + """Retain the minimal evaluation interface used by the oracle.""" + return self + + def __call__(self, input_ids, attention_mask, past_key_values=None, use_cache=True): + """Require a mask for all past and current positions, including one-token decode.""" + length = input_ids.shape[1] + total = length + (past_key_values or 0) + assert attention_mask.shape == (1, total) + assert attention_mask.all().item() + self.calls.append((length, total, past_key_values, use_cache)) + logits = torch.tensor([0.0, 1.0, 2.0, 3.0]).reshape(1, 1, 4).repeat(1, length, 1) + return SimpleNamespace(logits=logits, past_key_values=total if use_cache else None) + + +def request_fixture(): + """Provide exact fixture probabilities rather than a model-quality claim.""" + probabilities = torch.tensor([0.0, 1.0, 2.0, 3.0]).log_softmax(-1).tolist() + return { + 'prompt_token_ids': [1, 2], + 'token_ids': [3, 3], + 'logprobs': [{str(index): value + for index, value in enumerate(probabilities)} for _ in range(2)], + } + + +def test_cached_decode_mask_covers_full_prefix(reference): + """The second cache call has one input token but a three-position mask.""" + model = ReferenceFixture() + result = reference.inference_reference(model, [request_fixture()]) + assert model.calls == [(2, 2, None, True), (2, 2, None, False), (1, 3, 2, True), (3, 3, None, False)] + assert len(result['comparisons']) == 2 + assert all(row['cache_max_abs_error'] == 0 for row in result['comparisons']) + + +@pytest.mark.parametrize('requests', [[], [{'prompt_token_ids': [], 'token_ids': [], 'logprobs': []}]]) +def test_incomplete_reference_requests_fail(reference, requests): + """Never accept an empty or truncated numerical workload.""" + with pytest.raises(ValueError, match='nonempty|Incomplete'): + reference.inference_reference(ReferenceFixture(), requests) + + +def test_reference_requires_greedy_token_agreement(reference): + """Finite probabilities alone must not certify an incorrect generated token.""" + request = request_fixture() + request['token_ids'][0] = 1 + with pytest.raises(RuntimeError, match='greedy token'): + reference.inference_reference(ReferenceFixture(), [request]) + + +def test_reference_does_not_ignore_probability_mismatch(reference): + """Keep the numerical gate even when all generated tokens are correct.""" + request = request_fixture() + request['logprobs'][0]['3'] += 1.0 + with pytest.raises(AssertionError, match='request 0 step 0'): + reference.inference_reference(ReferenceFixture(), [request]) + + +@pytest.mark.parametrize('positions', [[], [0], [1], [0, 0, 1], [1, 0], [0, 2], [False, 1]]) +def test_invalid_full_prefix_sampling_fails(reference, positions): + """Do not accept malformed or first/final-step-incomplete numerical evidence.""" + request = request_fixture() + request['full_prefix_steps'] = positions + with pytest.raises(ValueError, match='reference positions'): + reference.inference_reference(ReferenceFixture(), [request]) + + +class TrainingReferenceFixture: + """Small autograd fixture for global-batch partitioning, not GPU model validation.""" + def __init__(self): + """Create the named parameters required by reference sampling.""" + names = [ + 'model.embed_tokens.weight', + 'model.layers.0.self_attn.q_proj.weight', + 'model.layers.0.self_attn.kv_a_proj_with_mqa.weight', + 'model.layers.0.mlp.down_proj.weight', + 'model.layers.1.mlp.gate.weight', + 'model.layers.1.mlp.experts.0.down_proj.weight', + ] + self.parameters = {name: torch.nn.Parameter(torch.ones(2, 2)) for name in names} + self.batches = [] + self.checkpointing = False + + def train(self): + """Expose the reference model's training-mode interface.""" + return self + + def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs): + """Require the memory-bounded nonreentrant reference policy.""" + assert gradient_checkpointing_kwargs == {'use_reentrant': False} + self.checkpointing = True + + def named_parameters(self): + """Expose stable names for independently selected gradient probes.""" + return self.parameters.items() + + def get_parameter(self, name): + """Look up the same parameter on each logical rank batch.""" + return self.parameters[name] + + def zero_grad(self, set_to_none): + """Discard local gradients before the next reference batch.""" + assert set_to_none + for parameter in self.parameters.values(): + parameter.grad = None + + def __call__(self, input_ids, labels, use_cache): + """Produce input-dependent gradients that differ between rank batches.""" + assert not use_cache and torch.equal(input_ids, labels) + self.batches.append(input_ids.clone()) + loss = sum(parameter.sum() for parameter in self.parameters.values()) * input_ids.float().mean() + return SimpleNamespace(loss=loss) + + +def test_training_reference_averages_distinct_real_profile_rank_batches(reference, monkeypatch): + """Check different rank inputs and float32 gradient averaging rather than replicated tokens.""" + monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: ([[1, 2, 4, 8]], 16)) + model = TrainingReferenceFixture() + result = reference.training_reference(model, 'unused', batch_size=2, seq_len=32, world_size=3) + expected = torch.tensor(result['tokens']).float().mean().item() + assert model.checkpointing + assert len(result['tokens']) == 6 and all(len(row) == 32 for row in result['tokens']) + assert len(model.batches) == 3 and not torch.equal(model.batches[0], model.batches[1]) + assert result['world_size'] == 3 and result['batch_size'] == 2 and result['seq_len'] == 32 + assert result['loss'] == pytest.approx(sum(result['loss_per_rank']) / 3) + for probe in result['gradients'].values(): + assert probe['values'] == pytest.approx([expected] * len(probe['indices'])) + assert all(parameter.grad is None for parameter in model.parameters.values()) + + +def test_targeted_reference_matches_full_backward_without_unneeded_gradients(reference, monkeypatch): + """Preserve full-model derivatives while avoiding storage for unsampled parameter gradients.""" + documents = [[1, 2, 4, 8]] + monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: (documents, 16)) + model = TrainingReferenceFixture() + ignored = torch.nn.Parameter(torch.tensor([2.0])) + model.parameters['model.layers.2.unprobed.weight'] = ignored + tokens = reference.packed_tokens(documents, 16, 32, 6) + expected = {} + for rank in range(2): + model.zero_grad(set_to_none=True) + inputs = torch.tensor(tokens[rank * 3:(rank + 1) * 3]) + model(input_ids=inputs, labels=inputs, use_cache=False).loss.backward() + for name, parameter in model.parameters.items(): + expected[name] = expected.get(name, torch.zeros_like(parameter)) + parameter.grad.detach() / 2 + model.zero_grad(set_to_none=True) + grad = Mock(wraps=torch.autograd.grad) + monkeypatch.setattr(torch.autograd, 'grad', grad) + result = reference.training_reference(model, 'unused', batch_size=3, seq_len=32, world_size=2) + assert grad.call_count == 2 + for call in grad.call_args_list: + assert all(parameter is not ignored for parameter in call[0][1]) + for name, probe in result['gradients'].items(): + assert probe['values'] == pytest.approx(expected[name].flatten()[probe['indices']].tolist()) + assert all(parameter.requires_grad and parameter.grad is None for parameter in model.parameters.values()) + + +@pytest.mark.parametrize('batch_size,seq_len,world_size', [(0, 32, 1), (1, 16, 1), (1, 32, 0)]) +def test_training_reference_rejects_invalid_profile(reference, batch_size, seq_len, world_size): + """Invalid global-batch definitions must fail before any model work.""" + with pytest.raises(ValueError, match='reference profile'): + reference.training_reference(TrainingReferenceFixture(), 'unused', batch_size, seq_len, world_size) + + +@pytest.fixture +def loading_contract(reference, tmp_path, monkeypatch): + """Mock library boundaries while exercising all loader identity checks.""" + if sys.version_info < (3, 10): + pytest.skip('The standalone model runtime requires Python 3.10 or later.') + import importlib.metadata + from superbench.benchmarks.model_benchmarks.deepseek_v2_lite.utils import EXPECTED_CONFIG + + (tmp_path / 'config.json').write_text(json.dumps(dict(EXPECTED_CONFIG, model_type='deepseek_v2'))) + parameter = SimpleNamespace(numel=lambda: reference.PARAMETER_COUNT, requires_grad=True) + model = SimpleNamespace(parameters=lambda: [parameter]) + loading = {key: [] for key in ['missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs']} + loader = Mock(return_value=(model, loading)) + tokenizer = SimpleNamespace(encode=Mock(return_value=[1, 2]), eos_token_id=9) + tokenizer_loader = Mock(return_value=tokenizer) + monkeypatch.setitem( + sys.modules, 'transformers', + SimpleNamespace( + AutoModelForCausalLM=SimpleNamespace(from_pretrained=loader), + AutoTokenizer=SimpleNamespace(from_pretrained=tokenizer_loader), + ) + ) + version = importlib.metadata.version + monkeypatch.setattr( + importlib.metadata, 'version', lambda name: '4.46.3' if name == 'transformers' else version(name) + ) + monkeypatch.setattr(torch.cuda, 'is_available', lambda: True) + return SimpleNamespace( + path=tmp_path, + model=model, + parameter=parameter, + loading=loading, + loader=loader, + tokenizer=tokenizer, + tokenizer_loader=tokenizer_loader, + ) + + +def test_official_loader_contract(reference, loading_contract): + """Require local official-code loading and complete loading diagnostics.""" + item = loading_contract + assert reference.load_model(str(item.path), torch.bfloat16) is item.model + options = item.loader.call_args[1] + assert options['torch_dtype'] == torch.bfloat16 + assert options['local_files_only'] and options['trust_remote_code'] and options['use_safetensors'] + assert options['attn_implementation'] == 'eager' and options['output_loading_info'] + documents, eos = reference.fixed_documents(str(item.path)) + assert len(documents) == len(reference.FIXED_TEXTS) and eos == 9 + assert item.tokenizer_loader.call_args[1]['local_files_only'] + assert item.tokenizer.encode.call_count == len(reference.FIXED_TEXTS) + + +@pytest.mark.parametrize('field', ['missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs']) +def test_loader_diagnostics_cannot_be_ignored(reference, loading_contract, field): + """Partial or incompatible loading must fail before reference execution.""" + loading_contract.loading[field] = ['invalid checkpoint'] + with pytest.raises(RuntimeError, match='checkpoint loading'): + reference.load_model(str(loading_contract.path), torch.bfloat16) + + +@pytest.mark.parametrize('failure', ['count', 'frozen', 'gpu', 'version']) +def test_loader_rejects_wrong_model_or_runtime(reference, loading_contract, monkeypatch, failure): + """Do not replace full-model GPU verification with a smaller or unsupported runtime.""" + item = loading_contract + if failure == 'count': + item.parameter.numel = lambda: 1 + elif failure == 'frozen': + item.parameter.requires_grad = False + elif failure == 'gpu': + monkeypatch.setattr(torch.cuda, 'is_available', lambda: False) + else: + import importlib.metadata + monkeypatch.setattr(importlib.metadata, 'version', lambda name: '0.0') + with pytest.raises(RuntimeError): + reference.load_model(str(item.path), torch.bfloat16) + + +@pytest.mark.parametrize('mode', ['training', 'inference']) +def test_reference_entrypoint_uses_expected_dtype_and_teardown(reference, tmp_path, monkeypatch, mode): + """Exercise orchestration with fake model work, not GPU numerical acceptance.""" + model = Mock() + model.cuda.return_value = model + loader = Mock(return_value=model) + monkeypatch.setattr(reference, 'load_model', loader) + monkeypatch.setattr(reference, 'training_reference', Mock(return_value={'loss': 1.0})) + monkeypatch.setattr(reference, 'inference_reference', Mock(return_value={'comparisons': []})) + monkeypatch.setattr(torch.cuda, 'set_device', Mock()) + monkeypatch.setattr(torch.cuda, 'synchronize', Mock()) + cleanup = Mock() + monkeypatch.setattr(torch.cuda, 'empty_cache', cleanup) + monkeypatch.setattr(torch.backends.cuda.matmul, 'allow_tf32', False) + monkeypatch.setenv('TORCH_ALLOW_TF32_CUBLAS_OVERRIDE', '0') + requests = tmp_path / 'requests.json' + requests.write_text('[]') + output = tmp_path / 'report.json' + monkeypatch.setattr( + sys, 'argv', [ + 'reference', + '--checkpoint', + str(tmp_path), + '--mode', + mode, + '--requests', + str(requests), + '--output', + str(output), + ] + ) + reference.main() + report = json.loads(output.read_text()) + expected = torch.bfloat16 if mode == 'training' else torch.float32 + assert loader.call_args[0][1] == expected + assert report['reference_dtype'] == str(expected) + assert report['correctness_passed'] and report['teardown_complete'] and not report['tf32_allowed'] + cleanup.assert_called_once() + + +def test_worker_environment_reaches_the_worker(tmp_path, monkeypatch): + """Put this package first on the worker search path and pass it through the supervisor.""" + monkeypatch.setenv('PYTHONPATH', 'existing') + expected = os.pathsep.join([str(Path(utils.__file__).resolve().parents[1]), 'existing']) + command = [sys.executable, '-c', 'import os, sys; assert os.environ["PYTHONPATH"] == sys.argv[1]', expected] + utils.run_worker(command, tmp_path / 'worker.log', 5, env=utils.worker_environment()) + + +def test_worker_modules_import_without_superbench(tmp_path): + """Worker interpreters lack SuperBench and site packages, so loading a worker module must need neither.""" + package = Path(utils.__file__).resolve().parent + # The cache helper uses the SuperBench logger and runs only in the adapter process. + names = sorted(path.stem for path in package.glob('*.py') if path.stem not in ('__init__', 'cache')) + assert {'reference', 'utils'} <= set(names) + code = ( + 'import importlib, sys; [importlib.import_module(name) for name in sys.argv[1:]]; ' + 'assert "superbench" not in sys.modules' + ) + modules = ['{}.{}'.format(package.name, name) for name in names] + utils.subprocess.run( + [sys.executable, '-S', '-c', code, *modules], env=utils.worker_environment(), cwd=str(tmp_path), check=True + ) diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_cache.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_cache.py deleted file mode 100644 index 46a2a0b8b..000000000 --- a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_cache.py +++ /dev/null @@ -1,110 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -"""CPU tests for bounded removal of one V2-Lite run's model cache.""" - -import subprocess -import sys -import time -from types import SimpleNamespace -from unittest.mock import Mock - -import pytest - -from superbench.benchmarks.model_benchmarks import deepseek_v2_lite_cache as cleanup - - -def test_removes_only_the_run_cache(tmp_path): - """Delete the downloaded checkpoint while keeping the run's report and logs.""" - cache = tmp_path / 'cache' - (cache / 'checkpoint').mkdir(parents=True) - (cache / 'checkpoint' / 'model-00001-of-000004.safetensors').write_bytes(b'weights') - (tmp_path / 'report.json').write_text('{}') - cleanup.remove_model_cache(cache, time.monotonic() + 30) - assert not cache.exists() - assert (tmp_path / 'report.json').is_file() - - -def test_missing_cache_is_not_an_error(tmp_path): - """A run that failed before downloading has no cache to remove.""" - cleanup.remove_model_cache(tmp_path / 'cache', time.monotonic() + 30) - assert not (tmp_path / 'cache').exists() - - -def test_cleanup_does_not_start_without_budget(tmp_path, monkeypatch): - """Never start an unbounded deletion after the deadline.""" - run = Mock() - monkeypatch.setattr(cleanup.subprocess, 'run', run) - with pytest.raises(TimeoutError, match='No time remains'): - cleanup.remove_model_cache(tmp_path / 'cache', time.monotonic()) - run.assert_not_called() - - -@pytest.mark.parametrize( - 'failure', - [PermissionError('read-only cache'), - subprocess.CalledProcessError(1, ['cleanup'], output='read-only cache')] -) -def test_filesystem_errors_are_logged(tmp_path, monkeypatch, failure): - """Report a cleanup error without treating it as a failed measurement.""" - log_error = Mock() - monkeypatch.setattr(cleanup.subprocess, 'run', Mock(side_effect=failure)) - monkeypatch.setattr(cleanup.logger, 'error', log_error) - cleanup.remove_model_cache(tmp_path / 'cache', time.monotonic() + 30) - log_error.assert_called_once() - assert 'read-only cache' in str(log_error.call_args[0][-1]) - - -@pytest.mark.parametrize('interrupted', [False, True]) -def test_cleanup_timeout_reaps_its_process(tmp_path, monkeypatch, interrupted): - """Stop and reap a real stalled cleanup child on either its deadline or controller interruption.""" - cache = tmp_path / 'cache' - cache.mkdir() - children = [] - popen = subprocess.Popen - - def stalled_cleanup(command, **kwargs): - child = popen([sys.executable, '-c', 'import time; time.sleep(30)'], **kwargs) - children.append(child) - if interrupted: - monkeypatch.setattr(child, 'communicate', Mock(side_effect=TimeoutError('controller interrupted'))) - return child - - monkeypatch.setattr(cleanup.subprocess, 'Popen', stalled_cleanup) - start = time.monotonic() - try: - with pytest.raises(TimeoutError): - cleanup.remove_model_cache(cache, start + 0.25) - assert time.monotonic() - start < 3 - assert len(children) == 1 - assert children[0].returncode is not None - assert cache.is_dir() - finally: - for child in children: - if child.poll() is None: - child.kill() - child.wait(timeout=5) - - -@pytest.mark.parametrize('deadline,budget', [(400.0, cleanup.FAILURE_CLEANUP_GRACE_SECONDS), (1000.0, 500.0)]) -def test_failure_cleanup_uses_the_remaining_budget_or_grace(tmp_path, monkeypatch, deadline, budget): - """Give a failed run's cleanup the rest of its budget, or a fixed grace once that budget is spent.""" - run = Mock() - monkeypatch.setattr(cleanup, 'time', SimpleNamespace(monotonic=lambda: 500.0)) - monkeypatch.setattr(cleanup.subprocess, 'run', run) - cleanup.remove_model_cache_after_failure(tmp_path / 'cache', deadline) - assert run.call_args[1]['timeout'] == budget - - -@pytest.mark.parametrize( - 'failure', [subprocess.TimeoutExpired(['cleanup'], 1), - TimeoutError('Killed by SIGTERM or timeout!')] -) -def test_failure_cleanup_never_raises_a_timeout(tmp_path, monkeypatch, failure): - """Log an unfinished cleanup so that the failed run keeps its original error.""" - log_error = Mock() - monkeypatch.setattr(cleanup.subprocess, 'run', Mock(side_effect=failure)) - monkeypatch.setattr(cleanup.logger, 'error', log_error) - cleanup.remove_model_cache_after_failure(tmp_path / 'cache', time.monotonic()) - log_error.assert_called_once() - assert 'after a failed run' in log_error.call_args[0][0] diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_inference_worker.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_inference_worker.py deleted file mode 100644 index 7cd946b9f..000000000 --- a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_inference_worker.py +++ /dev/null @@ -1,502 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -"""CPU tests for generation counters and the pinned engine timing contract.""" - -import importlib.util -import json -import sys -from pathlib import Path -from types import SimpleNamespace -from unittest.mock import Mock - -import pytest - - -@pytest.fixture -def worker(monkeypatch): - """Load the standalone worker without requiring a vLLM or CUDA installation.""" - directory = Path(__file__).resolve().parents[3] / 'superbench/benchmarks/model_benchmarks' - monkeypatch.syspath_prepend(str(directory)) - spec = importlib.util.spec_from_file_location( - 'v2lite_generation_test', directory / 'deepseek_v2_lite_inference_worker.py' - ) - if spec is None or spec.loader is None: - raise RuntimeError('Cannot load the standalone generation worker.') - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -def response(tokens=(7, 8)): - """Construct engine-response fixtures without simulating GPU success.""" - return SimpleNamespace( - finished=True, - prompt_token_ids=[1, 2, 3], - outputs=[ - SimpleNamespace( - token_ids=list(tokens), - finish_reason='length', - logprobs=[ - {key: SimpleNamespace(logprob=-0.5 if key == token else -2.0) - for key in set(range(20)) | {token}} for token in tokens - ] - ) - ], - metrics=SimpleNamespace( - is_corrupted=False, - num_generation_tokens=len(tokens), - scheduled_ts=10.0, - first_token_ts=10.25, - last_token_ts=10.5, - first_token_latency=0.4 - ), - ) - - -def test_actual_output_tokens_not_maximum(worker): - """Count emitted token IDs instead of treating max_tokens as completed work.""" - result = worker.output_record(response(), 64, [1, 2, 3], True) - assert result['token_ids'] == [7, 8] - assert len(result['token_ids']) == 2 - assert result['logprobs'][0]['7'] == result['logprobs'][1]['8'] == -0.5 - assert all(len(row) == 20 for row in result['logprobs']) - - -def test_eos_is_a_real_token(worker): - """An EOS-only request has one output token and no decode denominator.""" - output = response((100001, )) - output.outputs[0].finish_reason = 'stop' - output.metrics.last_token_ts = output.metrics.first_token_ts - assert worker.output_record(output, 64, [1, 2, 3])['token_ids'] == [100001] - assert worker.request_times(output) == (250.0, 400.0, None) - - -def test_pinned_engine_timestamps(worker): - """Derive durations from compatible monotonic timestamps and actual tokens.""" - assert worker.request_times(response()) == (250.0, 400.0, 250.0) - - -@pytest.mark.parametrize('tokens', [(), (1, 2, 3, 4, 5)]) -def test_invalid_token_counts(worker, tokens): - """Reject empty or over-limit outputs rather than inventing throughput.""" - with pytest.raises(RuntimeError, match='count'): - worker.output_record(response(tokens), 4, [1, 2, 3]) - - -@pytest.mark.parametrize('field,value', [('finished', False), ('prompt_token_ids', [])]) -def test_incomplete_requests(worker, field, value): - """Failed request batches do not count as complete model execution.""" - output = response() - setattr(output, field, value) - with pytest.raises(RuntimeError, match='unfinished'): - worker.output_record(output, 64, [1, 2, 3]) - - -def test_output_must_match_submitted_prompt(worker): - """Do not validate a correct response against a different request's tokens.""" - with pytest.raises(RuntimeError, match='different prompt'): - worker.output_record(response(), 64, [3, 2, 1]) - - -def test_missing_logprobs(worker): - """Missing numerical-reference evidence must fail explicitly.""" - output = response() - output.outputs[0].logprobs = None - with pytest.raises(RuntimeError, match='probabilities'): - worker.output_record(output, 64, [1, 2, 3], True) - - -def test_truncated_logprob_row_is_not_accepted(worker): - """Numerical validation must retain the requested top-20 positions, not only the chosen token.""" - output = response() - del output.outputs[0].logprobs[0][0] - with pytest.raises(RuntimeError, match='top-20'): - worker.output_record(output, 64, [1, 2, 3], True) - - -@pytest.mark.parametrize( - 'field,value', [ - ('is_corrupted', True), ('num_generation_tokens', 64), ('first_token_ts', 0.0), - ('first_token_latency', float('nan')), ('last_token_ts', 10.0) - ] -) -def test_invalid_statistics(worker, field, value): - """Never substitute zero/default durations or hide corrupted logits.""" - output = response() - setattr(output.metrics, field, value) - with pytest.raises(RuntimeError): - worker.request_times(output) - - -def test_measured_generation_excludes_warmup_and_counts_actual_tokens(worker, monkeypatch): - """Exclude distinct warmup timings and retain mixed EOS/multi-token measurements.""" - monkeypatch.setitem(sys.modules, 'torch', SimpleNamespace(cuda=SimpleNamespace(synchronize=lambda: None))) - monkeypatch.setitem(sys.modules, 'vllm', SimpleNamespace(SamplingParams=SimpleNamespace)) - clock = iter([0.0, 0.1, 1.0, 1.2, 2.0, 2.3]) - monkeypatch.setattr(worker.time, 'monotonic', lambda: next(clock)) - batches = iter( - [ - [(1, 0.05, 0.06, 0), (4, 0.075, 0.085, 0.015)], - [(1, 0.01, 0.015, 0), (3, 0.02, 0.025, 0.12)], - [(2, 0.03, 0.035, 0.08), (1, 0.04, 0.045, 0)], - ] - ) - submitted = [] - monkeypatch.setattr(worker.time, 'time', lambda: 1000.0 + 100 * len(submitted)) - - class Engine: - def generate(self, prompts, parameters, use_tqdm): - submitted.append(prompts) - outputs = [] - for prompt, (count, prefill, ttft, decode) in zip(prompts, next(batches)): - output = response((99, ) if count == 1 else tuple(range(7, 7 + count))) - output.prompt_token_ids = prompt['prompt_token_ids'] - output.metrics.first_token_ts = output.metrics.scheduled_ts + prefill - output.metrics.first_token_latency = ttft - output.metrics.last_token_ts = output.metrics.first_token_ts + decode - if count == 1: - output.outputs[0].finish_reason = 'stop' - outputs.append(output) - return outputs - - args = SimpleNamespace(num_warmup=1, num_steps=2, seq_len=32, batch_size=2, max_new_tokens=4) - report = worker.measured_generation(Engine(), [[1, 2, 3], [4, 5]], 99, args) - assert len(submitted) == 3 - assert report['step_ms'] == pytest.approx([200, 300]) - assert report['request_count'] == 4 - assert report['input_token_counts'] == [32, 32, 32, 32] - assert report['output_token_counts'] == [1, 3, 2, 1] - assert report['request_prefill_ms'] == pytest.approx([10, 20, 30, 40]) - assert report['ttft_ms'] == pytest.approx([15, 25, 35, 45]) - assert report['decode_tpot_ms'] == pytest.approx([60, 80]) - assert report['measurement_start_unix_seconds'] == 1100 - assert report['measurement_end_unix_seconds'] == 1300 - - -def test_measured_generation_rejects_missing_requests(worker, monkeypatch): - """A partial generation batch cannot become a valid throughput sample.""" - monkeypatch.setitem(sys.modules, 'torch', SimpleNamespace(cuda=SimpleNamespace(synchronize=lambda: None))) - monkeypatch.setitem(sys.modules, 'vllm', SimpleNamespace(SamplingParams=SimpleNamespace)) - engine = SimpleNamespace(generate=lambda *args, **kwargs: []) - args = SimpleNamespace(num_warmup=0, num_steps=1, seq_len=32, batch_size=2, max_new_tokens=4) - with pytest.raises(RuntimeError, match='fewer requests'): - worker.measured_generation(engine, [[1, 2, 3]], 99, args) - - -def test_numerical_checks_cover_real_profile_and_later_decode(worker, monkeypatch): - """Use a full performance-shaped batch and retain complete selected-token traces.""" - monkeypatch.setitem(sys.modules, 'vllm', SimpleNamespace(SamplingParams=SimpleNamespace)) - submitted = [] - - class Engine: - def generate(self, prompts, parameters, use_tqdm): - submitted.append((prompts, parameters)) - outputs = [] - for prompt in prompts: - output = response(tuple(range(64))) - output.prompt_token_ids = prompt['prompt_token_ids'] - outputs.append(output) - return outputs - - args = SimpleNamespace(seq_len=512, batch_size=8, max_new_tokens=64) - records = worker.profile_checks(Engine(), [[1, 2, 3], [4, 5]], 99, args) - prompts, parameters = submitted[0] - assert len(prompts) == 8 - assert all(len(prompt['prompt_token_ids']) == 512 for prompt in prompts) - assert parameters.max_tokens == 64 and parameters.logprobs == 20 - assert [record['profile_request_index'] for record in records] == [0, 7] - assert all(record['profile_batch_size'] == 8 for record in records) - assert all(len(record['token_ids']) == len(record['logprobs']) == 64 for record in records) - assert all(record['full_prefix_steps'] == [0, 1, 32, 63] for record in records) - - -def test_numerical_profile_checks_reject_partial_batch(worker, monkeypatch): - """Numerical sampling must not hide requests dropped from its full batch.""" - monkeypatch.setitem(sys.modules, 'vllm', SimpleNamespace(SamplingParams=SimpleNamespace)) - engine = SimpleNamespace(generate=lambda *args, **kwargs: []) - args = SimpleNamespace(seq_len=512, batch_size=8, max_new_tokens=64) - with pytest.raises(RuntimeError, match='lost a request'): - worker.profile_checks(engine, [[1, 2, 3]], 99, args) - - -@pytest.fixture -def main_driver(worker, tmp_path, monkeypatch): - """Exercise the full worker's control flow without real vLLM or GPU execution.""" - if sys.version_info < (3, 10): - pytest.skip('The standalone inference runtime requires Python 3.10 or later.') - import importlib.metadata - torch = pytest.importorskip('torch') - - version = importlib.metadata.version - monkeypatch.setattr(importlib.metadata, 'version', lambda name: '0.31.0' if name == 'vllm' else version(name)) - for variable in [ - 'TORCH_ALLOW_TF32_CUBLAS_OVERRIDE', 'NVIDIA_TF32_OVERRIDE', 'VLLM_FLOAT32_MATMUL_PRECISION', - 'TRITON_F32_DEFAULT', 'VLLM_RAISE_ON_LOGIT_NANS', 'VLLM_BATCH_INVARIANT', 'VLLM_MLA_DISABLE' - ]: - monkeypatch.setenv(variable, 'test-original') - monkeypatch.setattr(worker.signal, 'signal', Mock()) - monkeypatch.setattr(worker, 'configure_cache', Mock()) - download = Mock(return_value=tmp_path / 'checkpoint') - monkeypatch.setattr(worker, 'download_checkpoint', download) - monkeypatch.setattr(torch.cuda, 'is_available', lambda: True) - monkeypatch.setattr(torch.cuda, 'set_device', Mock()) - monkeypatch.setattr(torch.cuda, 'synchronize', Mock()) - monkeypatch.setattr(torch.cuda, 'empty_cache', Mock()) - monkeypatch.setattr(torch.cuda, 'get_device_name', lambda index: 'CPU orchestration fixture') - shutdown = Mock() - config = SimpleNamespace(dtype=torch.bfloat16, quantization=None) - tokenizer = SimpleNamespace(encode=lambda *args, **kwargs: [1, 2, 3], eos_token_id=99) - - def generate(prompts, parameters, use_tqdm): - outputs = [] - stop = hasattr(parameters, 'allowed_token_ids') - tokens = parameters.allowed_token_ids if stop else list(range(7, 7 + parameters.max_tokens)) - for prompt in prompts: - output = response(tuple(tokens)) - output.prompt_token_ids = prompt['prompt_token_ids'] - if stop: - output.outputs[0].finish_reason = 'stop' - output.metrics.last_token_ts = output.metrics.first_token_ts - outputs.append(output) - return outputs - - engine = SimpleNamespace( - llm_engine=SimpleNamespace(model_config=config, engine_core=SimpleNamespace(shutdown=shutdown)), - get_tokenizer=lambda: tokenizer, - generate=generate, - ) - factory = Mock(return_value=engine) - monkeypatch.setitem(sys.modules, 'vllm', SimpleNamespace(LLM=factory, SamplingParams=SimpleNamespace)) - - def reference(command, log, timeout): - assert timeout > 0 - assert shutdown.called - output = Path(command[command.index('--output') + 1]) - worker.write_json(output, {'correctness_passed': True, 'teardown_complete': True}) - - oracle = Mock(side_effect=reference) - monkeypatch.setattr(worker, 'run_worker', oracle) - output = tmp_path / 'report.json' - argv = [ - 'worker', - '--cache_dir', - str(tmp_path / 'cache'), - '--output', - str(output), - '--reference_python', - 'reference-python', - '--batch_size', - '2', - '--seq_len', - '64', - '--num_warmup', - '1', - '--num_steps', - '2', - '--max_new_tokens', - '4', - '--duration', - '60', - ] - monkeypatch.setattr(sys, 'argv', argv) - return SimpleNamespace( - output=output, - argv=argv, - factory=factory, - engine=engine, - config=config, - shutdown=shutdown, - oracle=oracle, - download=download, - torch=torch, - ) - - -def test_inference_main_keeps_precision_counts_and_reference_lifecycle(worker, main_driver): - """Check the selected policies and report only after shutdown and reference success.""" - state = main_driver - worker.main() - options = state.factory.call_args[1] - assert options['dtype'] == 'bfloat16' and options['quantization'] is None - assert options['hf_overrides'] == {'moe_router_dtype': 'float32'} - assert options['max_model_len'] == 68 and options['max_num_seqs'] == 2 - report = json.loads(state.output.read_text()) - assert report['status'] == 'success' and report['correctness_passed'] and report['teardown_complete'] - assert report['request_count'] == 4 and report['output_token_counts'] == [4] * 4 - assert report['router_dtype'] == 'float32' and report['float32_matmul_precision'] == 'highest' - assert report['numerical_policy'] == 'strict_fp32' and report['batch_invariant'] is False - state.shutdown.assert_called_once_with(timeout=10) - state.oracle.assert_called_once() - - -def test_nan_detection_is_enabled_before_vllm_import(worker, main_driver, monkeypatch): - """Reject a disabled inherited setting before the engine module is imported.""" - real_import = __import__ - engine_imports = [] - - def checked_import(name, *args, **kwargs): - if name == 'vllm': - assert worker.os.environ['VLLM_RAISE_ON_LOGIT_NANS'] == '1' - engine_imports.append(name) - return real_import(name, *args, **kwargs) - - monkeypatch.setattr('builtins.__import__', checked_import) - worker.main() - assert engine_imports - - -def test_corrupted_measured_generation_cannot_publish_success(worker, main_driver, monkeypatch): - """Corruption in unscored measured requests must prevent result publication.""" - generate = main_driver.engine.generate - - def corrupted_generation(*args, **kwargs): - outputs = generate(*args, **kwargs) - for output in outputs: - output.metrics.is_corrupted = True - return outputs - - monkeypatch.setattr(main_driver.engine, 'generate', corrupted_generation) - with pytest.raises(RuntimeError, match='logits were corrupted'): - worker.main() - main_driver.shutdown.assert_called_once() - main_driver.oracle.assert_not_called() - assert not main_driver.output.exists() - - -def test_engine_error_still_shuts_down(worker, main_driver, monkeypatch): - """Generation failure cannot leave the engine alive or produce performance success.""" - monkeypatch.setattr(main_driver.engine, 'generate', Mock(side_effect=RuntimeError('generation failed'))) - with pytest.raises(RuntimeError, match='generation failed'): - worker.main() - main_driver.shutdown.assert_called_once() - main_driver.oracle.assert_not_called() - assert not main_driver.output.exists() - - -def test_failed_reference_is_not_success(worker, main_driver): - """A numerically rejected generation run must not publish a success report.""" - main_driver.oracle.side_effect = RuntimeError('numerical gate failed') - with pytest.raises(RuntimeError, match='numerical gate'): - worker.main() - main_driver.shutdown.assert_called_once() - assert not main_driver.output.exists() - - -def test_wrong_engine_precision_is_rejected(worker, main_driver): - """Do not silently replace the BF16 performance workload with another precision.""" - main_driver.config.dtype = main_driver.torch.float32 - with pytest.raises(RuntimeError, match='unquantized BF16'): - worker.main() - main_driver.shutdown.assert_called_once() - assert not main_driver.output.exists() - - -def test_unsupported_engine_version_fails_before_download(worker, main_driver, monkeypatch): - """Version-specific timing and shutdown contracts must not silently drift.""" - import importlib.metadata - version = importlib.metadata.version - monkeypatch.setattr(importlib.metadata, 'version', lambda name: '0.32.0' if name == 'vllm' else version(name)) - with pytest.raises(RuntimeError, match='pinned vLLM'): - worker.main() - main_driver.download.assert_not_called() - - -def test_inference_does_not_fall_back_to_cpu(worker, main_driver, monkeypatch): - """Unavailable GPU execution is an explicit failure, not a replacement benchmark.""" - monkeypatch.setattr(main_driver.torch.cuda, 'is_available', lambda: False) - with pytest.raises(RuntimeError, match='GPU unavailable'): - worker.main() - main_driver.download.assert_not_called() - - -def test_reference_success_code_requires_correctness_flags(worker, main_driver): - """Returning from the oracle process is insufficient without its explicit checks.""" - def rejected(command, log, timeout): - output = Path(command[command.index('--output') + 1]) - worker.write_json(output, {'correctness_passed': False, 'teardown_complete': True}) - - main_driver.oracle.side_effect = rejected - with pytest.raises(RuntimeError, match='reference did not complete'): - worker.main() - assert not main_driver.output.exists() - - -@pytest.mark.parametrize( - 'override', [ - ['--batch_size', '0'], - ['--seq_len', '16'], - ['--num_steps', '0'], - ['--num_warmup', '-1'], - ['--max_new_tokens', '3'], - ['--gpu_memory_utilization', 'nan'], - ['--duration', '3600'], - ] -) -def test_inference_preflight_rejects_invalid_profile(worker, main_driver, monkeypatch, override): - """Invalid generation parameters must fail before download or engine creation.""" - monkeypatch.setattr(sys, 'argv', main_driver.argv + override) - with pytest.raises(ValueError): - worker.main() - main_driver.download.assert_not_called() - main_driver.factory.assert_not_called() - - -def h100_arguments(worker, main_driver): - """Select the frozen shape without changing the existing small fixture's defaults.""" - arguments = main_driver.argv + ['--numerical_policy', worker.numerics.POLICY] - for key, value in worker.numerics.PROFILE.items(): - arguments.extend(['--' + key, str(value)]) - return arguments - - -def test_h100_checks_retain_every_window_and_batch_row(worker, main_driver): - """The runtime replays all qualification windows, not only first/last rows.""" - args = SimpleNamespace(**worker.numerics.PROFILE) - documents, eos = [[1, 2, 3], [4, 5]], 99 - records = worker.qualified_checks(main_driver.engine, documents, eos, args) - assert len(records) == 84 - groups = worker.numerics.validate_requests(records, documents, eos) - assert list(groups) == list(worker.numerics.OFFSETS) - assert all(sum(len(record['token_ids']) for record in group) == 536 for group in groups.values()) - - -def test_h100_policy_uses_pinned_engine_settings_and_separate_reference(worker, main_driver, monkeypatch): - """Wire the explicit policy without replacing the measured BF16 model.""" - monkeypatch.setattr(sys, 'argv', h100_arguments(worker, main_driver)) - expected_gpu = worker.numerics.load_contract()['calibrated_contract']['runtime_identity']['gpu_name'] - monkeypatch.setattr(main_driver.torch.cuda, 'get_device_name', lambda index: expected_gpu) - main_driver.config.use_mla = True - validation = Mock() - monkeypatch.setattr(worker.numerics, 'validate_reference_result', validation) - worker.main() - report = json.loads(main_driver.output.read_text()) - assert report['numerical_policy'] == worker.numerics.POLICY and report['batch_invariant'] is True - assert main_driver.factory.call_args.kwargs['dtype'] == 'bfloat16' - command = main_driver.oracle.call_args.args[0] - assert command[1].endswith('deepseek_v2_lite_numerics.py') and '--mode' not in command - assert len(json.loads((main_driver.output.parent / 'reference-requests.json').read_text())) == 84 - validation.assert_called_once_with(report['reference']) - assert worker.os.environ['VLLM_BATCH_INVARIANT'] == '1' - assert worker.os.environ['VLLM_MLA_DISABLE'] == '0' - main_driver.shutdown.assert_called_once() - - -def test_h100_policy_rejects_another_gpu_before_download(worker, main_driver, monkeypatch): - """A qualified H100 policy cannot be silently reused on other hardware.""" - monkeypatch.setattr(sys, 'argv', h100_arguments(worker, main_driver)) - with pytest.raises(ValueError, match='qualified H100 hardware'): - worker.main() - main_driver.download.assert_not_called() - - -def test_h100_policy_rejects_expanded_kv_and_still_shuts_down(worker, main_driver, monkeypatch): - """Preserve the measured implementation as well as model dtype.""" - monkeypatch.setattr(sys, 'argv', h100_arguments(worker, main_driver)) - expected_gpu = worker.numerics.load_contract()['calibrated_contract']['runtime_identity']['gpu_name'] - monkeypatch.setattr(main_driver.torch.cuda, 'get_device_name', lambda index: expected_gpu) - main_driver.config.use_mla = False - with pytest.raises(RuntimeError, match='compressed-MLA'): - worker.main() - main_driver.shutdown.assert_called_once() - main_driver.oracle.assert_not_called() diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_numerics.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_numerics.py deleted file mode 100644 index 963f58eb7..000000000 --- a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_numerics.py +++ /dev/null @@ -1,555 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -"""CPU controls for the input-matched policy, not hardware qualification.""" - -import hashlib -import importlib.util -import inspect -import json -import math -import sys -from pathlib import Path -from types import SimpleNamespace -from unittest.mock import Mock - -import pytest - - -@pytest.fixture -def numerics(monkeypatch): - """Load the standalone reference without importing the engine.""" - directory = Path(__file__).resolve().parents[3] / 'superbench/benchmarks/model_benchmarks' - monkeypatch.syspath_prepend(str(directory)) - spec = importlib.util.spec_from_file_location('v2lite_numerics_test', directory / 'deepseek_v2_lite_numerics.py') - if spec is None or spec.loader is None: - raise RuntimeError('Cannot load the standalone numerical reference.') - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -def budgets(): - """Use deliberately small synthetic bounds for arithmetic controls.""" - return { - 'max_probability_error': 0.02, - 'relative_probability_mass_error': 0.03, - 'normalized_logprob_error': 0.5, - } - - -@pytest.fixture -def policy_file(numerics, tmp_path, monkeypatch): - """Create qualified-shaped test evidence without claiming GPU execution.""" - monkeypatch.setattr(numerics, '__file__', str(tmp_path / 'superbench/benchmarks/model_benchmarks/reference.py')) - path = tmp_path / 'superbench/config/deepseek-v2-lite-h100-numerics.json' - path.parent.mkdir(parents=True) - candidate = { - 'method': numerics.METHOD, - 'reference_only': True, - 'input_matched_limit_rule': numerics.LIMIT_RULE, - 'qualification_offsets': list(numerics.OFFSETS), - 'profile': {key: numerics.PROFILE[key] - for key in ('batch_size', 'seq_len', 'max_new_tokens')}, - 'qualification_stream': {key: numerics.PROFILE[key] - for key in ('num_warmup', 'num_steps')}, - } - candidate['frozen_limits_sha256'] = numerics.canonical_hash(candidate) - contract = { - 'status': 'qualified', - 'calibrated_contract': candidate, - 'qualification': [{ - 'profile_offset': offset - } for offset in numerics.OFFSETS], - 'reference_validation': { - 'non_anchor_comparisons': 1 - }, - } - - def save(): - path.write_text(json.dumps(contract)) - monkeypatch.setattr(numerics, 'CONTRACT_SHA256', hashlib.sha256(path.read_bytes()).hexdigest()) - - save() - return SimpleNamespace(path=path, contract=contract, candidate=candidate, save=save) - - -def test_frozen_profile_is_explicit_and_legacy_policy_is_unchanged(numerics): - """Do not apply one H100 qualification to other shapes or the default policy.""" - numerics.validate_profile(SimpleNamespace(numerical_policy='strict_fp32', batch_size=1)) - args = SimpleNamespace(numerical_policy=numerics.POLICY, **numerics.PROFILE) - numerics.validate_profile(args) - args.num_steps -= 1 - with pytest.raises(ValueError, match='complete frozen'): - numerics.validate_profile(args) - with pytest.raises(ValueError, match='Unknown'): - numerics.validate_profile(SimpleNamespace(numerical_policy='other')) - - -def test_contract_requires_installed_qualification(numerics, monkeypatch): - """An unfinished policy cannot start a reference workload.""" - monkeypatch.setattr(numerics, 'CONTRACT_SHA256', '') - with pytest.raises(RuntimeError, match='qualified contract'): - numerics.load_contract() - - -def test_contract_is_bound_to_exact_file_bytes(numerics, policy_file): - """Even a semantically equivalent substituted policy requires a new identity.""" - assert numerics.load_contract() == policy_file.contract - policy_file.path.write_text(policy_file.path.read_text() + '\n') - with pytest.raises(ValueError, match='changed'): - numerics.load_contract() - - -@pytest.mark.parametrize('fault', ['status', 'method', 'shape', 'stream', 'offsets', 'evidence', 'anchor-only', 'hash']) -def test_contract_rejects_incomplete_qualification(numerics, policy_file, fault): - """Validate semantics as well as a matching artifact digest.""" - candidate, contract = policy_file.candidate, policy_file.contract - if fault == 'status': - contract['status'] = 'candidate' - elif fault == 'method': - candidate['method'] = 'unqualified-method' - elif fault == 'shape': - candidate['profile']['batch_size'] = 1 - elif fault == 'stream': - candidate['qualification_stream']['num_steps'] = 1 - elif fault == 'offsets': - candidate['qualification_offsets'].pop() - elif fault == 'evidence': - contract['qualification'].pop() - elif fault == 'anchor-only': - contract['reference_validation']['non_anchor_comparisons'] = 0 - else: - candidate['frozen_limits_sha256'] = 'changed' - if fault != 'hash': - candidate['frozen_limits_sha256'] = numerics.canonical_hash( - {key: value - for key, value in candidate.items() if key != 'frozen_limits_sha256'} - ) - policy_file.save() - with pytest.raises(ValueError, match='qualification'): - numerics.load_contract() - - -@pytest.mark.parametrize( - 'expected,actual', [ - ([], []), - ([-1.0], []), - ([float('nan')], [-1.0]), - ([-1.0], [float('inf')]), - ([-1.0], [True]), - ([-1.0], [0.1]), - ([-1000.0], [-1000.0]), - ([0.0, 0.0], [0.0, 0.0]), - ] -) -def test_invalid_probability_data_is_rejected(numerics, expected, actual): - """Reject malformed, nonfinite and unnormalized probabilities explicitly.""" - with pytest.raises(ValueError): - numerics.probability_errors(expected, actual) - - -def test_probability_mass_and_log_metrics_retain_every_token(numerics): - """Detect normalization defects even when the greedy token is unchanged.""" - expected = [math.log(0.6), math.log(0.3)] - actual = [value - math.log(2) for value in expected] - errors = numerics.probability_errors(expected, actual) - assert errors['max_probability_error'] == pytest.approx(0.3) - assert errors['relative_probability_mass_error'] == pytest.approx(0.5) - assert errors['max_logprob_error'] == pytest.approx(math.log(2)) - assert errors['normalized_logprob_error'] > 0 - - -def test_input_matched_limits_are_reference_only(numerics): - """Keep calibration unchanged and fail if uncertainty admits half normalization.""" - calibrated = budgets() - original = dict(calibrated) - reference = {metric: 0.01 for metric in numerics.METRICS} - assert numerics.input_matched_limits(calibrated, reference) == { - metric: original[metric] + reference[metric] - for metric in numerics.METRICS - } - assert calibrated == original - reference['relative_probability_mass_error'] = 0.5 - with pytest.raises(ValueError, match='half-normalization'): - numerics.input_matched_limits(calibrated, reference) - reference['relative_probability_mass_error'] = float('nan') - with pytest.raises(ValueError, match='input-matched'): - numerics.input_matched_limits(calibrated, reference) - reference['relative_probability_mass_error'] = 0 - calibrated['normalized_logprob_error'] = 0 - with pytest.raises(ValueError, match='budget'): - numerics.input_matched_limits(calibrated, reference) - - -def test_greedy_rules_and_invalid_bounds(numerics): - """Near ties do not waive reported-greedy or probability-gap checks.""" - expected = {0: math.log(0.9), 1: math.log(0.1)} - result = numerics.score_probabilities(expected, expected, 1, 0, budgets()) - assert not result['accepted'] and not result['greedy_match'] - assert 'reported token is not greedy' in result['failures'] - assert 'greedy choice exceeds calibrated uncertainty' in result['failures'] - assert numerics.score_probabilities(expected, expected, 0, 0, budgets())['accepted'] - with pytest.raises(ValueError, match='Incomplete'): - numerics.score_probabilities(expected, {0: expected[0]}, 0, 0, budgets()) - limits = budgets() - limits['normalized_logprob_error'] = float('inf') - with pytest.raises(ValueError, match='bound'): - numerics.score_probabilities(expected, expected, 0, 0, limits) - - -def test_top_k_shape_bounds_and_tail_fault(numerics): - """A tiny tail still has to reject the fixed temperature fault.""" - torch = pytest.importorskip('torch') - logits = torch.full((32, ), -40.0) - logits[0] = 0 - expected = logits.log_softmax(-1) - wrong = (expected / 2).log_softmax(-1) - ids = wrong.topk(20).indices.tolist() - observed = {str(key): wrong[key].item() for key in ids} - result = numerics.evaluate_logits(expected, observed, 0, budgets()) - assert not result['accepted'] and 'normalized_logprob_error' in result['failures'] - with pytest.raises(ValueError, match='top-20'): - numerics.evaluate_logits(expected, {'0': 0.0}, 0, budgets()) - observed['1000'] = observed.pop(str(ids[-1])) - with pytest.raises(ValueError, match='out of range'): - numerics.evaluate_logits(expected, observed, 0, budgets()) - missing = {str(key): -10.0 for key in range(1, 21)} - assert not numerics.evaluate_logits(expected, missing, 1, budgets())['accepted'] - duplicate = {str(key): -10.0 for key in range(20)} - duplicate['00'] = -10.0 - with pytest.raises(ValueError, match='duplicated'): - numerics.evaluate_logits(expected, duplicate, 0, budgets()) - - -@pytest.fixture -def cpu_reference(monkeypatch): - """Exercise reference tensor operations on CPU with explicit fake device transport.""" - torch = pytest.importorskip('torch') - tensor, ones = torch.tensor, torch.ones - - def cpu_tensor(*args, **kwargs): - if kwargs.get('device') == 'cuda': - kwargs['device'] = 'cpu' - return tensor(*args, **kwargs) - - def cpu_ones(*args, **kwargs): - if kwargs.get('device') == 'cuda': - kwargs['device'] = 'cpu' - return ones(*args, **kwargs) - - monkeypatch.setattr(torch, 'tensor', cpu_tensor) - monkeypatch.setattr(torch, 'ones', cpu_ones) - return torch - - -def test_complete_prefix_and_cached_reference_shapes(numerics, cpu_reference): - """Check all attention-mask lengths and cache positions without a GPU.""" - torch = cpu_reference - calls = [] - - def model(input_ids, attention_mask, use_cache, past_key_values=None): - calls.append((input_ids.shape, attention_mask.shape, use_cache, past_key_values)) - logits = torch.arange(24, dtype=torch.float32).reshape(1, 1, 24) - return SimpleNamespace( - logits=logits.expand(input_ids.shape[0], input_ids.shape[1], 24), past_key_values=len(calls) - ) - - cases = [{'id': str(index), 'prompt_token_ids': [1, 2, 3], 'continuation_ids': [4, 5]} for index in range(3)] - full = numerics.full_logits(model, [[1, 2, 3]]) - assert full.shape == (1, 24) and calls[-1][2:] == (False, None) - values = numerics.collect_matched_bf16(model, cases, 2) - assert set(values) == {'0', '1', '2'} and all(value.shape == (2, 24) for value in values.values()) - assert calls[1][0:2] == (torch.Size([2, 3]), torch.Size([2, 3])) - assert calls[2][0:2] == (torch.Size([2, 1]), torch.Size([2, 4])) - assert calls[2][3] is not None - errors = numerics.tensor_errors(values['0'][0], values['1'][0]) - assert errors['greedy_match'] and all(errors[metric] == 0 for metric in numerics.METRICS) - with pytest.raises(ValueError, match='uniquely'): - numerics.configured_batches(cases + cases, 2) - mismatched = [cases[0], dict(cases[1], continuation_ids=[4])] - with pytest.raises(ValueError, match='matching sequence'): - list(numerics.cached_logits(model, mismatched)) - - -def test_reference_rejects_nonfinite_and_incomplete_output(numerics, cpu_reference, monkeypatch): - """Reference failures cannot create success-shaped numerical evidence.""" - torch = cpu_reference - - def model(**kwargs): - return SimpleNamespace(logits=torch.full((1, 2, 24), float('nan')), past_key_values=1) - - cases = [{'id': '0', 'prompt_token_ids': [1, 2], 'continuation_ids': [3]}] - with pytest.raises(RuntimeError, match='Nonfinite'): - numerics.full_logits(model, [[1, 2]]) - with pytest.raises(RuntimeError, match='Nonfinite'): - list(numerics.cached_logits(model, cases)) - monkeypatch.setattr(numerics, 'cached_logits', lambda *args: iter([])) - with pytest.raises(ValueError, match='Incomplete'): - numerics.collect_matched_bf16(model, cases, 1) - monkeypatch.setattr(numerics, 'cached_logits', lambda *args: iter([(1, torch.zeros((1, 24)))])) - with pytest.raises(ValueError, match='out-of-order'): - numerics.collect_matched_bf16(model, cases, 1) - - -def request_sets(numerics): - """Create token-shaped fixtures, not reference or engine measurements.""" - documents, eos, records = [[1, 2, 3], [4, 5, 6]], 99, [] - short = [ - numerics.packed_tokens(documents, eos, length, 1, index * 7)[0] for index, length in enumerate((16, 23, 32)) - ] - for offset in numerics.OFFSETS: - prompts = short * 2 + numerics.packed_tokens(documents, eos, 512, 8, offset) - for index, prompt in enumerate(prompts): - count = 4 if index < 6 else 64 - row = { - 'prompt_token_ids': prompt, - 'token_ids': [1] * count, - 'logprobs': [{} for _ in range(count)], - 'numerical_set_offset': offset, - } - if index >= 6: - row.update(profile_request_index=index - 6, profile_batch_size=8) - records.append(row) - return documents, eos, records - - -@pytest.mark.parametrize('fault', ['missing-window', 'wrong-prompt', 'short-decode', 'lost-row', 'bad-token', 'trace']) -def test_frozen_request_sets_cannot_drop_positions(numerics, fault): - """Require all six windows and every configured-batch row.""" - documents, eos, requests = request_sets(numerics) - groups = numerics.validate_requests(requests, documents, eos) - assert list(groups) == list(numerics.OFFSETS) - if fault == 'missing-window': - requests.pop() - elif fault == 'wrong-prompt': - requests[0]['prompt_token_ids'] = [7] - elif fault == 'short-decode': - for row in requests[:14]: - row['token_ids'] = row['token_ids'][:1] - row['logprobs'] = row['logprobs'][:1] - elif fault == 'lost-row': - requests[6]['profile_request_index'] = 2 - elif fault == 'bad-token': - requests[0]['token_ids'][0] = True - else: - requests[0]['logprobs'].pop() - with pytest.raises(ValueError): - numerics.validate_requests(requests, documents, eos) - - -@pytest.mark.parametrize('corrupt', [False, True]) -def test_group_scoring_retains_all_positive_and_fault_positions(numerics, monkeypatch, corrupt): - """A good synthetic pair must reject every fault; a corrupted pair must fail.""" - torch = pytest.importorskip('torch') - vectors = [torch.arange(32, dtype=torch.float32), torch.arange(31, -1, -1, dtype=torch.float32)] - expected = [value.log_softmax(-1) for value in vectors] - requests, matched = [], {} - for index in range(2): - ids = expected[index].topk(20).indices.tolist() - observed = {str(key): expected[index][key].item() for key in ids} - if corrupt: - observed = {key: value - math.log(2) for key, value in observed.items()} - requests.append( - { - 'prompt_token_ids': [index], - 'token_ids': [expected[index].argmax().item()] * 2, - 'logprobs': [observed, observed], - } - ) - matched['request-{}'.format(index)] = torch.stack([expected[index], expected[index]]) - monkeypatch.setattr(numerics, 'full_logits', lambda model, rows: vectors[rows[0][0]].unsqueeze(0)) - result = numerics.evaluate_group(None, requests, matched, budgets()) - assert result['positive_positions'] == 4 and result['negative_positions'] == 9 - assert len(result['positive_failures']) == (4 if corrupt else 0) - assert not result['negative_failures'] - assert {row['fault'] - for row in result['all_negative_records']} == { - 'half-normalization', - 'temperature-two', - 'last-request-context-for-first', - } - - -@pytest.mark.parametrize('failure', [False, True]) -def test_reference_models_are_sequential_and_always_released(numerics, monkeypatch, failure): - """Exercise lifecycle plumbing with explicit CPU-only model doubles.""" - if sys.version_info < (3, 10): - pytest.skip('The standalone reference runtime requires Python 3.10 or later.') - torch = pytest.importorskip('torch') - import deepseek_v2_lite_reference as reference - - loaded = [] - - def load_model(checkpoint, dtype): - loaded.append(dtype) - model = SimpleNamespace() - model.cuda = lambda: model - model.eval = lambda: model - return model - - monkeypatch.setattr(reference, 'load_model', load_model) - monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: ([[1, 2]], 99)) - monkeypatch.setattr(numerics, 'validate_requests', lambda *args: {0: [{'prompt_token_ids': [1], 'token_ids': [2]}]}) - monkeypatch.setattr(numerics, 'collect_matched_bf16', lambda *args: {}) - monkeypatch.setattr(torch, 'set_num_threads', Mock()) - monkeypatch.setattr(torch, 'set_float32_matmul_precision', Mock()) - monkeypatch.setattr(torch.cuda, 'set_device', Mock()) - monkeypatch.setattr(torch.cuda, 'get_device_name', lambda index: 'synthetic-h100') - release = Mock() - monkeypatch.setattr(torch.cuda, 'empty_cache', release) - monkeypatch.setattr(torch.cuda, 'synchronize', Mock()) - from importlib.metadata import version - identity = { - 'torch_version': torch.__version__, - 'transformers_version': version('transformers'), - 'gpu_name': 'synthetic-h100', - 'reference_loader_sha256': hashlib.sha256(inspect.getsource(load_model).encode()).hexdigest(), - 'tf32_allowed': False, - 'bf16_reduced_precision_reduction': torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction, - } - contract = { - 'calibrated_contract': { - 'runtime_identity': identity, - 'limits': budgets(), - 'frozen_limits_sha256': 'fixture' - } - } - evaluation = Mock( - side_effect=RuntimeError('reference failed') if failure else None, - return_value={ - 'positive_positions': 1, - 'negative_positions': 3, - 'positive_failures': [], - 'negative_failures': [] - }, - ) - monkeypatch.setattr(numerics, 'evaluate_group', evaluation) - if failure: - with pytest.raises(RuntimeError, match='reference failed'): - numerics.run_reference(Path('fixture'), [1], contract) - else: - result = numerics.run_reference(Path('fixture'), [1], contract) - assert result['correctness_passed'] is True and result['teardown_complete'] is True - assert loaded == [torch.bfloat16, torch.float32] - assert release.call_count == 2 - identity['gpu_name'] = 'different-hardware' - with pytest.raises(ValueError, match='runtime or hardware'): - numerics.run_reference(Path('fixture'), [1], contract) - - -@pytest.mark.parametrize('passed', [True, False]) -def test_reference_cli_preserves_rejection_evidence(numerics, monkeypatch, tmp_path, passed): - """A rejected report is saved but the process must still fail explicitly.""" - requests, output = tmp_path / 'requests.json', tmp_path / 'reference.json' - requests.write_text('[]') - monkeypatch.setattr( - sys, 'argv', [ - 'reference', - '--checkpoint', - str(tmp_path), - '--requests', - str(requests), - '--output', - str(output), - ] - ) - monkeypatch.setattr(numerics, 'load_contract', lambda: {'fixture': True}) - monkeypatch.setattr(numerics, 'run_reference', lambda *args: {'correctness_passed': passed}) - validate = Mock() - monkeypatch.setattr(numerics, 'validate_reference_result', validate) - if passed: - numerics.main() - else: - with pytest.raises(RuntimeError, match='rejected'): - numerics.main() - assert json.loads(output.read_text())['correctness_passed'] is passed - assert numerics.os.environ['NVIDIA_TF32_OVERRIDE'] == '0' - assert validate.call_count == int(passed) - - -def serialized_reference(numerics): - """Build complete control-flow evidence with explicit synthetic accepted/rejected flags.""" - windows = {} - for offset in numerics.OFFSETS: - positives, negatives = [], [] - for request in range(14): - count = 4 if request < 6 else 64 - for step in range(count): - positives.append({'request': request, 'step': step, 'accepted': True}) - negatives.extend( - [ - { - 'request': request, - 'step': step, - 'accepted': False, - 'fault': fault - } for fault in ('half-normalization', 'temperature-two') - ] - ) - negatives.append({'request': 0, 'step': 0, 'accepted': False, 'fault': 'last-request-context-for-first'}) - windows[str(offset)] = { - 'positive_positions': len(positives), - 'negative_positions': len(negatives), - 'positive_failures': [], - 'negative_failures': [], - 'all_positive_records': positives, - 'all_negative_records': negatives, - } - return { - 'correctness_passed': True, - 'teardown_complete': True, - 'numerical_policy': numerics.POLICY, - 'contract_sha256': numerics.CONTRACT_SHA256, - 'profile_offsets': list(numerics.OFFSETS), - 'request_count': 84, - 'positive_positions': 3216, - 'negative_positions': 6438, - 'windows': windows, - } - - -@pytest.mark.parametrize( - 'fault', [ - 'identity', - 'missing-window', - 'invalid-window', - 'missing-position', - 'accepted-fault', - 'failed-positive', - 'bad-index', - 'duplicate-position', - 'missing-step', - 'wrong-fault', - 'totals', - ] -) -def test_serialized_reference_cannot_fabricate_complete_success(numerics, fault): - """Validate all per-window records rather than trusting a summary flag.""" - report = serialized_reference(numerics) - numerics.validate_reference_result(report) - window = report['windows']['0'] - overrides = {'identity': ('contract_sha256', 'another-policy'), 'totals': ('positive_positions', 3215)} - if fault in overrides: - key, value = overrides[fault] - report[key] = value - elif fault == 'missing-window': - report['windows'].pop('0') - elif fault == 'invalid-window': - report['windows']['0'] = None - elif fault == 'missing-position': - window['all_positive_records'].pop() - elif fault == 'accepted-fault': - window['all_negative_records'][0]['accepted'] = True - elif fault == 'failed-positive': - window['all_positive_records'][0]['accepted'] = False - elif fault == 'bad-index': - window['all_positive_records'][0]['step'] = True - elif fault == 'duplicate-position': - window['all_positive_records'][0] = dict(window['all_positive_records'][1]) - elif fault == 'missing-step': - window['all_positive_records'][0]['step'] = 5 - else: - window['all_negative_records'][-1]['fault'] = 'substituted-fault' - with pytest.raises(ValueError): - numerics.validate_reference_result(report) diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_reference.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_reference.py deleted file mode 100644 index 50a88fc02..000000000 --- a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_reference.py +++ /dev/null @@ -1,377 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -"""CPU control-flow checks, not certification of full-model reference numerics.""" - -import importlib.util -import json -import sys -import weakref -from pathlib import Path -from types import SimpleNamespace -from unittest.mock import Mock - -import pytest - -torch = pytest.importorskip('torch') - - -@pytest.fixture -def reference(monkeypatch): - """Load the standalone oracle and redirect only test tensor creation to CPU.""" - directory = Path(__file__).resolve().parents[3] / 'superbench/benchmarks/model_benchmarks' - monkeypatch.syspath_prepend(str(directory)) - spec = importlib.util.spec_from_file_location('v2lite_reference_test', directory / 'deepseek_v2_lite_reference.py') - if spec is None or spec.loader is None: - raise RuntimeError('Cannot load the standalone reference.') - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - tensor = torch.tensor - - def cpu_tensor(data, *args, **kwargs): - if kwargs.get('device') == 'cuda': - kwargs['device'] = 'cpu' - return tensor(data, *args, **kwargs) - - monkeypatch.setattr(torch, 'tensor', cpu_tensor) - return module - - -class ReferenceFixture: - """Expose token-independent logits while checking cached attention shapes.""" - def __init__(self): - """Track cache and full-prefix calls separately.""" - self.calls = [] - - def eval(self): - """Retain the minimal evaluation interface used by the oracle.""" - return self - - def __call__(self, input_ids, attention_mask, past_key_values=None, use_cache=True): - """Require a mask for all past and current positions, including one-token decode.""" - length = input_ids.shape[1] - total = length + (past_key_values or 0) - assert attention_mask.shape == (1, total) - assert attention_mask.all().item() - self.calls.append((length, total, past_key_values, use_cache)) - logits = torch.tensor([0.0, 1.0, 2.0, 3.0]).reshape(1, 1, 4).repeat(1, length, 1) - return SimpleNamespace(logits=logits, past_key_values=total if use_cache else None) - - -def request_fixture(): - """Provide exact fixture probabilities rather than a model-quality claim.""" - probabilities = torch.tensor([0.0, 1.0, 2.0, 3.0]).log_softmax(-1).tolist() - return { - 'prompt_token_ids': [1, 2], - 'token_ids': [3, 3], - 'logprobs': [{str(index): value - for index, value in enumerate(probabilities)} for _ in range(2)], - } - - -def test_cached_decode_mask_covers_full_prefix(reference): - """The second cache call has one input token but a three-position mask.""" - model = ReferenceFixture() - result = reference.inference_reference(model, [request_fixture()]) - assert model.calls == [(2, 2, None, True), (2, 2, None, False), (1, 3, 2, True), (3, 3, None, False)] - assert len(result['comparisons']) == 2 - assert all(row['cache_max_abs_error'] == 0 for row in result['comparisons']) - - -@pytest.mark.parametrize('requests', [[], [{'prompt_token_ids': [], 'token_ids': [], 'logprobs': []}]]) -def test_incomplete_reference_requests_fail(reference, requests): - """Never accept an empty or truncated numerical workload.""" - with pytest.raises(ValueError, match='nonempty|Incomplete'): - reference.inference_reference(ReferenceFixture(), requests) - - -def test_reference_requires_greedy_token_agreement(reference): - """Finite probabilities alone must not certify an incorrect generated token.""" - request = request_fixture() - request['token_ids'][0] = 1 - with pytest.raises(RuntimeError, match='greedy token'): - reference.inference_reference(ReferenceFixture(), [request]) - - -def test_reference_does_not_ignore_probability_mismatch(reference): - """Keep the numerical gate even when all generated tokens are correct.""" - request = request_fixture() - request['logprobs'][0]['3'] += 1.0 - with pytest.raises(AssertionError, match='request 0 step 0'): - reference.inference_reference(ReferenceFixture(), [request]) - - -def test_long_decode_checks_every_engine_token_with_bounded_full_prefix_calls(reference): - """Only full-prefix recomputation is sampled, never engine probability validation.""" - request = request_fixture() - request['token_ids'] *= 4 - request['logprobs'] *= 4 - request['full_prefix_steps'] = [0, 1, 4, 7] - model = ReferenceFixture() - result = reference.inference_reference(model, [request]) - assert len(result['comparisons']) == 8 - assert len(model.calls) == 12 - assert [row['step'] for row in result['comparisons'] if row['full_prefix_checked']] == [0, 1, 4, 7] - assert all(row['cache_max_abs_error'] is None for row in result['comparisons'] if not row['full_prefix_checked']) - request['logprobs'][2] = dict(request['logprobs'][2], **{'3': 0.0}) - with pytest.raises(AssertionError, match='request 0 step 2'): - reference.inference_reference(ReferenceFixture(), [request]) - - -@pytest.mark.parametrize('positions', [[], [0], [1], [0, 0, 1], [1, 0], [0, 2], [False, 1]]) -def test_invalid_full_prefix_sampling_fails(reference, positions): - """Do not accept malformed or first/final-step-incomplete numerical evidence.""" - request = request_fixture() - request['full_prefix_steps'] = positions - with pytest.raises(ValueError, match='reference positions'): - reference.inference_reference(ReferenceFixture(), [request]) - - -class TrainingReferenceFixture: - """Small autograd fixture for global-batch partitioning, not GPU model validation.""" - def __init__(self): - """Create the named parameters required by reference sampling.""" - names = [ - 'model.embed_tokens.weight', - 'model.layers.0.self_attn.q_proj.weight', - 'model.layers.0.self_attn.kv_a_proj_with_mqa.weight', - 'model.layers.0.mlp.down_proj.weight', - 'model.layers.1.mlp.gate.weight', - 'model.layers.1.mlp.experts.0.down_proj.weight', - ] - self.parameters = {name: torch.nn.Parameter(torch.ones(2, 2)) for name in names} - self.batches = [] - self.checkpointing = False - - def train(self): - """Expose the reference model's training-mode interface.""" - return self - - def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs): - """Require the memory-bounded nonreentrant reference policy.""" - assert gradient_checkpointing_kwargs == {'use_reentrant': False} - self.checkpointing = True - - def named_parameters(self): - """Expose stable names for independently selected gradient probes.""" - return self.parameters.items() - - def get_parameter(self, name): - """Look up the same parameter on each logical rank batch.""" - return self.parameters[name] - - def zero_grad(self, set_to_none): - """Discard local gradients before the next reference batch.""" - assert set_to_none - for parameter in self.parameters.values(): - parameter.grad = None - - def __call__(self, input_ids, labels, use_cache): - """Produce input-dependent gradients that differ between rank batches.""" - assert not use_cache and torch.equal(input_ids, labels) - self.batches.append(input_ids.clone()) - loss = sum(parameter.sum() for parameter in self.parameters.values()) * input_ids.float().mean() - return SimpleNamespace(loss=loss) - - -def test_training_reference_averages_distinct_real_profile_rank_batches(reference, monkeypatch): - """Check different rank inputs and float32 gradient averaging rather than replicated tokens.""" - monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: ([[1, 2, 4, 8]], 16)) - model = TrainingReferenceFixture() - result = reference.training_reference(model, 'unused', batch_size=2, seq_len=32, world_size=3) - expected = torch.tensor(result['tokens']).float().mean().item() - assert model.checkpointing - assert len(result['tokens']) == 6 and all(len(row) == 32 for row in result['tokens']) - assert len(model.batches) == 3 and not torch.equal(model.batches[0], model.batches[1]) - assert result['world_size'] == 3 and result['batch_size'] == 2 and result['seq_len'] == 32 - assert result['loss'] == pytest.approx(sum(result['loss_per_rank']) / 3) - for probe in result['gradients'].values(): - assert probe['values'] == pytest.approx([expected] * len(probe['indices'])) - assert all(parameter.grad is None for parameter in model.parameters.values()) - - -def test_reference_preserves_exact_rank_microbatch_shape(reference, monkeypatch): - """Do not introduce BF16 batch-regrouping differences while checking distributed gradients.""" - monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: ([[1, 2, 4, 8]], 16)) - model = TrainingReferenceFixture() - result = reference.training_reference(model, 'unused', batch_size=3, seq_len=32, world_size=2) - assert [batch.shape[0] for batch in model.batches] == [3, 3] - assert all(batch.shape[1] == 32 for batch in model.batches) - assert torch.equal(torch.cat(model.batches), torch.tensor(result['tokens'])) - expected = torch.tensor(result['tokens']).float().mean().item() - assert result['reference_microbatch_size'] == 3 - assert result['loss'] == pytest.approx(expected * 24) - for probe in result['gradients'].values(): - assert probe['values'] == pytest.approx([expected] * len(probe['indices'])) - - -def test_targeted_reference_matches_full_backward_without_unneeded_gradients(reference, monkeypatch): - """Preserve full-model derivatives while avoiding storage for unsampled parameter gradients.""" - documents = [[1, 2, 4, 8]] - monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: (documents, 16)) - model = TrainingReferenceFixture() - ignored = torch.nn.Parameter(torch.tensor([2.0])) - model.parameters['model.layers.2.unprobed.weight'] = ignored - tokens = reference.packed_tokens(documents, 16, 32, 6) - expected = {} - for rank in range(2): - model.zero_grad(set_to_none=True) - inputs = torch.tensor(tokens[rank * 3:(rank + 1) * 3]) - model(input_ids=inputs, labels=inputs, use_cache=False).loss.backward() - for name, parameter in model.parameters.items(): - expected[name] = expected.get(name, torch.zeros_like(parameter)) + parameter.grad.detach() / 2 - model.zero_grad(set_to_none=True) - grad = Mock(wraps=torch.autograd.grad) - monkeypatch.setattr(torch.autograd, 'grad', grad) - result = reference.training_reference(model, 'unused', batch_size=3, seq_len=32, world_size=2) - assert grad.call_count == 2 - for call in grad.call_args_list: - assert all(parameter is not ignored for parameter in call[0][1]) - for name, probe in result['gradients'].items(): - assert probe['values'] == pytest.approx(expected[name].flatten()[probe['indices']].tolist()) - assert all(parameter.requires_grad and parameter.grad is None for parameter in model.parameters.values()) - - -def test_reference_does_not_retain_unused_model_outputs(reference, monkeypatch): - """Release returned vocabulary tensors before accumulating full-model gradients.""" - monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: ([[1, 2, 4, 8]], 16)) - - class OutputFixture(TrainingReferenceFixture): - def __call__(self, input_ids, labels, use_cache): - output = super().__call__(input_ids, labels, use_cache) - logits = torch.ones(8, 8) - self.logits_reference = weakref.ref(logits) - return SimpleNamespace(loss=output.loss, logits=logits) - - model = OutputFixture() - - def check_released(gradient): - assert model.logits_reference() is None - return gradient - - next(iter(model.parameters.values())).register_hook(check_released) - reference.training_reference(model, 'unused', batch_size=2, seq_len=32, world_size=2) - - -@pytest.mark.parametrize('batch_size,seq_len,world_size', [(0, 32, 1), (1, 16, 1), (1, 32, 0)]) -def test_training_reference_rejects_invalid_profile(reference, batch_size, seq_len, world_size): - """Invalid global-batch definitions must fail before any model work.""" - with pytest.raises(ValueError, match='reference profile'): - reference.training_reference(TrainingReferenceFixture(), 'unused', batch_size, seq_len, world_size) - - -@pytest.fixture -def loading_contract(reference, tmp_path, monkeypatch): - """Mock library boundaries while exercising all loader identity checks.""" - if sys.version_info < (3, 10): - pytest.skip('The standalone model runtime requires Python 3.10 or later.') - import importlib.metadata - from deepseek_v2_lite_utils import EXPECTED_CONFIG - - (tmp_path / 'config.json').write_text(json.dumps(dict(EXPECTED_CONFIG, model_type='deepseek_v2'))) - parameter = SimpleNamespace(numel=lambda: reference.PARAMETER_COUNT, requires_grad=True) - model = SimpleNamespace(parameters=lambda: [parameter]) - loading = {key: [] for key in ['missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs']} - loader = Mock(return_value=(model, loading)) - tokenizer = SimpleNamespace(encode=Mock(return_value=[1, 2]), eos_token_id=9) - tokenizer_loader = Mock(return_value=tokenizer) - monkeypatch.setitem( - sys.modules, 'transformers', - SimpleNamespace( - AutoModelForCausalLM=SimpleNamespace(from_pretrained=loader), - AutoTokenizer=SimpleNamespace(from_pretrained=tokenizer_loader), - ) - ) - version = importlib.metadata.version - monkeypatch.setattr( - importlib.metadata, 'version', lambda name: '4.46.3' if name == 'transformers' else version(name) - ) - monkeypatch.setattr(torch.cuda, 'is_available', lambda: True) - return SimpleNamespace( - path=tmp_path, - model=model, - parameter=parameter, - loading=loading, - loader=loader, - tokenizer=tokenizer, - tokenizer_loader=tokenizer_loader, - ) - - -def test_official_loader_contract(reference, loading_contract): - """Require local official-code loading and complete loading diagnostics.""" - item = loading_contract - assert reference.load_model(str(item.path), torch.bfloat16) is item.model - options = item.loader.call_args[1] - assert options['torch_dtype'] == torch.bfloat16 - assert options['local_files_only'] and options['trust_remote_code'] and options['use_safetensors'] - assert options['attn_implementation'] == 'eager' and options['output_loading_info'] - documents, eos = reference.fixed_documents(str(item.path)) - assert len(documents) == len(reference.FIXED_TEXTS) and eos == 9 - assert item.tokenizer_loader.call_args[1]['local_files_only'] - assert item.tokenizer.encode.call_count == len(reference.FIXED_TEXTS) - - -@pytest.mark.parametrize('field', ['missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs']) -def test_loader_diagnostics_cannot_be_ignored(reference, loading_contract, field): - """Partial or incompatible loading must fail before reference execution.""" - loading_contract.loading[field] = ['invalid checkpoint'] - with pytest.raises(RuntimeError, match='checkpoint loading'): - reference.load_model(str(loading_contract.path), torch.bfloat16) - - -@pytest.mark.parametrize('failure', ['count', 'frozen', 'gpu', 'version']) -def test_loader_rejects_wrong_model_or_runtime(reference, loading_contract, monkeypatch, failure): - """Do not replace full-model GPU verification with a smaller or unsupported runtime.""" - item = loading_contract - if failure == 'count': - item.parameter.numel = lambda: 1 - elif failure == 'frozen': - item.parameter.requires_grad = False - elif failure == 'gpu': - monkeypatch.setattr(torch.cuda, 'is_available', lambda: False) - else: - import importlib.metadata - monkeypatch.setattr(importlib.metadata, 'version', lambda name: '0.0') - with pytest.raises(RuntimeError): - reference.load_model(str(item.path), torch.bfloat16) - - -@pytest.mark.parametrize('mode', ['training', 'inference']) -def test_reference_entrypoint_uses_expected_dtype_and_teardown(reference, tmp_path, monkeypatch, mode): - """Exercise orchestration with fake model work, not GPU numerical acceptance.""" - model = Mock() - model.cuda.return_value = model - loader = Mock(return_value=model) - monkeypatch.setattr(reference, 'load_model', loader) - monkeypatch.setattr(reference, 'training_reference', Mock(return_value={'loss': 1.0})) - monkeypatch.setattr(reference, 'inference_reference', Mock(return_value={'comparisons': []})) - monkeypatch.setattr(torch.cuda, 'set_device', Mock()) - monkeypatch.setattr(torch.cuda, 'synchronize', Mock()) - cleanup = Mock() - monkeypatch.setattr(torch.cuda, 'empty_cache', cleanup) - monkeypatch.setattr(torch.backends.cuda.matmul, 'allow_tf32', False) - monkeypatch.setenv('TORCH_ALLOW_TF32_CUBLAS_OVERRIDE', '0') - requests = tmp_path / 'requests.json' - requests.write_text('[]') - output = tmp_path / 'report.json' - monkeypatch.setattr( - sys, 'argv', [ - 'reference', - '--checkpoint', - str(tmp_path), - '--mode', - mode, - '--requests', - str(requests), - '--output', - str(output), - ] - ) - reference.main() - report = json.loads(output.read_text()) - expected = torch.bfloat16 if mode == 'training' else torch.float32 - assert loader.call_args[0][1] == expected - assert report['reference_dtype'] == str(expected) - assert report['correctness_passed'] and report['teardown_complete'] and not report['tf32_allowed'] - cleanup.assert_called_once() diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_utils.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_utils.py deleted file mode 100644 index f6ff3756f..000000000 --- a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite_utils.py +++ /dev/null @@ -1,345 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -"""CPU-only tests for the standalone worker contract, without framework imports.""" - -import copy -import ctypes -import hashlib -import importlib.util -import math -import os -import signal -import sys -import time -from pathlib import Path -from types import SimpleNamespace -from unittest.mock import Mock - -import pytest - -WORKER_PATH = Path(__file__).resolve().parents[3] / 'superbench/benchmarks/model_benchmarks/deepseek_v2_lite_utils.py' -SPEC = importlib.util.spec_from_file_location('deepseek_v2_lite_utils_test', WORKER_PATH) -if SPEC is None or SPEC.loader is None: - raise RuntimeError('Cannot load the standalone worker utilities.') -utils = importlib.util.module_from_spec(SPEC) -SPEC.loader.exec_module(utils) - - -def test_checkpoint_identity(): - """Reject architecture proxies and quantization.""" - config = dict(utils.EXPECTED_CONFIG, model_type='deepseek_v2') - utils.validate_config(config) - config['hidden_size'] = 1024 - with pytest.raises(ValueError, match='hidden_size'): - utils.validate_config(config) - config['hidden_size'] = 2048 - config['quantization_config'] = {'quant_method': 'fp8'} - with pytest.raises(ValueError, match='quantized'): - utils.validate_config(config) - assert utils.WEIGHT_BYTES == 31413626576 - - -@pytest.mark.parametrize('field,value', [('seq_aux', False), ('aux_loss_alpha', 0.1), ('attention_dropout', 0.1)]) -def test_fixed_training_semantics_are_part_of_model_identity(field, value): - """Do not silently change the official auxiliary-loss or dropout configuration.""" - config = dict(utils.EXPECTED_CONFIG, model_type='deepseek_v2') - config[field] = value - with pytest.raises(ValueError, match=field): - utils.validate_config(config) - - -def test_packed_text_is_reproducible(): - """Pack actual token inputs with EOS separators, not padding or mock execution.""" - documents = [[1, 2], [3, 4, 5]] - expected = [[1, 2, 9, 3], [4, 5, 9, 1]] - assert utils.packed_tokens(documents, 9, 4, 2) == expected - assert utils.packed_tokens(documents, 9, 4, 2) == expected - assert utils.packed_tokens(documents, 9, 4, 2, offset=1) != expected - - -@pytest.mark.parametrize('documents,length,count', [([], 4, 1), ([[]], 4, 1), ([[True]], 4, 1), ([[1]], 1, 1)]) -def test_invalid_text_inputs(documents, length, count): - """Surface malformed inputs instead of returning an empty batch.""" - with pytest.raises(ValueError): - utils.packed_tokens(documents, 9, length, count) - - -def test_cold_cache_isolated(tmp_path, monkeypatch): - """Reject cache reuse without deleting shared contents.""" - shared = tmp_path / 'shared' - shared.mkdir() - sentinel = shared / 'keep' - sentinel.write_text('unrelated data') - monkeypatch.setenv('HF_HOME', str(shared)) - cache = tmp_path / 'cold' - utils.configure_cache(cache) - assert sentinel.read_text() == 'unrelated data' - assert utils.os.environ['HF_HOME'] == str(cache / 'hf') - assert utils.os.environ['HF_XET_CACHE'] == str(cache / 'xet') - (cache / 'present').touch() - with pytest.raises(ValueError, match='empty'): - utils.configure_cache(cache) - - -@pytest.mark.parametrize('values', [[math.nan], [math.inf], [-1], [0], [True], [], ['1']]) -def test_invalid_metric_series(values): - """Never accept NaNs, sentinels, incomplete samples or success-shaped defaults.""" - with pytest.raises(ValueError): - utils.numeric_series({'step_ms': values}, 'step_ms', 1) - - -def test_report_requires_correctness_and_teardown(): - """Require model identity, not just a successful process exit.""" - report = dict(utils.identity_report(), status='success', correctness_passed=True, teardown_complete=True) - utils.validate_identity(report) - incorrect = copy.deepcopy(report) - incorrect['parameter_count'] = 100 - with pytest.raises(ValueError, match='contract'): - utils.validate_identity(incorrect) - report['correctness_passed'] = False - with pytest.raises(ValueError, match='Correctness'): - utils.validate_identity(report) - - -@pytest.mark.parametrize('length', [1, 512, 209715200, 15706484224]) -def test_large_tensor_probe_indices(length): - """FP32-rounded endpoints must never index beyond a real full-model tensor.""" - indices = utils.uniform_indices(length) - assert len(indices) == 256 - assert indices[0] == 0 and indices[-1] == length - 1 - assert all(0 <= index < length for index in indices) - - -def test_atomic_json_rejects_nonfinite_values(tmp_path): - """A malformed report must not replace a complete report.""" - path = tmp_path / 'report.json' - utils.write_json(path, {'value': 1}) - with pytest.raises(ValueError): - utils.write_json(path, {'value': math.nan}) - assert utils.read_json(path) == {'value': 1} - path.write_text('{"value": NaN}') - with pytest.raises(ValueError, match='Nonfinite'): - utils.read_json(path) - - -def test_worker_failure_is_explicit(tmp_path): - """Reject nonzero exit codes even if the worker writes a result-like message.""" - with pytest.raises(RuntimeError, match='code 7'): - utils.run_worker([sys.executable, '-c', 'print("success"); raise SystemExit(7)'], tmp_path / 'worker.log', 5) - assert 'success' in (tmp_path / 'worker.log').read_text() - - -def test_timeout_reaps_worker(tmp_path): - """A timeout must terminate the created process rather than leave a worker.""" - pid_file = tmp_path / 'pid' - command = [ - sys.executable, - '-c', - 'import os,time; from pathlib import Path; Path({!r}).write_text(str(os.getpid())); time.sleep(60)'.format( - str(pid_file) - ), - ] - with pytest.raises(TimeoutError, match='deadline'): - utils.run_worker(command, tmp_path / 'worker.log', 1) - pid = int(pid_file.read_text()) - with pytest.raises(ProcessLookupError): - utils.os.kill(pid, 0) - - -def test_worker_argv_is_not_a_shell(tmp_path): - """Preserve argument boundaries rather than reinterpret shell metacharacters.""" - output = tmp_path / 'argv' - value = 'a=b; this is one value' - utils.run_worker( - [ - sys.executable, '-c', 'import sys; from pathlib import Path; Path(sys.argv[1]).write_text(sys.argv[2])', - str(output), value - ], tmp_path / 'worker.log', 5 - ) - assert output.read_text() == value - - -def test_success_with_live_child_is_rejected(tmp_path): - """A leader's exit code zero is insufficient when its child remains alive.""" - command = [ - sys.executable, - '-c', - 'import subprocess,sys; subprocess.Popen([sys.executable,"-c","import time; time.sleep(60)"])', - ] - with pytest.raises(RuntimeError, match='descendant processes'): - utils.run_worker(command, tmp_path / 'worker.log', 5) - - -@pytest.mark.parametrize('launcher_exits', [False, True]) -def test_separate_session_child_is_reaped(tmp_path, launcher_exits): - """Own escaped rank sessions even when their launcher exits or ignores termination.""" - pid_file = tmp_path / 'rank.pid' - rank = ( - 'import os,signal,time; from pathlib import Path; ' - 'signal.signal(signal.SIGTERM, signal.SIG_IGN); ' - 'Path({!r}).write_text(str(os.getpid())); time.sleep(60)' - ).format(str(pid_file)) - launcher = ( - 'import signal,subprocess,sys,time; from pathlib import Path; ' - 'signal.signal(signal.SIGTERM, signal.SIG_IGN); ' - 'subprocess.Popen([sys.executable, "-c", {!r}], start_new_session=True); ' - 'ready=Path({!r})\n' - 'while not ready.exists(): time.sleep(0.01)\n' - '{}' - ).format(rank, str(pid_file), 'sys.exit(0)' if launcher_exits else 'time.sleep(60)') - try: - expected = RuntimeError if launcher_exits else TimeoutError - with pytest.raises(expected): - utils.run_worker([sys.executable, '-c', launcher], tmp_path / 'worker.log', 5 if launcher_exits else 1) - pid = int(pid_file.read_text()) - with pytest.raises(ProcessLookupError): - os.kill(pid, 0) - finally: - if pid_file.exists(): - pid = int(pid_file.read_text()) - try: - os.kill(pid, signal.SIGKILL) - except ProcessLookupError: - pass - - -def test_worker_signal_does_not_kill_unrelated_process(tmp_path): - """Timeout cleanup must be scoped to the supervised job, not the controller's children.""" - unrelated = utils.subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)']) - try: - with pytest.raises(TimeoutError): - utils.run_worker([sys.executable, '-c', 'import time; time.sleep(60)'], tmp_path / 'worker.log', 0.2) - assert unrelated.poll() is None - finally: - unrelated.terminate() - unrelated.wait(timeout=5) - - -def test_controller_death_reaps_owned_worker(tmp_path): - """A killed controller must not leave its independently supervised job alive.""" - pid_file = tmp_path / 'worker.pid' - worker = ('import os,time; from pathlib import Path; ' - 'Path({!r}).write_text(str(os.getpid())); time.sleep(60)').format(str(pid_file)) - controller = ( - 'import sys; from pathlib import Path; sys.path.insert(0, {!r}); ' - 'from deepseek_v2_lite_utils import run_worker; ' - 'run_worker([sys.executable, "-c", {!r}], Path({!r}), 60)' - ).format(str(WORKER_PATH.parent), worker, str(tmp_path / 'worker.log')) - process = utils.subprocess.Popen([sys.executable, '-c', controller]) - try: - deadline = time.monotonic() + 5 - while not pid_file.exists() and time.monotonic() < deadline: - time.sleep(0.02) - assert pid_file.exists() - pid = int(pid_file.read_text()) - process.kill() - process.wait(timeout=5) - deadline = time.monotonic() + 15 - while time.monotonic() < deadline: - try: - os.kill(pid, 0) - except ProcessLookupError: - break - time.sleep(0.02) - else: - pytest.fail('The worker survived its controller.') - finally: - if process.poll() is None: - process.kill() - process.wait(timeout=5) - if pid_file.exists(): - try: - os.kill(int(pid_file.read_text()), signal.SIGKILL) - except ProcessLookupError: - pass - - -@pytest.fixture -def checkpoint_files(tmp_path, monkeypatch): - """Create small real files to test the checkpoint integrity contract.""" - root = tmp_path / 'checkpoint' - root.mkdir() - contents = b'CPU checkpoint integrity fixture' - shard = root / 'weights.safetensors' - shard.write_bytes(contents) - monkeypatch.setattr(utils, 'WEIGHT_FILES', { - shard.name: (len(contents), hashlib.sha256(contents).hexdigest()), - }) - utils.write_json(root / 'config.json', dict(utils.EXPECTED_CONFIG, model_type='deepseek_v2')) - utils.write_json(root / 'model.safetensors.index.json', {'weight_map': {'fixture.weight': shard.name}}) - return root, shard - - -def test_checkpoint_files_are_verified(checkpoint_files): - """Check file sizes, index membership and SHA256 without claiming model execution.""" - root, _ = checkpoint_files - utils.verify_checkpoint(root) - - -@pytest.mark.parametrize('failure', ['missing', 'size', 'hash', 'index']) -def test_invalid_checkpoint_files_fail(checkpoint_files, failure): - """Corrupted, missing or misindexed shards must never become a valid checkpoint.""" - root, shard = checkpoint_files - if failure == 'missing': - shard.unlink() - elif failure == 'size': - shard.write_bytes(b'short') - elif failure == 'hash': - shard.write_bytes(b'x' * shard.stat().st_size) - else: - utils.write_json(root / 'model.safetensors.index.json', {'weight_map': {'fixture.weight': 'other'}}) - with pytest.raises(ValueError): - utils.verify_checkpoint(root) - - -def test_download_uses_pinned_public_identity_and_then_verifies(checkpoint_files, monkeypatch): - """Disable implicit credentials and require the downloaded shard contract.""" - root, shard = checkpoint_files - download = Mock() - monkeypatch.setitem(sys.modules, 'huggingface_hub', SimpleNamespace(snapshot_download=download)) - assert utils.download_checkpoint(root.parent) == root - arguments = download.call_args[1] - assert arguments['repo_id'] == utils.MODEL_ID - assert arguments['revision'] == utils.REVISION - assert arguments['token'] is False - assert arguments['local_dir'] == str(root) - assert shard.name in arguments['allow_patterns'] - - -@pytest.mark.parametrize('length,count', [(0, 2), (1, 1)]) -def test_invalid_probe_dimensions_fail(length, count): - """Reject undefined probe endpoints instead of silently selecting positions.""" - with pytest.raises(ValueError, match='tensor length'): - utils.uniform_indices(length, count) - - -@pytest.mark.parametrize('timeout', [0, -1, float('nan')]) -def test_invalid_worker_deadline_fails_before_launch(tmp_path, timeout): - """A nonfinite or expired budget must not start a worker.""" - with pytest.raises(TimeoutError): - utils.run_worker([sys.executable, '-c', 'pass'], tmp_path / 'worker.log', timeout) - - -def test_empty_worker_command_fails(tmp_path): - """Do not launch a supervisor with no defined workload.""" - with pytest.raises(ValueError, match='command'): - utils.run_worker([], tmp_path / 'worker.log', 1) - - -def test_worker_interrupt_is_failure(): - """A termination request must unwind the worker's normal success path.""" - with pytest.raises(TimeoutError, match='interrupted'): - utils.interrupt_worker(signal.SIGTERM, None) - - -def test_supervisor_requires_kernel_ownership_support(monkeypatch): - """Fail before spawning when kernel ownership setup is unavailable.""" - monkeypatch.setattr(utils.signal, 'signal', Mock()) - monkeypatch.setattr(ctypes, 'CDLL', lambda *args, **kwargs: SimpleNamespace(prctl=lambda *args: -1)) - monkeypatch.setattr(ctypes, 'get_errno', lambda: 13) - spawn = Mock() - monkeypatch.setattr(utils.subprocess, 'Popen', spawn) - with pytest.raises(OSError): - utils.supervise_worker([sys.executable, '-c', 'pass'], 1, os.getppid()) - spawn.assert_not_called() diff --git a/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py b/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py index 6a6f000e2..be83f6ad1 100644 --- a/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py +++ b/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py @@ -1,9 +1,15 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -"""CPU adapter tests for the standalone complete-generation profile.""" +"""CPU tests for the DeepSeek-V2-Lite inference benchmark: adapter, vLLM worker and H100 numerical policy.""" +import hashlib +import inspect +import json +import math +import os import subprocess +import sys from pathlib import Path from types import SimpleNamespace from unittest.mock import Mock @@ -11,11 +17,14 @@ import pytest from superbench.benchmarks import BenchmarkType, ReturnCode -from superbench.benchmarks.model_benchmarks import deepseek_v2_lite_cache as cache_cleanup from superbench.benchmarks.model_benchmarks import vllm_deepseek_v2_lite as adapter -from superbench.benchmarks.model_benchmarks.deepseek_v2_lite_utils import identity_report, write_json +from superbench.benchmarks.model_benchmarks.deepseek_v2_lite import ( + cache as cache_cleanup, inference_worker, numerics as numerics_module +) +from superbench.benchmarks.model_benchmarks.deepseek_v2_lite.utils import identity_report, write_json +# Adapter. @pytest.fixture def benchmark(tmp_path, monkeypatch): """Use one local replica and an isolated output root.""" @@ -27,8 +36,10 @@ def benchmark(tmp_path, monkeypatch): ) -def successful_worker(command, log, timeout): +def successful_worker(command, log, timeout, env): """Provide validated-shaped fixtures, not actual GPU measurements.""" + assert command[1:3] == ['-m', 'deepseek_v2_lite.inference_worker'] + assert env['PYTHONPATH'].split(os.pathsep)[0] == str(Path(adapter.__file__).resolve().parent) output = Path(command[command.index('--output') + 1]) report = dict( identity_report(), @@ -98,8 +109,8 @@ def test_parameters_render_in_help(): ) def test_reject_invalid_generation_reports(benchmark, monkeypatch, field, value): """Validate output shapes and thresholds instead of accepting exit code zero.""" - def invalid_worker(command, log, timeout): - successful_worker(command, log, timeout) + def invalid_worker(command, log, timeout, env): + successful_worker(command, log, timeout, env) output = Path(command[command.index('--output') + 1]) report = adapter.read_json(output) report[field] = value @@ -112,7 +123,7 @@ def invalid_worker(command, log, timeout): def test_deadline_failure(benchmark, monkeypatch): """A watchdog exit cannot be reported as a successful under-hour run.""" - def timeout(command, log, seconds): + def timeout(command, log, seconds, env): raise TimeoutError('whole job deadline') monkeypatch.setattr(adapter, 'run_worker', timeout) @@ -125,7 +136,7 @@ def test_model_cache_is_removed_after_every_run(benchmark, monkeypatch, outcome) """Delete the per-run checkpoint cache on every exit path while keeping reports and logs.""" jobs = [] - def worker(command, log, timeout): + def worker(command, log, timeout, env): cache = Path(command[command.index('--cache_dir') + 1]) (cache / 'checkpoint').mkdir(parents=True) (cache / 'checkpoint' / 'model-00001-of-000004.safetensors').write_bytes(b'weights') @@ -135,7 +146,7 @@ def worker(command, log, timeout): raise RuntimeError('worker failed') if outcome == 'timeout': raise TimeoutError('whole job deadline') - successful_worker(command, log, timeout) + successful_worker(command, log, timeout, env) monkeypatch.setattr(adapter, 'run_worker', worker) assert benchmark.run() is (outcome == 'success') @@ -144,57 +155,16 @@ def worker(command, log, timeout): assert (jobs[0] / 'report.json').is_file() is (outcome == 'success') -@pytest.mark.parametrize( - 'failure', - [PermissionError('read-only cache'), - subprocess.CalledProcessError(1, ['cleanup'], output='read-only cache')] -) -def test_cache_removal_failure_keeps_a_valid_measurement(benchmark, monkeypatch, failure): - """Log a cleanup error without discarding metrics that were already validated.""" - caches = [] - log_error = Mock() - - def worker(command, log, timeout): - cache = Path(command[command.index('--cache_dir') + 1]) - cache.mkdir(parents=True) - caches.append(cache) - successful_worker(command, log, timeout) - - monkeypatch.setattr(adapter, 'run_worker', worker) - monkeypatch.setattr(cache_cleanup.subprocess, 'run', Mock(side_effect=failure)) - monkeypatch.setattr(adapter.logger, 'error', log_error) - assert benchmark.run() - assert benchmark.return_code == ReturnCode.SUCCESS - assert caches[0].is_dir() - log_error.assert_called_once() - assert 'read-only cache' in str(log_error.call_args[0][-1]) - - -def test_sigterm_during_cache_removal_still_reports_timeout(benchmark, monkeypatch): - """A runner timeout during cleanup must not be reported as a completed run.""" - def worker(command, log, timeout): - Path(command[command.index('--cache_dir') + 1]).mkdir(parents=True) - successful_worker(command, log, timeout) - - cleanup = Mock(side_effect=TimeoutError('Killed by SIGTERM or timeout!')) - monkeypatch.setattr(adapter, 'run_worker', worker) - monkeypatch.setattr(cache_cleanup.subprocess, 'run', cleanup) - assert not benchmark.run() - assert benchmark.return_code == ReturnCode.KILLED_BY_TIMEOUT - assert 'end_to_end_seconds' not in benchmark.result - assert cleanup.call_count == 2 - - @pytest.mark.parametrize('cleanup_seconds', [7, 50, 70]) def test_cache_cleanup_counts_toward_the_job_deadline(benchmark, monkeypatch, cleanup_seconds): """Include cleanup in elapsed time and reject the exact deadline as well as an overrun.""" clock = [100.0] run_cleanup = subprocess.run - def worker(command, log, timeout): + def worker(command, log, timeout, env): assert timeout == 40 Path(command[command.index('--cache_dir') + 1]).mkdir(parents=True) - successful_worker(command, log, timeout) + successful_worker(command, log, timeout, env) clock[0] += 10 def cleanup(command, **kwargs): @@ -219,36 +189,6 @@ def cleanup(command, **kwargs): assert 'bf16_inference_output_tokens_per_second' not in benchmark.result -def test_cleanup_after_the_deadline_uses_the_failure_grace(benchmark, monkeypatch): - """Fail an overrun job, then still remove its cache within the bounded failure grace.""" - clock = [100.0] - timeouts = [] - caches = [] - run_cleanup = subprocess.run - - def worker(command, log, timeout): - cache = Path(command[command.index('--cache_dir') + 1]) - cache.mkdir(parents=True) - caches.append(cache) - successful_worker(command, log, timeout) - clock[0] += 60 - - def cleanup(command, **kwargs): - timeouts.append(kwargs['timeout']) - return run_cleanup(command, **kwargs) - - fake_time = SimpleNamespace(monotonic=lambda: clock[0]) - monkeypatch.setattr(adapter, 'time', fake_time) - monkeypatch.setattr(cache_cleanup, 'time', fake_time) - monkeypatch.setattr(adapter, 'run_worker', worker) - monkeypatch.setattr(cache_cleanup.subprocess, 'run', cleanup) - assert not benchmark.run() - assert benchmark.return_code == ReturnCode.KILLED_BY_TIMEOUT - assert 'end_to_end_seconds' not in benchmark.result - assert timeouts == [cache_cleanup.FAILURE_CLEANUP_GRACE_SECONDS] - assert not caches[0].exists() - - @pytest.mark.parametrize( 'failure,code', [ (RuntimeError('worker failed'), ReturnCode.RUNTIME_EXCEPTION_ERROR), @@ -259,7 +199,7 @@ def test_unfinished_failure_cleanup_keeps_the_original_error(benchmark, monkeypa """Report the worker failure rather than a later cleanup timeout, and log both.""" log_error = Mock() - def worker(command, log, timeout): + def worker(command, log, timeout, env): Path(command[command.index('--cache_dir') + 1]).mkdir(parents=True) raise failure @@ -290,7 +230,7 @@ def test_h100_adapter_requires_matching_numerical_evidence(tmp_path, monkeypatch validator = Mock(side_effect=ValueError('bad reference') if fault == 'reference' else None) monkeypatch.setattr(adapter.numerics, 'validate_reference_result', validator) - def worker(command, log, timeout): + def worker(command, log, timeout, env): assert command[command.index('--numerical_policy') + 1] == adapter.numerics.POLICY report = dict( identity_report(), @@ -327,3 +267,889 @@ def worker(command, log, timeout): validator.assert_called_once_with({'positive_positions': 3216, 'negative_positions': 6438}) else: assert instance.return_code == ReturnCode.RUNTIME_EXCEPTION_ERROR + + +# vLLM worker. +@pytest.fixture +def worker(): + """Return the worker, which imports vLLM and CUDA only inside its functions.""" + return inference_worker + + +def response(tokens=(7, 8)): + """Construct engine-response fixtures without simulating GPU success.""" + return SimpleNamespace( + finished=True, + prompt_token_ids=[1, 2, 3], + outputs=[ + SimpleNamespace( + token_ids=list(tokens), + finish_reason='length', + logprobs=[ + {key: SimpleNamespace(logprob=-0.5 if key == token else -2.0) + for key in set(range(20)) | {token}} for token in tokens + ] + ) + ], + metrics=SimpleNamespace( + is_corrupted=False, + num_generation_tokens=len(tokens), + scheduled_ts=10.0, + first_token_ts=10.25, + last_token_ts=10.5, + first_token_latency=0.4 + ), + ) + + +def test_actual_output_tokens_not_maximum(worker): + """Count emitted token IDs instead of treating max_tokens as completed work.""" + result = worker.output_record(response(), 64, [1, 2, 3], True) + assert result['token_ids'] == [7, 8] + assert len(result['token_ids']) == 2 + assert result['logprobs'][0]['7'] == result['logprobs'][1]['8'] == -0.5 + assert all(len(row) == 20 for row in result['logprobs']) + + +@pytest.mark.parametrize('tokens', [(), (1, 2, 3, 4, 5)]) +def test_invalid_token_counts(worker, tokens): + """Reject empty or over-limit outputs rather than inventing throughput.""" + with pytest.raises(RuntimeError, match='count'): + worker.output_record(response(tokens), 4, [1, 2, 3]) + + +@pytest.mark.parametrize('field,value', [('finished', False), ('prompt_token_ids', [])]) +def test_incomplete_requests(worker, field, value): + """Failed request batches do not count as complete model execution.""" + output = response() + setattr(output, field, value) + with pytest.raises(RuntimeError, match='unfinished'): + worker.output_record(output, 64, [1, 2, 3]) + + +def test_output_must_match_submitted_prompt(worker): + """Do not validate a correct response against a different request's tokens.""" + with pytest.raises(RuntimeError, match='different prompt'): + worker.output_record(response(), 64, [3, 2, 1]) + + +def test_missing_logprobs(worker): + """Missing numerical-reference evidence must fail explicitly.""" + output = response() + output.outputs[0].logprobs = None + with pytest.raises(RuntimeError, match='probabilities'): + worker.output_record(output, 64, [1, 2, 3], True) + + +@pytest.mark.parametrize( + 'field,value', [ + ('is_corrupted', True), ('num_generation_tokens', 64), ('first_token_ts', 0.0), + ('first_token_latency', float('nan')), ('last_token_ts', 10.0) + ] +) +def test_invalid_statistics(worker, field, value): + """Never substitute zero/default durations or hide corrupted logits.""" + output = response() + setattr(output.metrics, field, value) + with pytest.raises(RuntimeError): + worker.request_times(output) + + +def test_measured_generation_excludes_warmup_and_counts_actual_tokens(worker, monkeypatch): + """Exclude distinct warmup timings and retain mixed EOS/multi-token measurements.""" + monkeypatch.setitem(sys.modules, 'torch', SimpleNamespace(cuda=SimpleNamespace(synchronize=lambda: None))) + monkeypatch.setitem(sys.modules, 'vllm', SimpleNamespace(SamplingParams=SimpleNamespace)) + clock = iter([0.0, 0.1, 1.0, 1.2, 2.0, 2.3]) + monkeypatch.setattr(worker.time, 'monotonic', lambda: next(clock)) + batches = iter( + [ + [(1, 0.05, 0.06, 0), (4, 0.075, 0.085, 0.015)], + [(1, 0.01, 0.015, 0), (3, 0.02, 0.025, 0.12)], + [(2, 0.03, 0.035, 0.08), (1, 0.04, 0.045, 0)], + ] + ) + submitted = [] + monkeypatch.setattr(worker.time, 'time', lambda: 1000.0 + 100 * len(submitted)) + + class Engine: + def generate(self, prompts, parameters, use_tqdm): + submitted.append(prompts) + outputs = [] + for prompt, (count, prefill, ttft, decode) in zip(prompts, next(batches)): + output = response((99, ) if count == 1 else tuple(range(7, 7 + count))) + output.prompt_token_ids = prompt['prompt_token_ids'] + output.metrics.first_token_ts = output.metrics.scheduled_ts + prefill + output.metrics.first_token_latency = ttft + output.metrics.last_token_ts = output.metrics.first_token_ts + decode + if count == 1: + output.outputs[0].finish_reason = 'stop' + outputs.append(output) + return outputs + + args = SimpleNamespace(num_warmup=1, num_steps=2, seq_len=32, batch_size=2, max_new_tokens=4) + report = worker.measured_generation(Engine(), [[1, 2, 3], [4, 5]], 99, args) + assert len(submitted) == 3 + assert report['step_ms'] == pytest.approx([200, 300]) + assert report['request_count'] == 4 + assert report['input_token_counts'] == [32, 32, 32, 32] + assert report['output_token_counts'] == [1, 3, 2, 1] + assert report['request_prefill_ms'] == pytest.approx([10, 20, 30, 40]) + assert report['ttft_ms'] == pytest.approx([15, 25, 35, 45]) + assert report['decode_tpot_ms'] == pytest.approx([60, 80]) + assert report['measurement_start_unix_seconds'] == 1100 + assert report['measurement_end_unix_seconds'] == 1300 + + +def test_measured_generation_rejects_missing_requests(worker, monkeypatch): + """A partial generation batch cannot become a valid throughput sample.""" + monkeypatch.setitem(sys.modules, 'torch', SimpleNamespace(cuda=SimpleNamespace(synchronize=lambda: None))) + monkeypatch.setitem(sys.modules, 'vllm', SimpleNamespace(SamplingParams=SimpleNamespace)) + engine = SimpleNamespace(generate=lambda *args, **kwargs: []) + args = SimpleNamespace(num_warmup=0, num_steps=1, seq_len=32, batch_size=2, max_new_tokens=4) + with pytest.raises(RuntimeError, match='fewer requests'): + worker.measured_generation(engine, [[1, 2, 3]], 99, args) + + +@pytest.fixture +def main_driver(worker, tmp_path, monkeypatch): + """Exercise the full worker's control flow without real vLLM or GPU execution.""" + if sys.version_info < (3, 10): + pytest.skip('The standalone inference runtime requires Python 3.10 or later.') + import importlib.metadata + torch = pytest.importorskip('torch') + + version = importlib.metadata.version + monkeypatch.setattr(importlib.metadata, 'version', lambda name: '0.31.0' if name == 'vllm' else version(name)) + for variable in [ + 'TORCH_ALLOW_TF32_CUBLAS_OVERRIDE', 'NVIDIA_TF32_OVERRIDE', 'VLLM_FLOAT32_MATMUL_PRECISION', + 'TRITON_F32_DEFAULT', 'VLLM_RAISE_ON_LOGIT_NANS', 'VLLM_BATCH_INVARIANT', 'VLLM_MLA_DISABLE' + ]: + monkeypatch.setenv(variable, 'test-original') + monkeypatch.setattr(worker.signal, 'signal', Mock()) + monkeypatch.setattr(worker, 'configure_cache', Mock()) + download = Mock(return_value=tmp_path / 'checkpoint') + monkeypatch.setattr(worker, 'download_checkpoint', download) + monkeypatch.setattr(torch.cuda, 'is_available', lambda: True) + monkeypatch.setattr(torch.cuda, 'set_device', Mock()) + monkeypatch.setattr(torch.cuda, 'synchronize', Mock()) + monkeypatch.setattr(torch.cuda, 'empty_cache', Mock()) + monkeypatch.setattr(torch.cuda, 'get_device_name', lambda index: 'CPU orchestration fixture') + shutdown = Mock() + config = SimpleNamespace(dtype=torch.bfloat16, quantization=None) + tokenizer = SimpleNamespace(encode=lambda *args, **kwargs: [1, 2, 3], eos_token_id=99) + + def generate(prompts, parameters, use_tqdm): + outputs = [] + stop = hasattr(parameters, 'allowed_token_ids') + tokens = parameters.allowed_token_ids if stop else list(range(7, 7 + parameters.max_tokens)) + for prompt in prompts: + output = response(tuple(tokens)) + output.prompt_token_ids = prompt['prompt_token_ids'] + if stop: + output.outputs[0].finish_reason = 'stop' + output.metrics.last_token_ts = output.metrics.first_token_ts + outputs.append(output) + return outputs + + engine = SimpleNamespace( + llm_engine=SimpleNamespace(model_config=config, engine_core=SimpleNamespace(shutdown=shutdown)), + get_tokenizer=lambda: tokenizer, + generate=generate, + ) + factory = Mock(return_value=engine) + monkeypatch.setitem(sys.modules, 'vllm', SimpleNamespace(LLM=factory, SamplingParams=SimpleNamespace)) + + def reference(command, log, timeout): + assert timeout > 0 + assert shutdown.called + output = Path(command[command.index('--output') + 1]) + worker.write_json(output, {'correctness_passed': True, 'teardown_complete': True}) + + oracle = Mock(side_effect=reference) + monkeypatch.setattr(worker, 'run_worker', oracle) + output = tmp_path / 'report.json' + argv = [ + 'worker', + '--cache_dir', + str(tmp_path / 'cache'), + '--output', + str(output), + '--reference_python', + 'reference-python', + '--batch_size', + '2', + '--seq_len', + '64', + '--num_warmup', + '1', + '--num_steps', + '2', + '--max_new_tokens', + '4', + '--duration', + '60', + ] + monkeypatch.setattr(sys, 'argv', argv) + return SimpleNamespace( + output=output, + argv=argv, + factory=factory, + engine=engine, + config=config, + shutdown=shutdown, + oracle=oracle, + download=download, + torch=torch, + ) + + +def test_inference_main_keeps_precision_counts_and_reference_lifecycle(worker, main_driver): + """Check the selected policies and report only after shutdown and reference success.""" + state = main_driver + worker.main() + options = state.factory.call_args[1] + assert options['dtype'] == 'bfloat16' and options['quantization'] is None + assert options['hf_overrides'] == {'moe_router_dtype': 'float32'} + assert options['max_model_len'] == 68 and options['max_num_seqs'] == 2 + report = json.loads(state.output.read_text()) + assert report['status'] == 'success' and report['correctness_passed'] and report['teardown_complete'] + assert report['request_count'] == 4 and report['output_token_counts'] == [4] * 4 + assert report['router_dtype'] == 'float32' and report['float32_matmul_precision'] == 'highest' + assert report['numerical_policy'] == 'strict_fp32' and report['batch_invariant'] is False + state.shutdown.assert_called_once_with(timeout=10) + state.oracle.assert_called_once() + + +def test_corrupted_measured_generation_cannot_publish_success(worker, main_driver, monkeypatch): + """Corruption in unscored measured requests must prevent result publication.""" + generate = main_driver.engine.generate + + def corrupted_generation(*args, **kwargs): + outputs = generate(*args, **kwargs) + for output in outputs: + output.metrics.is_corrupted = True + return outputs + + monkeypatch.setattr(main_driver.engine, 'generate', corrupted_generation) + with pytest.raises(RuntimeError, match='logits were corrupted'): + worker.main() + main_driver.shutdown.assert_called_once() + main_driver.oracle.assert_not_called() + assert not main_driver.output.exists() + + +def test_engine_error_still_shuts_down(worker, main_driver, monkeypatch): + """Generation failure cannot leave the engine alive or produce performance success.""" + monkeypatch.setattr(main_driver.engine, 'generate', Mock(side_effect=RuntimeError('generation failed'))) + with pytest.raises(RuntimeError, match='generation failed'): + worker.main() + main_driver.shutdown.assert_called_once() + main_driver.oracle.assert_not_called() + assert not main_driver.output.exists() + + +def test_failed_reference_is_not_success(worker, main_driver): + """A numerically rejected generation run must not publish a success report.""" + main_driver.oracle.side_effect = RuntimeError('numerical gate failed') + with pytest.raises(RuntimeError, match='numerical gate'): + worker.main() + main_driver.shutdown.assert_called_once() + assert not main_driver.output.exists() + + +def test_wrong_engine_precision_is_rejected(worker, main_driver): + """Do not silently replace the BF16 performance workload with another precision.""" + main_driver.config.dtype = main_driver.torch.float32 + with pytest.raises(RuntimeError, match='unquantized BF16'): + worker.main() + main_driver.shutdown.assert_called_once() + assert not main_driver.output.exists() + + +def test_unsupported_engine_version_fails_before_download(worker, main_driver, monkeypatch): + """Version-specific timing and shutdown contracts must not silently drift.""" + import importlib.metadata + version = importlib.metadata.version + monkeypatch.setattr(importlib.metadata, 'version', lambda name: '0.32.0' if name == 'vllm' else version(name)) + with pytest.raises(RuntimeError, match='pinned vLLM'): + worker.main() + main_driver.download.assert_not_called() + + +def test_inference_does_not_fall_back_to_cpu(worker, main_driver, monkeypatch): + """Unavailable GPU execution is an explicit failure, not a replacement benchmark.""" + monkeypatch.setattr(main_driver.torch.cuda, 'is_available', lambda: False) + with pytest.raises(RuntimeError, match='GPU unavailable'): + worker.main() + main_driver.download.assert_not_called() + + +@pytest.mark.parametrize( + 'override', [ + ['--batch_size', '0'], + ['--seq_len', '16'], + ['--num_steps', '0'], + ['--num_warmup', '-1'], + ['--max_new_tokens', '3'], + ['--gpu_memory_utilization', 'nan'], + ['--duration', '3600'], + ] +) +def test_inference_preflight_rejects_invalid_profile(worker, main_driver, monkeypatch, override): + """Invalid generation parameters must fail before download or engine creation.""" + monkeypatch.setattr(sys, 'argv', main_driver.argv + override) + with pytest.raises(ValueError): + worker.main() + main_driver.download.assert_not_called() + main_driver.factory.assert_not_called() + + +def h100_arguments(worker, main_driver): + """Select the frozen shape without changing the existing small fixture's defaults.""" + arguments = main_driver.argv + ['--numerical_policy', worker.numerics.POLICY] + for key, value in worker.numerics.PROFILE.items(): + arguments.extend(['--' + key, str(value)]) + return arguments + + +def test_h100_policy_uses_pinned_engine_settings_and_separate_reference(worker, main_driver, monkeypatch): + """Wire the explicit policy without replacing the measured BF16 model.""" + monkeypatch.setattr(sys, 'argv', h100_arguments(worker, main_driver)) + expected_gpu = worker.numerics.load_contract()['calibrated_contract']['runtime_identity']['gpu_name'] + monkeypatch.setattr(main_driver.torch.cuda, 'get_device_name', lambda index: expected_gpu) + main_driver.config.use_mla = True + validation = Mock() + monkeypatch.setattr(worker.numerics, 'validate_reference_result', validation) + worker.main() + report = json.loads(main_driver.output.read_text()) + assert report['numerical_policy'] == worker.numerics.POLICY and report['batch_invariant'] is True + assert main_driver.factory.call_args.kwargs['dtype'] == 'bfloat16' + command = main_driver.oracle.call_args.args[0] + assert command[1:3] == ['-m', 'deepseek_v2_lite.numerics'] and '--mode' not in command + assert len(json.loads((main_driver.output.parent / 'reference-requests.json').read_text())) == 84 + validation.assert_called_once_with(report['reference']) + assert worker.os.environ['VLLM_BATCH_INVARIANT'] == '1' + assert worker.os.environ['VLLM_MLA_DISABLE'] == '0' + main_driver.shutdown.assert_called_once() + + +def test_h100_policy_rejects_another_gpu_before_download(worker, main_driver, monkeypatch): + """A qualified H100 policy cannot be silently reused on other hardware.""" + monkeypatch.setattr(sys, 'argv', h100_arguments(worker, main_driver)) + with pytest.raises(ValueError, match='qualified H100 hardware'): + worker.main() + main_driver.download.assert_not_called() + + +# H100 numerical policy. +@pytest.fixture +def numerics(): + """Return the numerical policy, which imports no engine at load time.""" + return numerics_module + + +def budgets(): + """Use deliberately small synthetic bounds for arithmetic controls.""" + return { + 'max_probability_error': 0.02, + 'relative_probability_mass_error': 0.03, + 'normalized_logprob_error': 0.5, + } + + +@pytest.fixture +def policy_file(numerics, tmp_path, monkeypatch): + """Create qualified-shaped test evidence without claiming GPU execution.""" + monkeypatch.setattr(numerics, '__file__', str(tmp_path / 'numerics.py')) + path = tmp_path / 'h100_bf16_v6.json' + candidate = { + 'method': numerics.METHOD, + 'reference_only': True, + 'input_matched_limit_rule': numerics.LIMIT_RULE, + 'qualification_offsets': list(numerics.OFFSETS), + 'profile': {key: numerics.PROFILE[key] + for key in ('batch_size', 'seq_len', 'max_new_tokens')}, + 'qualification_stream': {key: numerics.PROFILE[key] + for key in ('num_warmup', 'num_steps')}, + } + candidate['frozen_limits_sha256'] = numerics.canonical_hash(candidate) + contract = { + 'status': 'qualified', + 'calibrated_contract': candidate, + 'qualification': [{ + 'profile_offset': offset + } for offset in numerics.OFFSETS], + 'reference_validation': { + 'non_anchor_comparisons': 1 + }, + } + + def save(): + path.write_text(json.dumps(contract)) + monkeypatch.setattr(numerics, 'CONTRACT_SHA256', hashlib.sha256(path.read_bytes()).hexdigest()) + + save() + return SimpleNamespace(path=path, contract=contract, candidate=candidate, save=save) + + +def test_frozen_profile_is_explicit_and_legacy_policy_is_unchanged(numerics): + """Do not apply one H100 qualification to other shapes or the default policy.""" + numerics.validate_profile(SimpleNamespace(numerical_policy='strict_fp32', batch_size=1)) + args = SimpleNamespace(numerical_policy=numerics.POLICY, **numerics.PROFILE) + numerics.validate_profile(args) + args.num_steps -= 1 + with pytest.raises(ValueError, match='complete frozen'): + numerics.validate_profile(args) + with pytest.raises(ValueError, match='Unknown'): + numerics.validate_profile(SimpleNamespace(numerical_policy='other')) + + +def test_contract_is_bound_to_exact_file_bytes(numerics, policy_file): + """Even a semantically equivalent substituted policy requires a new identity.""" + assert numerics.load_contract() == policy_file.contract + policy_file.path.write_text(policy_file.path.read_text() + '\n') + with pytest.raises(ValueError, match='changed'): + numerics.load_contract() + + +@pytest.mark.parametrize('fault', ['status', 'method', 'shape', 'stream', 'offsets', 'evidence', 'anchor-only', 'hash']) +def test_contract_rejects_incomplete_qualification(numerics, policy_file, fault): + """Validate semantics as well as a matching artifact digest.""" + candidate, contract = policy_file.candidate, policy_file.contract + if fault == 'status': + contract['status'] = 'candidate' + elif fault == 'method': + candidate['method'] = 'unqualified-method' + elif fault == 'shape': + candidate['profile']['batch_size'] = 1 + elif fault == 'stream': + candidate['qualification_stream']['num_steps'] = 1 + elif fault == 'offsets': + candidate['qualification_offsets'].pop() + elif fault == 'evidence': + contract['qualification'].pop() + elif fault == 'anchor-only': + contract['reference_validation']['non_anchor_comparisons'] = 0 + else: + candidate['frozen_limits_sha256'] = 'changed' + if fault != 'hash': + candidate['frozen_limits_sha256'] = numerics.canonical_hash( + {key: value + for key, value in candidate.items() if key != 'frozen_limits_sha256'} + ) + policy_file.save() + with pytest.raises(ValueError, match='qualification'): + numerics.load_contract() + + +@pytest.mark.parametrize( + 'expected,actual', [ + ([], []), + ([-1.0], []), + ([float('nan')], [-1.0]), + ([-1.0], [float('inf')]), + ([-1.0], [True]), + ([-1.0], [0.1]), + ([-1000.0], [-1000.0]), + ([0.0, 0.0], [0.0, 0.0]), + ] +) +def test_invalid_probability_data_is_rejected(numerics, expected, actual): + """Reject malformed, nonfinite and unnormalized probabilities explicitly.""" + with pytest.raises(ValueError): + numerics.probability_errors(expected, actual) + + +def test_input_matched_limits_are_reference_only(numerics): + """Keep calibration unchanged and fail if uncertainty admits half normalization.""" + calibrated = budgets() + original = dict(calibrated) + reference = {metric: 0.01 for metric in numerics.METRICS} + assert numerics.input_matched_limits(calibrated, reference) == { + metric: original[metric] + reference[metric] + for metric in numerics.METRICS + } + assert calibrated == original + reference['relative_probability_mass_error'] = 0.5 + with pytest.raises(ValueError, match='half-normalization'): + numerics.input_matched_limits(calibrated, reference) + reference['relative_probability_mass_error'] = float('nan') + with pytest.raises(ValueError, match='input-matched'): + numerics.input_matched_limits(calibrated, reference) + reference['relative_probability_mass_error'] = 0 + calibrated['normalized_logprob_error'] = 0 + with pytest.raises(ValueError, match='budget'): + numerics.input_matched_limits(calibrated, reference) + + +def test_greedy_rules_and_invalid_bounds(numerics): + """Near ties do not waive reported-greedy or probability-gap checks.""" + expected = {0: math.log(0.9), 1: math.log(0.1)} + result = numerics.score_probabilities(expected, expected, 1, 0, budgets()) + assert not result['accepted'] and not result['greedy_match'] + assert 'reported token is not greedy' in result['failures'] + assert 'greedy choice exceeds calibrated uncertainty' in result['failures'] + assert numerics.score_probabilities(expected, expected, 0, 0, budgets())['accepted'] + with pytest.raises(ValueError, match='Incomplete'): + numerics.score_probabilities(expected, {0: expected[0]}, 0, 0, budgets()) + limits = budgets() + limits['normalized_logprob_error'] = float('inf') + with pytest.raises(ValueError, match='bound'): + numerics.score_probabilities(expected, expected, 0, 0, limits) + + +def test_top_k_shape_bounds_and_tail_fault(numerics): + """A tiny tail still has to reject the fixed temperature fault.""" + torch = pytest.importorskip('torch') + logits = torch.full((32, ), -40.0) + logits[0] = 0 + expected = logits.log_softmax(-1) + wrong = (expected / 2).log_softmax(-1) + ids = wrong.topk(20).indices.tolist() + observed = {str(key): wrong[key].item() for key in ids} + result = numerics.evaluate_logits(expected, observed, 0, budgets()) + assert not result['accepted'] and 'normalized_logprob_error' in result['failures'] + with pytest.raises(ValueError, match='top-20'): + numerics.evaluate_logits(expected, {'0': 0.0}, 0, budgets()) + observed['1000'] = observed.pop(str(ids[-1])) + with pytest.raises(ValueError, match='out of range'): + numerics.evaluate_logits(expected, observed, 0, budgets()) + missing = {str(key): -10.0 for key in range(1, 21)} + assert not numerics.evaluate_logits(expected, missing, 1, budgets())['accepted'] + duplicate = {str(key): -10.0 for key in range(20)} + duplicate['00'] = -10.0 + with pytest.raises(ValueError, match='duplicated'): + numerics.evaluate_logits(expected, duplicate, 0, budgets()) + + +@pytest.fixture +def cpu_reference(monkeypatch): + """Exercise reference tensor operations on CPU with explicit fake device transport.""" + torch = pytest.importorskip('torch') + tensor, ones = torch.tensor, torch.ones + + def cpu_tensor(*args, **kwargs): + if kwargs.get('device') == 'cuda': + kwargs['device'] = 'cpu' + return tensor(*args, **kwargs) + + def cpu_ones(*args, **kwargs): + if kwargs.get('device') == 'cuda': + kwargs['device'] = 'cpu' + return ones(*args, **kwargs) + + monkeypatch.setattr(torch, 'tensor', cpu_tensor) + monkeypatch.setattr(torch, 'ones', cpu_ones) + return torch + + +def test_complete_prefix_and_cached_reference_shapes(numerics, cpu_reference): + """Check all attention-mask lengths and cache positions without a GPU.""" + torch = cpu_reference + calls = [] + + def model(input_ids, attention_mask, use_cache, past_key_values=None): + calls.append((input_ids.shape, attention_mask.shape, use_cache, past_key_values)) + logits = torch.arange(24, dtype=torch.float32).reshape(1, 1, 24) + return SimpleNamespace( + logits=logits.expand(input_ids.shape[0], input_ids.shape[1], 24), past_key_values=len(calls) + ) + + cases = [{'id': str(index), 'prompt_token_ids': [1, 2, 3], 'continuation_ids': [4, 5]} for index in range(3)] + full = numerics.full_logits(model, [[1, 2, 3]]) + assert full.shape == (1, 24) and calls[-1][2:] == (False, None) + values = numerics.collect_matched_bf16(model, cases, 2) + assert set(values) == {'0', '1', '2'} and all(value.shape == (2, 24) for value in values.values()) + assert calls[1][0:2] == (torch.Size([2, 3]), torch.Size([2, 3])) + assert calls[2][0:2] == (torch.Size([2, 1]), torch.Size([2, 4])) + assert calls[2][3] is not None + errors = numerics.tensor_errors(values['0'][0], values['1'][0]) + assert errors['greedy_match'] and all(errors[metric] == 0 for metric in numerics.METRICS) + with pytest.raises(ValueError, match='uniquely'): + numerics.configured_batches(cases + cases, 2) + mismatched = [cases[0], dict(cases[1], continuation_ids=[4])] + with pytest.raises(ValueError, match='matching sequence'): + list(numerics.cached_logits(model, mismatched)) + + +def test_reference_rejects_nonfinite_and_incomplete_output(numerics, cpu_reference, monkeypatch): + """Reference failures cannot create success-shaped numerical evidence.""" + torch = cpu_reference + + def model(**kwargs): + return SimpleNamespace(logits=torch.full((1, 2, 24), float('nan')), past_key_values=1) + + cases = [{'id': '0', 'prompt_token_ids': [1, 2], 'continuation_ids': [3]}] + with pytest.raises(RuntimeError, match='Nonfinite'): + numerics.full_logits(model, [[1, 2]]) + with pytest.raises(RuntimeError, match='Nonfinite'): + list(numerics.cached_logits(model, cases)) + monkeypatch.setattr(numerics, 'cached_logits', lambda *args: iter([])) + with pytest.raises(ValueError, match='Incomplete'): + numerics.collect_matched_bf16(model, cases, 1) + monkeypatch.setattr(numerics, 'cached_logits', lambda *args: iter([(1, torch.zeros((1, 24)))])) + with pytest.raises(ValueError, match='out-of-order'): + numerics.collect_matched_bf16(model, cases, 1) + + +def request_sets(numerics): + """Create token-shaped fixtures, not reference or engine measurements.""" + documents, eos, records = [[1, 2, 3], [4, 5, 6]], 99, [] + short = [ + numerics.packed_tokens(documents, eos, length, 1, index * 7)[0] for index, length in enumerate((16, 23, 32)) + ] + for offset in numerics.OFFSETS: + prompts = short * 2 + numerics.packed_tokens(documents, eos, 512, 8, offset) + for index, prompt in enumerate(prompts): + count = 4 if index < 6 else 64 + row = { + 'prompt_token_ids': prompt, + 'token_ids': [1] * count, + 'logprobs': [{} for _ in range(count)], + 'numerical_set_offset': offset, + } + if index >= 6: + row.update(profile_request_index=index - 6, profile_batch_size=8) + records.append(row) + return documents, eos, records + + +@pytest.mark.parametrize('fault', ['missing-window', 'wrong-prompt', 'short-decode', 'lost-row', 'bad-token', 'trace']) +def test_frozen_request_sets_cannot_drop_positions(numerics, fault): + """Require all six windows and every configured-batch row.""" + documents, eos, requests = request_sets(numerics) + groups = numerics.validate_requests(requests, documents, eos) + assert list(groups) == list(numerics.OFFSETS) + if fault == 'missing-window': + requests.pop() + elif fault == 'wrong-prompt': + requests[0]['prompt_token_ids'] = [7] + elif fault == 'short-decode': + for row in requests[:14]: + row['token_ids'] = row['token_ids'][:1] + row['logprobs'] = row['logprobs'][:1] + elif fault == 'lost-row': + requests[6]['profile_request_index'] = 2 + elif fault == 'bad-token': + requests[0]['token_ids'][0] = True + else: + requests[0]['logprobs'].pop() + with pytest.raises(ValueError): + numerics.validate_requests(requests, documents, eos) + + +@pytest.mark.parametrize('corrupt', [False, True]) +def test_group_scoring_retains_all_positive_and_fault_positions(numerics, monkeypatch, corrupt): + """A good synthetic pair must reject every fault; a corrupted pair must fail.""" + torch = pytest.importorskip('torch') + vectors = [torch.arange(32, dtype=torch.float32), torch.arange(31, -1, -1, dtype=torch.float32)] + expected = [value.log_softmax(-1) for value in vectors] + requests, matched = [], {} + for index in range(2): + ids = expected[index].topk(20).indices.tolist() + observed = {str(key): expected[index][key].item() for key in ids} + if corrupt: + observed = {key: value - math.log(2) for key, value in observed.items()} + requests.append( + { + 'prompt_token_ids': [index], + 'token_ids': [expected[index].argmax().item()] * 2, + 'logprobs': [observed, observed], + } + ) + matched['request-{}'.format(index)] = torch.stack([expected[index], expected[index]]) + monkeypatch.setattr(numerics, 'full_logits', lambda model, rows: vectors[rows[0][0]].unsqueeze(0)) + result = numerics.evaluate_group(None, requests, matched, budgets()) + assert result['positive_positions'] == 4 and result['negative_positions'] == 9 + assert len(result['positive_failures']) == (4 if corrupt else 0) + assert not result['negative_failures'] + assert {row['fault'] + for row in result['all_negative_records']} == { + 'half-normalization', + 'temperature-two', + 'last-request-context-for-first', + } + + +@pytest.mark.parametrize('failure', [False, True]) +def test_reference_models_are_sequential_and_always_released(numerics, monkeypatch, failure): + """Exercise lifecycle plumbing with explicit CPU-only model doubles.""" + if sys.version_info < (3, 10): + pytest.skip('The standalone reference runtime requires Python 3.10 or later.') + torch = pytest.importorskip('torch') + from superbench.benchmarks.model_benchmarks.deepseek_v2_lite import reference + + loaded = [] + + def load_model(checkpoint, dtype): + loaded.append(dtype) + model = SimpleNamespace() + model.cuda = lambda: model + model.eval = lambda: model + return model + + monkeypatch.setattr(reference, 'load_model', load_model) + monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: ([[1, 2]], 99)) + monkeypatch.setattr(numerics, 'validate_requests', lambda *args: {0: [{'prompt_token_ids': [1], 'token_ids': [2]}]}) + monkeypatch.setattr(numerics, 'collect_matched_bf16', lambda *args: {}) + monkeypatch.setattr(torch, 'set_num_threads', Mock()) + monkeypatch.setattr(torch, 'set_float32_matmul_precision', Mock()) + monkeypatch.setattr(torch.cuda, 'set_device', Mock()) + monkeypatch.setattr(torch.cuda, 'get_device_name', lambda index: 'synthetic-h100') + release = Mock() + monkeypatch.setattr(torch.cuda, 'empty_cache', release) + monkeypatch.setattr(torch.cuda, 'synchronize', Mock()) + from importlib.metadata import version + identity = { + 'torch_version': torch.__version__, + 'transformers_version': version('transformers'), + 'gpu_name': 'synthetic-h100', + 'reference_loader_sha256': hashlib.sha256(inspect.getsource(load_model).encode()).hexdigest(), + 'tf32_allowed': False, + 'bf16_reduced_precision_reduction': torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction, + } + contract = { + 'calibrated_contract': { + 'runtime_identity': identity, + 'limits': budgets(), + 'frozen_limits_sha256': 'fixture' + } + } + evaluation = Mock( + side_effect=RuntimeError('reference failed') if failure else None, + return_value={ + 'positive_positions': 1, + 'negative_positions': 3, + 'positive_failures': [], + 'negative_failures': [] + }, + ) + monkeypatch.setattr(numerics, 'evaluate_group', evaluation) + if failure: + with pytest.raises(RuntimeError, match='reference failed'): + numerics.run_reference(Path('fixture'), [1], contract) + else: + result = numerics.run_reference(Path('fixture'), [1], contract) + assert result['correctness_passed'] is True and result['teardown_complete'] is True + assert loaded == [torch.bfloat16, torch.float32] + assert release.call_count == 2 + identity['gpu_name'] = 'different-hardware' + with pytest.raises(ValueError, match='runtime or hardware'): + numerics.run_reference(Path('fixture'), [1], contract) + + +@pytest.mark.parametrize('passed', [True, False]) +def test_reference_cli_preserves_rejection_evidence(numerics, monkeypatch, tmp_path, passed): + """A rejected report is saved but the process must still fail explicitly.""" + requests, output = tmp_path / 'requests.json', tmp_path / 'reference.json' + requests.write_text('[]') + monkeypatch.setattr( + sys, 'argv', [ + 'reference', + '--checkpoint', + str(tmp_path), + '--requests', + str(requests), + '--output', + str(output), + ] + ) + monkeypatch.setattr(numerics, 'load_contract', lambda: {'fixture': True}) + monkeypatch.setattr(numerics, 'run_reference', lambda *args: {'correctness_passed': passed}) + validate = Mock() + monkeypatch.setattr(numerics, 'validate_reference_result', validate) + if passed: + numerics.main() + else: + with pytest.raises(RuntimeError, match='rejected'): + numerics.main() + assert json.loads(output.read_text())['correctness_passed'] is passed + assert numerics.os.environ['NVIDIA_TF32_OVERRIDE'] == '0' + assert validate.call_count == int(passed) + + +def serialized_reference(numerics): + """Build complete control-flow evidence with explicit synthetic accepted/rejected flags.""" + windows = {} + for offset in numerics.OFFSETS: + positives, negatives = [], [] + for request in range(14): + count = 4 if request < 6 else 64 + for step in range(count): + positives.append({'request': request, 'step': step, 'accepted': True}) + negatives.extend( + [ + { + 'request': request, + 'step': step, + 'accepted': False, + 'fault': fault + } for fault in ('half-normalization', 'temperature-two') + ] + ) + negatives.append({'request': 0, 'step': 0, 'accepted': False, 'fault': 'last-request-context-for-first'}) + windows[str(offset)] = { + 'positive_positions': len(positives), + 'negative_positions': len(negatives), + 'positive_failures': [], + 'negative_failures': [], + 'all_positive_records': positives, + 'all_negative_records': negatives, + } + return { + 'correctness_passed': True, + 'teardown_complete': True, + 'numerical_policy': numerics.POLICY, + 'contract_sha256': numerics.CONTRACT_SHA256, + 'profile_offsets': list(numerics.OFFSETS), + 'request_count': 84, + 'positive_positions': 3216, + 'negative_positions': 6438, + 'windows': windows, + } + + +@pytest.mark.parametrize( + 'fault', [ + 'identity', + 'missing-window', + 'invalid-window', + 'missing-position', + 'accepted-fault', + 'failed-positive', + 'bad-index', + 'duplicate-position', + 'missing-step', + 'wrong-fault', + 'totals', + ] +) +def test_serialized_reference_cannot_fabricate_complete_success(numerics, fault): + """Validate all per-window records rather than trusting a summary flag.""" + report = serialized_reference(numerics) + numerics.validate_reference_result(report) + window = report['windows']['0'] + overrides = {'identity': ('contract_sha256', 'another-policy'), 'totals': ('positive_positions', 3215)} + if fault in overrides: + key, value = overrides[fault] + report[key] = value + elif fault == 'missing-window': + report['windows'].pop('0') + elif fault == 'invalid-window': + report['windows']['0'] = None + elif fault == 'missing-position': + window['all_positive_records'].pop() + elif fault == 'accepted-fault': + window['all_negative_records'][0]['accepted'] = True + elif fault == 'failed-positive': + window['all_positive_records'][0]['accepted'] = False + elif fault == 'bad-index': + window['all_positive_records'][0]['step'] = True + elif fault == 'duplicate-position': + window['all_positive_records'][0] = dict(window['all_positive_records'][1]) + elif fault == 'missing-step': + window['all_positive_records'][0]['step'] = 5 + else: + window['all_negative_records'][-1]['fault'] = 'substituted-fault' + with pytest.raises(ValueError): + numerics.validate_reference_result(report) From 7861ecd4f596d2918729016d43479c81d9ff49bb Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Fri, 30 Oct 2026 15:13:16 +0000 Subject: [PATCH 7/8] Benchmarks - Build DeepSeek-V2-Lite inference runtimes into the CUDA 13.0 image Replace the dedicated inference image with a third_party target that the CUDA 13.0 platform image runs. It installs vLLM 0.31.0 with torch 2.13.0+cu130 in /opt/vllm and the official-code reference, transformers 4.46.3 on that torch, in /opt/deepseek-reference, both outside the SuperBench Python. Remove the inference Dockerfile and its requirement locks, update the usage docs, and note that only the inference workers run without SuperBench. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- dockerfile/cuda13.0.dockerfile | 1 + .../deepseek-v2-lite-inference.dockerfile | 23 ------ .../deepseek-v2-lite-controller.in | 15 ---- .../deepseek-v2-lite-controller.txt | 81 ------------------- .../deepseek-v2-lite-reference.txt | 5 -- .../benchmarks/model-benchmarks.md | 20 ++--- .../deepseek_v2_lite/__init__.py | 4 +- third_party/Makefile | 23 +++++- 8 files changed, 30 insertions(+), 142 deletions(-) delete mode 100644 dockerfile/deepseek-v2-lite-inference.dockerfile delete mode 100644 dockerfile/requirements/deepseek-v2-lite-controller.in delete mode 100644 dockerfile/requirements/deepseek-v2-lite-controller.txt delete mode 100644 dockerfile/requirements/deepseek-v2-lite-reference.txt diff --git a/dockerfile/cuda13.0.dockerfile b/dockerfile/cuda13.0.dockerfile index 520920afa..a97d9255a 100644 --- a/dockerfile/cuda13.0.dockerfile +++ b/dockerfile/cuda13.0.dockerfile @@ -153,6 +153,7 @@ WORKDIR ${SB_HOME} ADD third_party third_party RUN make -C third_party cuda +RUN make -C third_party deepseek_v2_lite ADD . . RUN python3 -m pip install --upgrade setuptools==78.1.0 && \ diff --git a/dockerfile/deepseek-v2-lite-inference.dockerfile b/dockerfile/deepseek-v2-lite-inference.dockerfile deleted file mode 100644 index dcaa4f11d..000000000 --- a/dockerfile/deepseek-v2-lite-inference.dockerfile +++ /dev/null @@ -1,23 +0,0 @@ -FROM vllm/vllm-openai:v0.31.0@sha256:c1c9f6fd5c109ba7f0546a59f5b2f15fb87f64c77782e90a27b648b42a8e67c3 - -RUN apt-get update && apt-get install -y --no-install-recommends git && apt-get clean - -COPY dockerfile/requirements/deepseek-v2-lite-controller.txt /tmp/deepseek-v2-lite-controller.txt -RUN mkdir -p /opt/vllm/bin && ln -s /usr/bin/python3 /opt/vllm/bin/python && \ - python3 -m venv --system-site-packages /opt/deepseek-reference && \ - python3 -c "import pathlib, sys, sysconfig; source=sysconfig.get_path('purelib'); target=pathlib.Path('/opt/deepseek-reference/lib') / ('python%d.%d' % sys.version_info[:2]) / 'site-packages'; (target / 'engine-torch.pth').write_text(source + '\n')" && \ - /opt/deepseek-reference/bin/pip install --no-cache-dir --no-deps -r /tmp/deepseek-v2-lite-controller.txt - -WORKDIR /opt/superbench -COPY setup.py MANIFEST.in LICENSE README.md ./ -COPY superbench ./superbench -RUN /opt/deepseek-reference/bin/pip install --no-cache-dir --no-deps --no-build-isolation . && \ - /opt/deepseek-reference/bin/python -c "import numpy, torch, transformers; assert transformers.__version__ == '4.46.3'; assert torch.from_numpy(numpy.ones(1, dtype=numpy.float32)).numpy()[0] == 1" && \ - /opt/vllm/bin/python -c "from importlib.metadata import version; import numpy, torch; assert version('vllm').split('+')[0] == '0.31.0'; assert version('transformers') == '5.17.0'; assert torch.from_numpy(numpy.ones(1, dtype=numpy.float32)).numpy()[0] == 1" && \ - /opt/deepseek-reference/bin/sb run --help > /dev/null && \ - /opt/deepseek-reference/bin/sb result diagnosis --help > /dev/null - -RUN apt-get update && apt-get install -y --no-install-recommends rsync && apt-get clean - -ENV PATH="/opt/deepseek-reference/bin:${PATH}" -ENTRYPOINT ["sb"] diff --git a/dockerfile/requirements/deepseek-v2-lite-controller.in b/dockerfile/requirements/deepseek-v2-lite-controller.in deleted file mode 100644 index cef428772..000000000 --- a/dockerfile/requirements/deepseek-v2-lite-controller.in +++ /dev/null @@ -1,15 +0,0 @@ -# Additional constraints for the dedicated Python 3.12 controller/reference runtime. -# Torch and torchvision are provided by the digest-pinned GPU base image. -# The NGC Torch build uses the NumPy 1.x ABI; keep its array bridge functional. -# Regenerate from the repository root with bash: -# uv pip compile setup.py dockerfile/requirements/deepseek-v2-lite-reference.txt \ -# dockerfile/requirements/deepseek-v2-lite-controller.in --python-version 3.12 \ -# --python-platform x86_64-unknown-linux-gnu --excludes <(printf 'torch\ntorchvision\n') \ -# --no-header --no-annotate -o dockerfile/requirements/deepseek-v2-lite-controller.txt -numpy==1.26.4 -pandas==2.2.3 -py3nvml==0.2.7 -setuptools==80.10.2 -setuptools-scm==10.3.4 -vcs-versioning==2.5.0 -wheel diff --git a/dockerfile/requirements/deepseek-v2-lite-controller.txt b/dockerfile/requirements/deepseek-v2-lite-controller.txt deleted file mode 100644 index 905fbf218..000000000 --- a/dockerfile/requirements/deepseek-v2-lite-controller.txt +++ /dev/null @@ -1,81 +0,0 @@ -# Generated for Python 3.12 / Linux x86_64 from setup.py, the reference pins, -# and deepseek-v2-lite-controller.in. The GPU base supplies torch/torchvision. -accelerate==1.2.1 -ansible==14.5.0 -ansible-core==2.21.5 -ansible-runner==2.4.3 -antlr4-python3-runtime==4.9.3 -argcomplete==3.7.2 -attrs==26.1.0 -certifi==2026.10.19 -cffi==2.1.1 -charset-normalizer==3.5.2 -click==8.5.0 -cloudpickle==3.1.2 -colorlog==6.12.0 -contourpy==1.3.3 -cryptography==50.0.2 -cycler==0.12.1 -et-xmlfile==2.0.0 -filelock==4.2.4 -fonttools==4.67.0 -fsspec==2026.9.0 -huggingface-hub==0.26.5 -idna==3.20 -importlib-metadata==9.0.1 -jinja2==3.1.6 -jmespath==1.1.0 -joblib==1.6.0 -jsonlines==4.0.0 -kiwisolver==1.5.1 -knack==0.14.0 -lockfile==0.12.2 -markdown==3.11.2 -markupsafe==3.0.4 -matplotlib==3.11.2 -natsort==8.4.0 -networkx==3.7 -numpy==1.26.4 -omegaconf==2.3.0 -openpyxl==3.1.5 -packaging==26.3 -pandas==2.2.3 -pexpect==4.9.0 -pillow==13.0.0 -prettytable==3.18.0 -protobuf==7.36.2 -pssh @ git+https://github.com/lilydjwg/pssh.git@2dce3d8e45a492985fa1ae0207b6d55afac97c16 -psutil==7.2.2 -ptyprocess==0.7.0 -py3nvml==0.2.7 -pycparser==3.11 -pygments==2.21.0 -pyparsing==3.3.3 -python-daemon==3.1.2 -python-dateutil==2.9.0.post0 -pytz==2026.5 -pyyaml==6.0.3 -regex==2026.9.29 -requests==2.34.2 -resolvelib==1.2.1 -safetensors==0.5.3 -seaborn==0.13.2 -setuptools==80.10.2 -setuptools-scm==10.3.4 -six==1.17.0 -tabulate==0.10.0 -tcping==0.1.1rc1 -tokenizers==0.20.3 -tqdm==4.70.1 -transformers==4.46.3 -types-requests==2.33.0.20261006 -typing-extensions==4.16.0 -tzdata==2026.5 -urllib3==2.8.0 -vcs-versioning==2.5.0 -wcwidth==0.9.3 -wheel==0.48.0 -xlrd==2.0.2 -xlsxwriter==3.2.9 -xmltodict==1.0.4 -zipp==4.1.2 diff --git a/dockerfile/requirements/deepseek-v2-lite-reference.txt b/dockerfile/requirements/deepseek-v2-lite-reference.txt deleted file mode 100644 index e5ab4c95a..000000000 --- a/dockerfile/requirements/deepseek-v2-lite-reference.txt +++ /dev/null @@ -1,5 +0,0 @@ -# Separate worker environment; do not replace SuperBench's framework dependencies. -transformers==4.46.3 -huggingface-hub==0.26.5 -accelerate==1.2.1 -safetensors==0.5.3 diff --git a/docs/user-tutorial/benchmarks/model-benchmarks.md b/docs/user-tutorial/benchmarks/model-benchmarks.md index 3a2d4209b..3cf2b22a3 100644 --- a/docs/user-tutorial/benchmarks/model-benchmarks.md +++ b/docs/user-tutorial/benchmarks/model-benchmarks.md @@ -188,21 +188,11 @@ only on one H100 80GB GPU. The FP32 reference needs an 80GB-class GPU. #### Usage Run the [inference profile](../../../superbench/config/deepseek-v2-lite-inference.yaml) as its own -benchmark entry with one local process (`proc_num: 1`). The -[model runtime Dockerfile](../../../dockerfile/deepseek-v2-lite-inference.dockerfile) provides -separate vLLM and reference environments: - -```bash -docker build -f dockerfile/deepseek-v2-lite-inference.dockerfile -t sb-v2lite-inference . -docker run --rm --gpus device=0 --shm-size 32g \ - -v "$PWD/v2lite-results:/results" sb-v2lite-inference exec \ - --config-file superbench/config/deepseek-v2-lite-inference.yaml \ - --output-dir /results/sb-output \ - -C superbench.benchmarks.deepseek-v2-lite-inference.parameters.cache_root=/results/model-cache -``` - -Outside Docker, set `runtime_python` to a vLLM 0.31.0 environment and `reference_python` to a separate -environment with the [reference packages](../../../dockerfile/requirements/deepseek-v2-lite-reference.txt). +benchmark entry with one local process (`proc_num: 1`) in the SuperBench CUDA 13.0 image. Its build runs +`make -C third_party deepseek_v2_lite`, which installs vLLM 0.31.0 in `/opt/vllm` (`runtime_python`) and +the official-code reference in `/opt/deepseek-reference` (`reference_python`). Both stay outside the +SuperBench Python because vLLM pins its own PyTorch. Elsewhere, run that target or point both +parameters at equivalent environments. `cache_root` is required. Each run downloads the checkpoint into a new directory under it and deletes that model cache at the end, keeping the report and logs. If deletion fails, the cache path is logged diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/__init__.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/__init__.py index 9cc630068..da0e0cb0a 100644 --- a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/__init__.py +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/__init__.py @@ -3,6 +3,6 @@ """DeepSeek-V2-Lite workers and helpers. -Workers run as ``python -m deepseek_v2_lite.`` in interpreters without SuperBench, so every module -except ``cache`` imports only the standard library and this package at load time. +Workers run as ``python -m deepseek_v2_lite.``, the inference ones in interpreters without SuperBench, +so every module except ``cache`` imports only the standard library and this package at load time. """ diff --git a/third_party/Makefile b/third_party/Makefile index 5dd73372c..65327c114 100755 --- a/third_party/Makefile +++ b/third_party/Makefile @@ -8,6 +8,8 @@ HIP_HOME ?= /opt/rocm/hip RCCL_HOME ?= /opt/rocm/rccl HPCX_HOME ?= /opt/hpcx ROCM_PATH ?= /opt/rocm +DEEPSEEK_V2_LITE_VLLM ?= /opt/vllm +DEEPSEEK_V2_LITE_REFERENCE ?= /opt/deepseek-reference CUDA_VER ?= $(shell nvcc --version | grep 'release' | awk '{print $$6}' | cut -c2- | cut -d '.' -f1-2) ROCBLAS_BRANCH ?= rocm-$(shell dpkg -l | grep 'rocm-dev ' | awk '{print $$3}' | cut -d '.' -f1-3) @@ -16,7 +18,7 @@ ROCM_VER ?= $(shell hipconfig -R | grep -oP '\d+\.\d+\.\d+' || echo "0.0.0") NUM_MAKE_JOBS ?= $(shell nproc --ignore=2) -.PHONY: all cuda_with_msccl cuda rocm common cuda_cutlass cuda_bandwidthTest cuda_nccl_tests cuda_perftest cuda_msccl rocm_perftest fio rocm_rccl_tests rocm_rocblas rocm_bandwidthTest gpcnet cuda_gpuburn cpu_stream cpu_hpl directx_amf_encoding_latency directx_amd rocm_hipblaslt megatron_lm megatron_deepspeed apex_rocm nvbandwidth rocm_megatron_lm cuda_nvbench +.PHONY: all cuda_with_msccl cuda rocm common cuda_cutlass cuda_bandwidthTest cuda_nccl_tests cuda_perftest cuda_msccl rocm_perftest fio rocm_rccl_tests rocm_rocblas rocm_bandwidthTest gpcnet cuda_gpuburn cpu_stream cpu_hpl directx_amf_encoding_latency directx_amd rocm_hipblaslt megatron_lm megatron_deepspeed apex_rocm nvbandwidth rocm_megatron_lm cuda_nvbench deepseek_v2_lite # Build targets. all: cuda rocm @@ -268,6 +270,25 @@ megatron_deepspeed: python -m pip install --no-cache-dir -r requirements.txt && \ python -m pip install DeepSpeed +# Install the vLLM engine and the official-code reference for DeepSeek-V2-Lite inference outside the SuperBench +# Python: vLLM pins its own torch, and the qualified reference needs transformers 4.46.3 on that torch. +deepseek_v2_lite: + python3 -m venv $(DEEPSEEK_V2_LITE_VLLM) && \ + $(DEEPSEEK_V2_LITE_VLLM)/bin/python -m pip install --no-cache-dir --index-url https://download.pytorch.org/whl/cu130 \ + torch==2.13.0 torchvision==0.28.0 torchaudio==2.11.0 && \ + $(DEEPSEEK_V2_LITE_VLLM)/bin/python -m pip install --no-cache-dir vllm==0.31.0 transformers==5.17.0 && \ + python3 -m venv $(DEEPSEEK_V2_LITE_REFERENCE) && \ + $(DEEPSEEK_V2_LITE_VLLM)/bin/python -c "import sysconfig; print(sysconfig.get_path('purelib'))" > \ + $$($(DEEPSEEK_V2_LITE_REFERENCE)/bin/python -c "import sysconfig; print(sysconfig.get_path('purelib'))")/vllm-torch.pth && \ + $(DEEPSEEK_V2_LITE_REFERENCE)/bin/python -m pip install --no-cache-dir --no-deps transformers==4.46.3 tokenizers==0.20.3 \ + huggingface-hub==0.26.5 safetensors==0.5.3 accelerate==1.2.1 numpy==1.26.4 && \ + $(DEEPSEEK_V2_LITE_VLLM)/bin/python -c "from importlib.metadata import version; import numpy, torch; \ + assert (version('vllm'), version('transformers'), torch.__version__) == ('0.31.0', '5.17.0', '2.13.0+cu130'); \ + assert torch.from_numpy(numpy.ones(1, dtype=numpy.float32)).numpy()[0] == 1" && \ + $(DEEPSEEK_V2_LITE_REFERENCE)/bin/python -c "import numpy, torch, transformers; \ + assert (transformers.__version__, torch.__version__) == ('4.46.3', '2.13.0+cu130'); \ + assert torch.from_numpy(numpy.ones(1, dtype=numpy.float32)).numpy()[0] == 1" + rocm_megatron_lm: cd Megatron && mkdir -p rocm && cd rocm && \ if [ ! -d "Megatron-LM" ]; then \ From 2ffcb7e550a7efe41a0a4b4216a5c7f73da52f7a Mon Sep 17 00:00:00 2001 From: gusui-msft <257632554+gusui-msft@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:04:52 +0000 Subject: [PATCH 8/8] Benchmarks - Enforce one V2-Lite launcher and keep timeouts after failed cleanup Port the shared fixes from the #887 review, keeping deepseek_v2_lite/utils.py and its tests identical in both PRs: - Check PROC_RANK, WORLD_SIZE and OMPI_COMM_WORLD_SIZE independently, so a second local process or a masked MPI world size cannot start another model replica. - If descendant cleanup fails after the deadline, the supervisor returns 126 and run_worker raises a TimeoutError that names the failed cleanup. - The download test now proves that a corrupted shard is rejected. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../deepseek_v2_lite/utils.py | 64 ++++++++++++++----- .../model_benchmarks/vllm_deepseek_v2_lite.py | 14 ++-- .../model_benchmarks/test_deepseek_v2_lite.py | 41 +++++++++++- .../test_vllm_deepseek_v2_lite.py | 12 ++++ 4 files changed, 109 insertions(+), 22 deletions(-) diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/utils.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/utils.py index 0a44520ef..9ab65448e 100644 --- a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/utils.py +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/utils.py @@ -12,7 +12,7 @@ import sys import time from pathlib import Path -from typing import Dict, List, Optional, Sequence +from typing import Callable, Dict, List, Mapping, Optional, Sequence MODEL_ID = 'deepseek-ai/DeepSeek-V2-Lite' REVISION = '604d5664dddd88a0433dbae533b7fe9472482de0' @@ -238,6 +238,20 @@ def _stop_children() -> None: time.sleep(0.02) +def _wait_for_worker(process: subprocess.Popen, deadline: float, interrupted: Callable[[], bool]) -> int: + """Return the worker status, 124 at the deadline or on interruption, or 125 for live descendants.""" + while process.poll() is None: + if interrupted() or time.monotonic() >= deadline: + return 124 + time.sleep(0.02) + code = process.wait() + _reap_children() + if code == 0 and _owned_children(): + print('Worker exited with live descendant processes.', file=sys.stderr, flush=True) + return 125 + return code if code >= 0 else 128 - code + + def supervise_worker(command: List[str], timeout: float, parent_pid: int) -> int: """Contain Linux worker descendants in a separate single-threaded supervisor.""" import ctypes @@ -262,20 +276,21 @@ def stop(signum, frame): return 124 deadline = time.monotonic() + timeout process = subprocess.Popen(command) + stopped = False try: - while process.poll() is None: - if interrupted or time.monotonic() >= deadline: - return 124 - time.sleep(0.02) - code = process.wait() - _reap_children() - if code == 0 and _owned_children(): - print('Worker exited with live descendant processes.', file=sys.stderr, flush=True) - return 125 - return code if code >= 0 else 128 - code + code = _wait_for_worker(process, deadline, lambda: interrupted) finally: - _stop_children() - process.wait() + try: + _stop_children() + stopped = True + except RuntimeError as error: + print(error, file=sys.stderr, flush=True) + if stopped: + process.wait() + if stopped: + return code + # Keep cleanup failures visible: 126 is a deadline whose cleanup also failed, and a clean exit becomes 125. + return 126 if code == 124 else code or 125 def interrupt_worker(signum, frame) -> None: @@ -283,6 +298,24 @@ def interrupt_worker(signum, frame) -> None: raise TimeoutError('Model worker interrupted by signal {}.'.format(signum)) +# SuperBench local ranks and the torch and MPI world sizes; any other value means another launcher. +SINGLE_LAUNCHER = {'PROC_RANK': 0, 'WORLD_SIZE': 1, 'OMPI_COMM_WORLD_SIZE': 1} + + +def validate_single_launcher(environment: Mapping[str, str]) -> None: + """Reject a second local process or a distributed group, checking every launcher variable.""" + for name, expected in SINGLE_LAUNCHER.items(): + value = environment.get(name) + if value is None: + continue + try: + single = int(value) == expected + except ValueError: + single = False + if not single: + raise ValueError('{}={!r} means another launcher; run one local process.'.format(name, value)) + + def worker_environment() -> Dict[str, str]: """Let worker interpreters without SuperBench import this package by module name.""" environment = dict(os.environ) @@ -314,8 +347,9 @@ def run_worker(command: List[str], log: Path, timeout: float, env: Optional[Dict code = process.wait(timeout=timeout + 20) except subprocess.TimeoutExpired as error: raise TimeoutError('Model worker supervisor exceeded its cleanup deadline.') from error - if code == 124: - raise TimeoutError('Model worker exceeded the download-inclusive deadline.') + if code in (124, 126): + cleanup = ' and its descendants did not exit; see {}'.format(log) if code == 126 else '' + raise TimeoutError('Model worker exceeded the download-inclusive deadline{}.'.format(cleanup)) if code == 125: raise RuntimeError('Model worker left descendant processes running; see {}.'.format(log)) if code != 0: diff --git a/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py b/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py index 27bdd7d08..9d1d8d918 100644 --- a/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py +++ b/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py @@ -18,7 +18,7 @@ remove_model_cache, remove_model_cache_after_failure ) from superbench.benchmarks.model_benchmarks.deepseek_v2_lite.utils import ( - numeric_series, read_json, run_worker, validate_identity, worker_environment + numeric_series, read_json, run_worker, validate_identity, validate_single_launcher, worker_environment ) @@ -59,16 +59,18 @@ def _preprocess(self): self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) return False try: - world_size = int(os.environ.get('WORLD_SIZE', os.environ.get('OMPI_COMM_WORLD_SIZE', '1'))) - except ValueError: - world_size = 0 + validate_single_launcher(os.environ) + except ValueError as error: + logger.error('V2-Lite inference requires one local replica: %s', error) + self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) + return False invalid = ( args.run_count != 1 or not 30 < args.duration < 3600 or args.batch_size < 1 or args.seq_len < 32 or args.max_new_tokens < 4 or args.num_warmup < 0 or args.num_steps < 1 - or not 0 < args.gpu_memory_utilization <= 0.95 or world_size != 1 + or not 0 < args.gpu_memory_utilization <= 0.95 ) if invalid: - logger.error('V2-Lite inference requires one local replica and a valid BF16 generation/deadline profile.') + logger.error('V2-Lite inference requires a valid BF16 generation/deadline profile.') self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) return False try: diff --git a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite.py index 3934bc0fb..36cf39a8a 100644 --- a/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite.py +++ b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite.py @@ -260,7 +260,7 @@ def test_invalid_checkpoint_files_fail(checkpoint_files, failure): def test_download_uses_pinned_public_identity_and_then_verifies(checkpoint_files, monkeypatch): - """Disable implicit credentials and require the downloaded shard contract.""" + """Disable implicit credentials and reject a downloaded shard that fails verification.""" root, shard = checkpoint_files download = Mock() monkeypatch.setitem(sys.modules, 'huggingface_hub', SimpleNamespace(snapshot_download=download)) @@ -271,6 +271,9 @@ def test_download_uses_pinned_public_identity_and_then_verifies(checkpoint_files assert arguments['token'] is False assert arguments['local_dir'] == str(root) assert shard.name in arguments['allow_patterns'] + download.side_effect = lambda **kwargs: shard.write_bytes(b'x' * shard.stat().st_size) + with pytest.raises(ValueError, match='SHA256'): + utils.download_checkpoint(root.parent) @pytest.mark.parametrize('timeout', [0, -1, float('nan')]) @@ -298,6 +301,42 @@ def test_supervisor_requires_kernel_ownership_support(monkeypatch): spawn.assert_not_called() +def test_timeout_survives_failed_descendant_cleanup(tmp_path, monkeypatch, capsys): + """A cleanup failure after the deadline stays a timeout and keeps its own details.""" + worker = SimpleNamespace(poll=lambda: None, wait=Mock()) + monkeypatch.setattr(utils.signal, 'signal', Mock()) + monkeypatch.setattr(ctypes, 'CDLL', lambda *args, **kwargs: SimpleNamespace(prctl=lambda *args: 0)) + monkeypatch.setattr(utils.subprocess, 'Popen', lambda command: worker) + monkeypatch.setattr(utils, '_stop_children', Mock(side_effect=RuntimeError('descendants did not exit: [4242]'))) + assert utils.supervise_worker([sys.executable, '-c', 'pass'], 0.05, os.getppid()) == 126 + assert '[4242]' in capsys.readouterr().err + worker.wait.assert_not_called() + supervisor = SimpleNamespace(wait=lambda timeout: 126, poll=lambda: 126) + monkeypatch.setattr(utils.subprocess, 'Popen', lambda *args, **kwargs: supervisor) + with pytest.raises(TimeoutError, match='deadline and its descendants did not exit'): + utils.run_worker([sys.executable, '-c', 'pass'], tmp_path / 'worker.log', 5) + + +@pytest.mark.parametrize( + 'environment, accepted', [ + ('', True), + ('PROC_RANK=0 WORLD_SIZE=1 OMPI_COMM_WORLD_SIZE=1', True), + ('PROC_RANK=1', False), + ('WORLD_SIZE=1 OMPI_COMM_WORLD_SIZE=8', False), + ('OMPI_COMM_WORLD_SIZE=1 WORLD_SIZE=2', False), + ('PROC_RANK=', False), + ] +) +def test_launcher_variables_are_checked_independently(environment, accepted): + """A local rank or any one distributed world size above one means another launcher.""" + variables = dict(item.split('=', 1) for item in environment.split()) + if accepted: + utils.validate_single_launcher(variables) + else: + with pytest.raises(ValueError, match='another launcher'): + utils.validate_single_launcher(variables) + + # Per-run model cache removal. def test_removes_only_the_run_cache(tmp_path): """Delete the downloaded checkpoint while keeping the run's report and logs.""" diff --git a/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py b/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py index be83f6ad1..fe6a95a96 100644 --- a/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py +++ b/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py @@ -30,6 +30,7 @@ def benchmark(tmp_path, monkeypatch): """Use one local replica and an isolated output root.""" monkeypatch.delenv('WORLD_SIZE', raising=False) monkeypatch.delenv('OMPI_COMM_WORLD_SIZE', raising=False) + monkeypatch.delenv('PROC_RANK', raising=False) return adapter.DeepSeekV2LiteInference( 'deepseek-v2-lite-inference', '--cache_root "{}" --num_steps 2 --batch_size 2 --seq_len 64 --duration 60'.format(tmp_path), @@ -91,6 +92,17 @@ def test_cache_root_is_required(): assert instance.return_code == ReturnCode.INVALID_ARGUMENT +@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 model replica.""" + for item in environment.split(): + monkeypatch.setenv(*item.split('=', 1)) + 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.""" instance = adapter.DeepSeekV2LiteInference('deepseek-v2-lite-inference')