diff --git a/MANIFEST.in b/MANIFEST.in index 34d9d0272..1b29ff6d4 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,3 +1,4 @@ include LICENSE README.md +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/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/docs/user-tutorial/benchmarks/model-benchmarks.md b/docs/user-tutorial/benchmarks/model-benchmarks.md index c782abbcc..3cf2b22a3 100644 --- a/docs/user-tutorial/benchmarks/model-benchmarks.md +++ b/docs/user-tutorial/benchmarks/model-benchmarks.md @@ -163,3 +163,56 @@ Run GPT pretrain tasks with float32, float16, bfloat16 precisions with [Megatron | megatron-gpt/${precision}_train_mem_allocated | GB | The average GPU memory allocated per iteration. | | megatron-gpt/${precision}_train_max_mem_allocated | GB | The average maximum GPU memory allocated per iteration. | +## DeepSeek-V2-Lite Inference + +### `deepseek-v2-lite-inference` + +#### 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`) 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 +for manual removal. `duration` must be below 3600 seconds and covers the whole job, from download to +cache deletion. + +#### Metrics + +| 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. | 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/__init__.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/__init__.py new file mode 100644 index 000000000..da0e0cb0a --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/__init__.py @@ -0,0 +1,8 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""DeepSeek-V2-Lite workers and helpers. + +Workers run as ``python -m deepseek_v2_lite.``, the inference ones in interpreters without SuperBench, +so every module except ``cache`` imports only the standard library and this package at load time. +""" diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/cache.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/cache.py new file mode 100644 index 000000000..a240a7787 --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/cache.py @@ -0,0 +1,60 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Bounded removal of one V2-Lite run's downloaded model cache.""" + +import subprocess +import sys +import time +from pathlib import Path + +from superbench.common.utils import logger + +FAILURE_CLEANUP_GRACE_SECONDS = 60 +_REMOVE_TREE = 'import os, shutil, sys\nif os.path.exists(sys.argv[1]):\n shutil.rmtree(sys.argv[1])' + + +def remove_model_cache(cache: Path, deadline: float) -> None: + """Delete one run's model cache before a monotonic deadline, keeping reports and logs. + + A missing budget, an expired deletion or a SuperBench SIGTERM raises TimeoutError. Other + filesystem errors are logged so that a validated measurement is not discarded. + """ + start = time.monotonic() + remaining = deadline - start + if remaining <= 0: + raise TimeoutError('No time remains to remove the V2-Lite model cache at {}.'.format(cache)) + try: + # A child process can be stopped and reaped at the deadline; an in-process rmtree cannot. + subprocess.run( + [sys.executable, '-c', _REMOVE_TREE, str(cache)], + timeout=remaining, + check=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + universal_newlines=True, + ) + except subprocess.TimeoutExpired as error: + raise TimeoutError('V2-Lite model cache cleanup exceeded the deadline at {}.'.format(cache)) from error + except TimeoutError: + # The SuperBench SIGTERM handler raises TimeoutError, an OSError subclass; keep it fatal. + raise + except subprocess.CalledProcessError as error: + logger.error('Failed to remove the V2-Lite model cache %s: %s', cache, error.output or error) + return + except OSError as error: + logger.error('Failed to remove the V2-Lite model cache %s: %s', cache, error) + return + logger.info('V2-Lite model cache cleanup completed for %s in %.1f seconds.', cache, time.monotonic() - start) + + +def remove_model_cache_after_failure(cache: Path, deadline: float) -> None: + """Remove the cache of a failed run without replacing the run's original error. + + Cleanup may run until the job deadline or for FAILURE_CLEANUP_GRACE_SECONDS, whichever ends later, + so a timed-out worker does not leave its checkpoint behind only because the budget is spent. + """ + try: + remove_model_cache(cache, max(deadline, time.monotonic() + FAILURE_CLEANUP_GRACE_SECONDS)) + except TimeoutError as error: + logger.error('V2-Lite model cache cleanup did not finish after a failed run: %s', error) diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/h100_bf16_v6.json b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/h100_bf16_v6.json new file mode 100644 index 000000000..b245bd522 --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/h100_bf16_v6.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/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..b488bd8ac --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/inference_worker.py @@ -0,0 +1,338 @@ +# 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 + +from . import numerics +from .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, '-m', 'deepseek_v2_lite.numerics', '--checkpoint', + str(checkpoint), '--requests', + str(requests), '--output', + str(reference) + ] if contract else [ + args.reference_python, '-m', 'deepseek_v2_lite.reference', '--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..a32b72375 --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/numerics.py @@ -0,0 +1,482 @@ +# 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 + +from .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__).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.') + 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 + from .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..313d2c89b --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/reference.py @@ -0,0 +1,266 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Unsharded official-code reference, executed in a separate pinned environment.""" + +import argparse +import gc +import os +from pathlib import Path + +from .utils import ( + FIXED_TEXTS, PARAMETER_COUNT, packed_tokens, read_json, uniform_indices, validate_config, write_json +) + +TRAINING_GRADIENT_PARAMETERS = { + 'model.embed_tokens.weight', + 'model.layers.0.self_attn.q_proj.weight', + 'model.layers.0.self_attn.kv_a_proj_with_mqa.weight', + 'model.layers.0.mlp.down_proj.weight', + 'model.layers.1.mlp.gate.weight', +} + + +def load_model(checkpoint, dtype): + """Load official causal-LM weights with no quantization or model reduction.""" + from importlib.metadata import version + + import torch + from transformers import AutoModelForCausalLM + + if version('transformers') != '4.46.3': + raise RuntimeError('The official-code reference requires transformers==4.46.3.') + validate_config(read_json(Path(checkpoint) / 'config.json')) + model, loading = AutoModelForCausalLM.from_pretrained( + checkpoint, + torch_dtype=dtype, + trust_remote_code=True, + local_files_only=True, + use_safetensors=True, + attn_implementation='eager', + output_loading_info=True, + ) + for key in ('missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs'): + if key not in loading or loading[key]: + raise RuntimeError('Official checkpoint loading failed: {}={!r}.'.format(key, loading.get(key))) + if sum(parameter.numel() for parameter in model.parameters()) != PARAMETER_COUNT: + raise RuntimeError('Loaded parameter count differs from the complete official V2-Lite.') + if not all(parameter.requires_grad for parameter in model.parameters()): + raise RuntimeError('The full-parameter profile must not freeze model parameters.') + if not torch.cuda.is_available(): + raise RuntimeError('CUDA/ROCm GPU unavailable in the reference environment.') + return model + + +def fixed_documents(checkpoint): + """Tokenize the small, versioned natural-text input with the official tokenizer.""" + from transformers import AutoTokenizer + + tokenizer = AutoTokenizer.from_pretrained(checkpoint, local_files_only=True, trust_remote_code=True) + return [tokenizer.encode(text, add_special_tokens=False) for text in FIXED_TEXTS], tokenizer.eos_token_id + + +def _training_gradient_probes(model, gradients): + """Select fixed dense/MLA/router/active-expert positions from the first rank batch.""" + import torch + + required = TRAINING_GRADIENT_PARAMETERS + probes = {} + expert_probe = False + for name, parameter in model.named_parameters(): + gradient = gradients.get(name) + if gradient is None: + continue + selected_expert = ( + not expert_probe and name.startswith('model.layers.1.mlp.experts.') and name.endswith('down_proj.weight') + and torch.count_nonzero(gradient).item() > 0 + ) + if name in required or selected_expert: + flat = gradient.detach().flatten() + nonzero = torch.nonzero(flat, as_tuple=False).flatten()[:512] + spread = torch.tensor(uniform_indices(flat.numel()), device=flat.device, dtype=torch.long) + indices = torch.unique(torch.cat((nonzero, spread))) + values = flat[indices].float().cpu() + if not torch.isfinite(values).all().item(): + raise RuntimeError('Nonfinite reference gradient: {}'.format(name)) + probes[name] = { + 'shape': list(parameter.shape), + 'indices': indices.cpu().tolist(), + 'values': torch.zeros_like(values) + } + if selected_expert: + expert_probe = True + if not required.issubset(probes) or not expert_probe: + raise RuntimeError('Required dense/MLA/router/expert reference gradients are missing.') + return probes + + +def training_reference(model, checkpoint, batch_size=1, seq_len=32, world_size=1): + """Reference exact rank batches without storing unrequested parameter gradients.""" + import torch + + if batch_size < 1 or seq_len < 32 or world_size < 1: + raise ValueError('Invalid training reference profile.') + documents, eos = fixed_documents(checkpoint) + model.train() + model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={'use_reentrant': False}) + tokens = packed_tokens(documents, eos, seq_len, batch_size * world_size) + losses, probes = [], {} + targets = { + name: parameter + for name, parameter in model.named_parameters() if name in TRAINING_GRADIENT_PARAMETERS or + (name.startswith('model.layers.1.mlp.experts.') and name.endswith('down_proj.weight')) + } + for rank in range(world_size): + batch = tokens[rank * batch_size:(rank + 1) * batch_size] + inputs = torch.tensor(batch, device='cuda', dtype=torch.long) + model.zero_grad(set_to_none=True) + output = model(input_ids=inputs, labels=inputs, use_cache=False) + loss = output.loss + del output + if loss is None or not torch.isfinite(loss).item(): + raise RuntimeError('Nonfinite or missing reference causal-LM loss.') + losses.append(loss.item()) + gradients = dict(zip(targets, torch.autograd.grad(loss, tuple(targets.values()), allow_unused=True))) + if not probes: + probes = _training_gradient_probes(model, gradients) + for name, probe in probes.items(): + gradient = gradients[name] + if gradient is None: + if '.experts.' not in name: + raise RuntimeError('Missing reference gradient: {}'.format(name)) + continue + indices = torch.tensor(probe['indices'], device=gradient.device, dtype=torch.long) + values = gradient.detach().flatten()[indices].float().cpu() + if not torch.isfinite(values).all().item(): + raise RuntimeError('Nonfinite reference gradient: {}'.format(name)) + probe['values'] += values / world_size + del gradients, loss, inputs + model.zero_grad(set_to_none=True) + for probe in probes.values(): + probe['values'] = probe['values'].tolist() + return { + 'tokens': tokens, + 'loss': sum(losses) / world_size, + 'loss_per_rank': losses, + 'gradients': probes, + 'batch_size': batch_size, + 'seq_len': seq_len, + 'world_size': world_size, + 'reference_microbatch_size': batch_size, + } + + +def inference_reference(model, requests): + """Compare cached decode to full-prefix logits and engine-selected logprobs.""" + import torch + + if not isinstance(requests, list) or not requests: + raise ValueError('Inference reference requests must be nonempty.') + model.eval() + comparisons = [] + with torch.no_grad(): + for request_index, request in enumerate(requests): + prompt = request['prompt_token_ids'] + completion = request['token_ids'] + logprobs = request['logprobs'] + if not prompt or not completion or len(completion) != len(logprobs): + raise ValueError('Incomplete inference reference request.') + full_prefix_steps = request.get('full_prefix_steps', list(range(len(completion)))) + if ( + not isinstance(full_prefix_steps, list) or not full_prefix_steps + or any(type(step) is not int + for step in full_prefix_steps) or full_prefix_steps != sorted(set(full_prefix_steps)) + or full_prefix_steps[0] != 0 or full_prefix_steps[-1] != len(completion) - 1 + ): + raise ValueError('Full-prefix reference positions must include ordered first and final steps.') + prefix = torch.tensor([prompt], device='cuda', dtype=torch.long) + cache = None + for step, token in enumerate(completion): + attention_mask = torch.ones_like(prefix) + output = model( + input_ids=prefix if step == 0 else prefix[:, -1:], + attention_mask=attention_mask, + past_key_values=cache, + use_cache=True + ) + cache = output.past_key_values + cached = output.logits[:, -1, :].float() + check_full_prefix = step in full_prefix_steps + full = ( + model(input_ids=prefix, attention_mask=attention_mask, use_cache=False).logits[:, -1, :].float() + if check_full_prefix else cached + ) + if not torch.isfinite(cached).all().item() or not torch.isfinite(full).all().item(): + raise RuntimeError('Nonfinite reference logits.') + if check_full_prefix: + torch.testing.assert_close(cached, full, rtol=0.02, atol=0.05) + if full[0].argmax().item() != token: + raise RuntimeError('Engine greedy token differs at request {} step {}.'.format(request_index, step)) + expected = torch.log_softmax(full[0], dim=-1) + ids = [int(value) for value in logprobs[step]] + if token not in ids or not ids: + raise ValueError('Missing selected-token engine log probability.') + actual = torch.tensor([logprobs[step][str(value)] for value in ids], device='cuda') + target = expected[ids] + torch.testing.assert_close( + actual, + target, + rtol=0.02, + atol=0.05, + msg=lambda message: 'Engine/reference request {} step {}:\n{}'.format(request_index, step, message), + ) + comparisons.append( + { + 'request': request_index, + 'step': step, + 'logprob_positions': len(ids), + 'full_prefix_checked': check_full_prefix, + 'cache_max_abs_error': (cached - full).abs().max().item() if check_full_prefix else None, + 'engine_logprob_max_abs_error': (actual - target).abs().max().item(), + } + ) + prefix = torch.cat((prefix, torch.tensor([[token]], device='cuda')), dim=1) + return {'comparisons': comparisons, 'logprob_rtol': 0.02, 'logprob_atol': 0.05} + + +def main(): + """Run a bounded reference and write only numeric/token-ID evidence.""" + import torch + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--checkpoint', required=True) + parser.add_argument('--mode', choices=['training', 'inference'], required=True) + parser.add_argument('--requests') + parser.add_argument('--output', required=True) + parser.add_argument('--batch_size', type=int, default=1) + parser.add_argument('--seq_len', type=int, default=32) + parser.add_argument('--world_size', type=int, default=1) + args = parser.parse_args() + torch.cuda.set_device(0) + os.environ['TORCH_ALLOW_TF32_CUBLAS_OVERRIDE'] = '0' + torch.backends.cuda.matmul.allow_tf32 = False + dtype = torch.bfloat16 if args.mode == 'training' else torch.float32 + model = load_model(args.checkpoint, dtype).cuda() + try: + if args.mode == 'training': + result = training_reference(model, args.checkpoint, args.batch_size, args.seq_len, args.world_size) + else: + if not args.requests: + raise ValueError('--requests is required for inference reference.') + result = inference_reference(model, read_json(Path(args.requests))) + torch.cuda.synchronize() + finally: + del model + gc.collect() + torch.cuda.empty_cache() + torch.cuda.synchronize() + result['correctness_passed'] = True + result['teardown_complete'] = True + result['reference_dtype'] = str(dtype) + result['tf32_allowed'] = False + write_json(Path(args.output), result) + + +if __name__ == '__main__': + main() diff --git a/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/utils.py b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/utils.py new file mode 100644 index 000000000..9ab65448e --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/deepseek_v2_lite/utils.py @@ -0,0 +1,406 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Checkpoint, input and subprocess contracts for the fixed V2-Lite workload.""" + +import hashlib +import json +import math +import os +import signal +import subprocess +import sys +import time +from pathlib import Path +from typing import Callable, Dict, List, Mapping, Optional, Sequence + +MODEL_ID = 'deepseek-ai/DeepSeek-V2-Lite' +REVISION = '604d5664dddd88a0433dbae533b7fe9472482de0' +PARAMETER_COUNT = 15706484224 +WEIGHT_FILES = { + 'model-00001-of-000004.safetensors': + (8594887408, '0d7e9f39bde40111a4c0f390b87497dce4565cf578d916395e6b2c7851f1e8da'), + 'model-00002-of-000004.safetensors': + (8591757448, 'e0656832b0d594b4a64cad40ff8465231de6ed44c854f74f6b217797660aa4bb'), + 'model-00003-of-000004.safetensors': + (8590718520, '843ec689624f3a520526e040f0326c4dc9865e8172942ca98a084fe136fdb21a'), + 'model-00004-of-000004.safetensors': + (5636263200, 'cfb51658f67cedfbbc4d62ad14187830ceec8ee82c788c5f718feea98905ef31'), +} +WEIGHT_BYTES = sum(size for size, _ in WEIGHT_FILES.values()) +EXPECTED_CONFIG = { + 'hidden_size': 2048, + 'num_hidden_layers': 27, + 'num_attention_heads': 16, + 'intermediate_size': 10944, + 'moe_intermediate_size': 1408, + 'n_routed_experts': 64, + 'n_shared_experts': 2, + 'num_experts_per_tok': 6, + 'first_k_dense_replace': 1, + 'kv_lora_rank': 512, + 'q_lora_rank': None, + 'qk_nope_head_dim': 128, + 'qk_rope_head_dim': 64, + 'v_head_dim': 128, + 'vocab_size': 102400, + 'seq_aux': True, + 'aux_loss_alpha': 0.001, + 'attention_dropout': 0.0, +} +FIXED_TEXTS = ( + 'The engineering team measures a system before changing its configuration. ' + 'Each measurement records the input, the software version, and the observation time.', + 'A warehouse receives several shipments each morning. Workers check the labels, ' + 'sort the packages by destination, and keep a record of damaged items.', + 'A weather station samples temperature and wind speed at regular intervals. ' + 'Missing readings are reported explicitly instead of being replaced with zero.', + 'The library contains books about science, history, and music. Readers can search ' + 'the catalog, reserve an available book, and return it at the front desk.', + 'A numerical experiment compares two implementations on the same input. ' + 'The result includes the error tolerance and every failed comparison.', + 'A small garden has three rows of vegetables and a rainwater tank. ' + 'The gardener checks soil moisture before deciding how much water to use.', + 'The train arrives at the northern platform at eight in the morning. ' + 'Passengers check their tickets and leave space for people getting off.', + 'A computer processes a sequence of tokens using a language model. ' + 'Training computes a loss and gradients, while generation reuses attention state.', +) +INPUT_SHA256 = hashlib.sha256('\n'.join(FIXED_TEXTS).encode('utf-8')).hexdigest() + + +def read_json(path: Path): + """Read a JSON document without accepting nonfinite JSON constants.""" + def reject_constant(value): + raise ValueError('Nonfinite JSON constant: {}'.format(value)) + + with path.open() as stream: + return json.load(stream, parse_constant=reject_constant) + + +def write_json(path: Path, document) -> None: + """Write a complete report atomically, rejecting nonfinite numbers.""" + temporary = path.with_suffix(path.suffix + '.tmp') + with temporary.open('w') as stream: + json.dump(document, stream, indent=2, allow_nan=False) + stream.write('\n') + temporary.replace(path) + + +def validate_config(config) -> None: + """Reject a reduced, quantized or different model configuration.""" + if not isinstance(config, dict) or config.get('model_type') != 'deepseek_v2': + raise ValueError('Expected the official DeepSeek-V2 configuration.') + for key, expected in EXPECTED_CONFIG.items(): + if key not in config or config[key] != expected: + raise ValueError('Official V2-Lite {} must be {!r}, got {!r}.'.format(key, expected, config.get(key))) + if config.get('quantization_config') is not None: + raise ValueError('This profile does not accept quantized checkpoints.') + + +def configure_cache(cache: Path) -> None: + """Isolate all model caches without reading or removing shared caches.""" + cache.mkdir(parents=True, exist_ok=True) + if any(cache.iterdir()): + raise ValueError('Cold-start cache must be empty: {}'.format(cache)) + set_cache_environment(cache) + + +def set_cache_environment(cache: Path) -> None: + """Select the same isolated cache in each distributed worker.""" + for variable, directory in { + 'HF_HOME': 'hf', + 'HF_HUB_CACHE': 'hub', + 'HF_XET_CACHE': 'xet', + 'HF_MODULES_CACHE': 'modules', + 'TRANSFORMERS_CACHE': 'transformers', + }.items(): + os.environ[variable] = str(cache / directory) + os.environ['HF_HUB_DISABLE_IMPLICIT_TOKEN'] = '1' + os.environ['HF_HUB_DISABLE_TELEMETRY'] = '1' + + +def verify_checkpoint(checkpoint: Path) -> None: + """Verify the complete fixed checkpoint, its index and every weight hash.""" + validate_config(read_json(checkpoint / 'config.json')) + index = read_json(checkpoint / 'model.safetensors.index.json') + if not isinstance(index, dict) or not isinstance(index.get('weight_map'), dict): + raise ValueError('Missing checkpoint weight map.') + if set(index['weight_map'].values()) != set(WEIGHT_FILES): + raise ValueError('Checkpoint index does not describe the four official weight shards.') + for filename, (size, expected_hash) in WEIGHT_FILES.items(): + path = checkpoint / filename + if not path.is_file() or path.stat().st_size != size: + raise ValueError('Missing or incorrectly sized checkpoint shard: {}'.format(filename)) + digest = hashlib.sha256() + with path.open('rb') as stream: + for block in iter(lambda: stream.read(8 * 1024 * 1024), b''): + digest.update(block) + if digest.hexdigest() != expected_hash: + raise ValueError('Checkpoint SHA256 mismatch: {}'.format(filename)) + + +def download_checkpoint(cache: Path) -> Path: + """Download and verify official weights before any GPU model construction.""" + from huggingface_hub import snapshot_download + + checkpoint = cache / 'checkpoint' + snapshot_download( + repo_id=MODEL_ID, + revision=REVISION, + local_dir=str(checkpoint), + cache_dir=str(cache / 'hub'), + allow_patterns=list(WEIGHT_FILES) + [ + 'config.json', 'generation_config.json', 'model.safetensors.index.json', 'tokenizer*', + 'special_tokens_map.json', '*.py' + ], + token=False, + max_workers=4, + ) + verify_checkpoint(checkpoint) + return checkpoint + + +def packed_tokens(documents: Sequence[Sequence[int]], + eos: int, + length: int, + count: int, + offset: int = 0) -> List[List[int]]: + """Pack deterministic real-text tokens without padding a pressure workload.""" + if length < 2 or count < 1 or offset < 0 or not documents or eos < 0: + raise ValueError('Invalid packed-input dimensions or documents.') + stream: List[int] = [] + for document in documents: + if not document or any(type(token) is not int or token < 0 for token in document): + raise ValueError('Each document must contain nonnegative integer token IDs.') + stream.extend(document) + stream.append(eos) + return [ + [stream[(offset + row * length + column) % len(stream)] for column in range(length)] for row in range(count) + ] + + +def numeric_series(report, name: str, count: int, positive: bool = True) -> List[float]: + """Require a complete finite metric series, never a default or sentinel.""" + values = report.get(name) if isinstance(report, dict) else None + if not isinstance(values, list) or len(values) != count: + raise ValueError('Expected {} {} samples.'.format(count, name)) + if any( + isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or + (positive and value <= 0) for value in values + ): + raise ValueError('Invalid numeric metric: {}'.format(name)) + return [float(value) for value in values] + + +def uniform_indices(length: int, count: int = 256) -> List[int]: + """Sample large tensor offsets with integer arithmetic, never FP32 rounding.""" + if length < 1 or count < 2: + raise ValueError('Invalid tensor length or sample count.') + return [position * (length - 1) // (count - 1) for position in range(count)] + + +def _owned_children() -> List[int]: + """Read the dedicated supervisor's direct and adopted children.""" + path = Path('/proc/self/task/{}/children'.format(os.getpid())) + return [int(pid) for pid in path.read_text().split()] + + +def _reap_children() -> None: + """Reap exited owned children so no stale PID is treated as running.""" + while True: + try: + pid, _ = os.waitpid(-1, os.WNOHANG) + except ChildProcessError: + return + if pid == 0: + return + + +def _stop_children() -> None: + """Reap all job descendants, including ranks that created new sessions.""" + graceful_deadline = time.monotonic() + 10 + deadline = graceful_deadline + 5 + while True: + children = _owned_children() + if not children: + return + current = time.monotonic() + if current >= deadline: + raise RuntimeError('Owned worker descendants did not exit: {}.'.format(children)) + signum = signal.SIGTERM if current < graceful_deadline else signal.SIGKILL + for pid in children: + try: + os.kill(pid, signum) + except ProcessLookupError: + pass + _reap_children() + time.sleep(0.02) + + +def _wait_for_worker(process: subprocess.Popen, deadline: float, interrupted: Callable[[], bool]) -> int: + """Return the worker status, 124 at the deadline or on interruption, or 125 for live descendants.""" + while process.poll() is None: + if interrupted() or time.monotonic() >= deadline: + return 124 + time.sleep(0.02) + code = process.wait() + _reap_children() + if code == 0 and _owned_children(): + print('Worker exited with live descendant processes.', file=sys.stderr, flush=True) + return 125 + return code if code >= 0 else 128 - code + + +def supervise_worker(command: List[str], timeout: float, parent_pid: int) -> int: + """Contain Linux worker descendants in a separate single-threaded supervisor.""" + import ctypes + + if sys.platform != 'linux': + raise RuntimeError('The isolated model worker supervisor requires Linux.') + libc = ctypes.CDLL(None, use_errno=True) + interrupted = False + + def stop(signum, frame): + nonlocal interrupted + interrupted = True + + signal.signal(signal.SIGTERM, stop) + signal.signal(signal.SIGINT, stop) + # Adopt orphaned rank sessions and clean up if the controller itself dies. + for option, value in [(36, 1), (1, signal.SIGTERM)]: # PR_SET_CHILD_SUBREAPER, PR_SET_PDEATHSIG + if libc.prctl(option, ctypes.c_ulong(value), ctypes.c_ulong(0), ctypes.c_ulong(0), ctypes.c_ulong(0)) != 0: + error = ctypes.get_errno() + raise OSError(error, os.strerror(error)) + if os.getppid() != parent_pid: + return 124 + deadline = time.monotonic() + timeout + process = subprocess.Popen(command) + stopped = False + try: + code = _wait_for_worker(process, deadline, lambda: interrupted) + finally: + try: + _stop_children() + stopped = True + except RuntimeError as error: + print(error, file=sys.stderr, flush=True) + if stopped: + process.wait() + if stopped: + return code + # Keep cleanup failures visible: 126 is a deadline whose cleanup also failed, and a clean exit becomes 125. + return 126 if code == 124 else code or 125 + + +def interrupt_worker(signum, frame) -> None: + """Unwind subprocess waits so nested reference workers are cleaned up.""" + raise TimeoutError('Model worker interrupted by signal {}.'.format(signum)) + + +# SuperBench local ranks and the torch and MPI world sizes; any other value means another launcher. +SINGLE_LAUNCHER = {'PROC_RANK': 0, 'WORLD_SIZE': 1, 'OMPI_COMM_WORLD_SIZE': 1} + + +def validate_single_launcher(environment: Mapping[str, str]) -> None: + """Reject a second local process or a distributed group, checking every launcher variable.""" + for name, expected in SINGLE_LAUNCHER.items(): + value = environment.get(name) + if value is None: + continue + try: + single = int(value) == expected + except ValueError: + single = False + if not single: + raise ValueError('{}={!r} means another launcher; run one local process.'.format(name, value)) + + +def worker_environment() -> Dict[str, str]: + """Let worker interpreters without SuperBench import this package by module name.""" + environment = dict(os.environ) + paths = [str(Path(__file__).resolve().parents[1]), environment.get('PYTHONPATH', '')] + environment['PYTHONPATH'] = os.pathsep.join(path for path in paths if path) + return environment + + +def run_worker(command: List[str], log: Path, timeout: float, env: Optional[Dict[str, str]] = None) -> None: + """Supervise the whole worker tree under one deadline, preserving failure logs.""" + if not math.isfinite(timeout) or timeout <= 0: + raise TimeoutError('No time remains for the worker.') + if not command: + raise ValueError('The model worker command must not be empty.') + supervisor = [ + sys.executable, + str(Path(__file__).resolve()), + '--worker-timeout', + str(timeout), + '--parent-pid', + str(os.getpid()), + '--', + *command, + ] + with log.open('w') as stream: + process = subprocess.Popen(supervisor, stdout=stream, stderr=subprocess.STDOUT, start_new_session=True, env=env) + try: + try: + code = process.wait(timeout=timeout + 20) + except subprocess.TimeoutExpired as error: + raise TimeoutError('Model worker supervisor exceeded its cleanup deadline.') from error + if code in (124, 126): + cleanup = ' and its descendants did not exit; see {}'.format(log) if code == 126 else '' + raise TimeoutError('Model worker exceeded the download-inclusive deadline{}.'.format(cleanup)) + if code == 125: + raise RuntimeError('Model worker left descendant processes running; see {}.'.format(log)) + if code != 0: + raise RuntimeError('Model worker exited with code {}; see {}.'.format(code, log)) + finally: + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=20) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + raise RuntimeError('Model worker supervisor did not complete descendant cleanup.') + + +def identity_report() -> Dict[str, object]: + """Describe the fixed model and input contract without generated text.""" + return { + 'model_id': MODEL_ID, + 'revision': REVISION, + 'weight_bytes': WEIGHT_BYTES, + 'weight_sha256': {name: digest + for name, (_, digest) in WEIGHT_FILES.items()}, + 'parameter_count': PARAMETER_COUNT, + 'precision': 'bfloat16', + 'input_dataset': 'fixed-text-v1', + 'input_sha256': INPUT_SHA256, + 'cold_cache': True, + } + + +def validate_identity(report) -> None: + """Require a successful official-model report before accepting any metrics.""" + expected = identity_report() + if not isinstance(report, dict) or report.get('status') != 'success': + raise ValueError('Worker did not produce a successful model report.') + if any(report.get(key) != value for key, value in expected.items()): + raise ValueError('Worker report does not match the official checkpoint/input contract.') + if report.get('correctness_passed') is not True or report.get('teardown_complete') is not True: + raise ValueError('Correctness or worker teardown was not completed.') + + +if __name__ == '__main__': + import argparse + + parser = argparse.ArgumentParser(description='Supervise one isolated model worker command.') + parser.add_argument('--worker-timeout', type=float, required=True) + parser.add_argument('--parent-pid', type=int, required=True) + parser.add_argument('command', nargs=argparse.REMAINDER) + arguments = parser.parse_args() + worker_command = arguments.command[1:] if arguments.command[:1] == ['--'] else arguments.command + if not worker_command or not math.isfinite(arguments.worker_timeout) or arguments.worker_timeout <= 0: + parser.error('A worker command and finite positive timeout are required.') + sys.exit(supervise_worker(worker_command, arguments.worker_timeout, arguments.parent_pid)) diff --git a/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py b/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py new file mode 100644 index 000000000..9d1d8d918 --- /dev/null +++ b/superbench/benchmarks/model_benchmarks/vllm_deepseek_v2_lite.py @@ -0,0 +1,197 @@ +# 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.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, validate_single_launcher, worker_environment +) + + +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=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', 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: + 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 + ) + if invalid: + logger.error('V2-Lite inference requires 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, + '-m', + 'deepseek_v2_lite.inference_worker', + '--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 _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() + 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))) + 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, + env=worker_environment(), + ) + 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) + 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.') + 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-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.py b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite.py new file mode 100644 index 000000000..36cf39a8a --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_deepseek_v2_lite.py @@ -0,0 +1,754 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""CPU tests for the shared DeepSeek-V2-Lite helpers: checkpoint, worker supervision, cache and reference.""" + +import copy +import ctypes +import hashlib +import json +import math +import os +import signal +import subprocess +import sys +import time +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +from superbench.benchmarks.model_benchmarks.deepseek_v2_lite import ( + cache as cleanup, reference as reference_module, utils +) + +torch = pytest.importorskip('torch') + + +# Checkpoint identity, fixed inputs and worker supervision. +def test_checkpoint_identity(): + """Reject architecture proxies and quantization.""" + config = dict(utils.EXPECTED_CONFIG, model_type='deepseek_v2') + utils.validate_config(config) + config['hidden_size'] = 1024 + with pytest.raises(ValueError, match='hidden_size'): + utils.validate_config(config) + config['hidden_size'] = 2048 + config['quantization_config'] = {'quant_method': 'fp8'} + with pytest.raises(ValueError, match='quantized'): + utils.validate_config(config) + assert utils.WEIGHT_BYTES == 31413626576 + + +def test_packed_text_is_reproducible(): + """Pack actual token inputs with EOS separators, not padding or mock execution.""" + documents = [[1, 2], [3, 4, 5]] + expected = [[1, 2, 9, 3], [4, 5, 9, 1]] + assert utils.packed_tokens(documents, 9, 4, 2) == expected + assert utils.packed_tokens(documents, 9, 4, 2) == expected + assert utils.packed_tokens(documents, 9, 4, 2, offset=1) != expected + + +@pytest.mark.parametrize('documents,length,count', [([], 4, 1), ([[]], 4, 1), ([[True]], 4, 1), ([[1]], 1, 1)]) +def test_invalid_text_inputs(documents, length, count): + """Surface malformed inputs instead of returning an empty batch.""" + with pytest.raises(ValueError): + utils.packed_tokens(documents, 9, length, count) + + +def test_cold_cache_isolated(tmp_path, monkeypatch): + """Reject cache reuse without deleting shared contents.""" + shared = tmp_path / 'shared' + shared.mkdir() + sentinel = shared / 'keep' + sentinel.write_text('unrelated data') + monkeypatch.setenv('HF_HOME', str(shared)) + cache = tmp_path / 'cold' + utils.configure_cache(cache) + assert sentinel.read_text() == 'unrelated data' + assert utils.os.environ['HF_HOME'] == str(cache / 'hf') + assert utils.os.environ['HF_XET_CACHE'] == str(cache / 'xet') + (cache / 'present').touch() + with pytest.raises(ValueError, match='empty'): + utils.configure_cache(cache) + + +def test_report_requires_correctness_and_teardown(): + """Require model identity, not just a successful process exit.""" + report = dict(utils.identity_report(), status='success', correctness_passed=True, teardown_complete=True) + utils.validate_identity(report) + incorrect = copy.deepcopy(report) + incorrect['parameter_count'] = 100 + with pytest.raises(ValueError, match='contract'): + utils.validate_identity(incorrect) + report['correctness_passed'] = False + with pytest.raises(ValueError, match='Correctness'): + utils.validate_identity(report) + + +@pytest.mark.parametrize('length', [1, 512, 209715200, 15706484224]) +def test_large_tensor_probe_indices(length): + """FP32-rounded endpoints must never index beyond a real full-model tensor.""" + indices = utils.uniform_indices(length) + assert len(indices) == 256 + assert indices[0] == 0 and indices[-1] == length - 1 + assert all(0 <= index < length for index in indices) + + +def test_atomic_json_rejects_nonfinite_values(tmp_path): + """A malformed report must not replace a complete report.""" + path = tmp_path / 'report.json' + utils.write_json(path, {'value': 1}) + with pytest.raises(ValueError): + utils.write_json(path, {'value': math.nan}) + assert utils.read_json(path) == {'value': 1} + path.write_text('{"value": NaN}') + with pytest.raises(ValueError, match='Nonfinite'): + utils.read_json(path) + + +def test_worker_failure_is_explicit(tmp_path): + """Reject nonzero exit codes even if the worker writes a result-like message.""" + with pytest.raises(RuntimeError, match='code 7'): + utils.run_worker([sys.executable, '-c', 'print("success"); raise SystemExit(7)'], tmp_path / 'worker.log', 5) + assert 'success' in (tmp_path / 'worker.log').read_text() + + +def test_timeout_reaps_worker(tmp_path): + """A timeout must terminate the created process rather than leave a worker.""" + pid_file = tmp_path / 'pid' + command = [ + sys.executable, + '-c', + 'import os,time; from pathlib import Path; Path({!r}).write_text(str(os.getpid())); time.sleep(60)'.format( + str(pid_file) + ), + ] + with pytest.raises(TimeoutError, match='deadline'): + utils.run_worker(command, tmp_path / 'worker.log', 1) + pid = int(pid_file.read_text()) + with pytest.raises(ProcessLookupError): + utils.os.kill(pid, 0) + + +def test_success_with_live_child_is_rejected(tmp_path): + """A leader's exit code zero is insufficient when its child remains alive.""" + command = [ + sys.executable, + '-c', + 'import subprocess,sys; subprocess.Popen([sys.executable,"-c","import time; time.sleep(60)"])', + ] + with pytest.raises(RuntimeError, match='descendant processes'): + utils.run_worker(command, tmp_path / 'worker.log', 5) + + +@pytest.mark.parametrize('launcher_exits', [False, True]) +def test_separate_session_child_is_reaped(tmp_path, launcher_exits): + """Own escaped rank sessions even when their launcher exits or ignores termination.""" + pid_file = tmp_path / 'rank.pid' + rank = ( + 'import os,signal,time; from pathlib import Path; ' + 'signal.signal(signal.SIGTERM, signal.SIG_IGN); ' + 'Path({!r}).write_text(str(os.getpid())); time.sleep(60)' + ).format(str(pid_file)) + launcher = ( + 'import signal,subprocess,sys,time; from pathlib import Path; ' + 'signal.signal(signal.SIGTERM, signal.SIG_IGN); ' + 'subprocess.Popen([sys.executable, "-c", {!r}], start_new_session=True); ' + 'ready=Path({!r})\n' + 'while not ready.exists(): time.sleep(0.01)\n' + '{}' + ).format(rank, str(pid_file), 'sys.exit(0)' if launcher_exits else 'time.sleep(60)') + try: + expected = RuntimeError if launcher_exits else TimeoutError + with pytest.raises(expected): + utils.run_worker([sys.executable, '-c', launcher], tmp_path / 'worker.log', 5 if launcher_exits else 1) + pid = int(pid_file.read_text()) + with pytest.raises(ProcessLookupError): + os.kill(pid, 0) + finally: + if pid_file.exists(): + pid = int(pid_file.read_text()) + try: + os.kill(pid, signal.SIGKILL) + except ProcessLookupError: + pass + + +def test_worker_signal_does_not_kill_unrelated_process(tmp_path): + """Timeout cleanup must be scoped to the supervised job, not the controller's children.""" + unrelated = utils.subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)']) + try: + with pytest.raises(TimeoutError): + utils.run_worker([sys.executable, '-c', 'import time; time.sleep(60)'], tmp_path / 'worker.log', 0.2) + assert unrelated.poll() is None + finally: + unrelated.terminate() + unrelated.wait(timeout=5) + + +def test_controller_death_reaps_owned_worker(tmp_path): + """A killed controller must not leave its independently supervised job alive.""" + pid_file = tmp_path / 'worker.pid' + worker = ('import os,time; from pathlib import Path; ' + 'Path({!r}).write_text(str(os.getpid())); time.sleep(60)').format(str(pid_file)) + controller = ( + 'import sys; from pathlib import Path; sys.path.insert(0, {!r}); ' + 'from deepseek_v2_lite.utils import run_worker; ' + 'run_worker([sys.executable, "-c", {!r}], Path({!r}), 60)' + ).format(str(Path(utils.__file__).resolve().parents[1]), worker, str(tmp_path / 'worker.log')) + process = utils.subprocess.Popen([sys.executable, '-c', controller]) + try: + deadline = time.monotonic() + 5 + while not pid_file.exists() and time.monotonic() < deadline: + time.sleep(0.02) + assert pid_file.exists() + pid = int(pid_file.read_text()) + process.kill() + process.wait(timeout=5) + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + try: + os.kill(pid, 0) + except ProcessLookupError: + break + time.sleep(0.02) + else: + pytest.fail('The worker survived its controller.') + finally: + if process.poll() is None: + process.kill() + process.wait(timeout=5) + if pid_file.exists(): + try: + os.kill(int(pid_file.read_text()), signal.SIGKILL) + except ProcessLookupError: + pass + + +@pytest.fixture +def checkpoint_files(tmp_path, monkeypatch): + """Create small real files to test the checkpoint integrity contract.""" + root = tmp_path / 'checkpoint' + root.mkdir() + contents = b'CPU checkpoint integrity fixture' + shard = root / 'weights.safetensors' + shard.write_bytes(contents) + monkeypatch.setattr(utils, 'WEIGHT_FILES', { + shard.name: (len(contents), hashlib.sha256(contents).hexdigest()), + }) + utils.write_json(root / 'config.json', dict(utils.EXPECTED_CONFIG, model_type='deepseek_v2')) + utils.write_json(root / 'model.safetensors.index.json', {'weight_map': {'fixture.weight': shard.name}}) + return root, shard + + +@pytest.mark.parametrize('failure', ['missing', 'size', 'hash', 'index']) +def test_invalid_checkpoint_files_fail(checkpoint_files, failure): + """Corrupted, missing or misindexed shards must never become a valid checkpoint.""" + root, shard = checkpoint_files + if failure == 'missing': + shard.unlink() + elif failure == 'size': + shard.write_bytes(b'short') + elif failure == 'hash': + shard.write_bytes(b'x' * shard.stat().st_size) + else: + utils.write_json(root / 'model.safetensors.index.json', {'weight_map': {'fixture.weight': 'other'}}) + with pytest.raises(ValueError): + utils.verify_checkpoint(root) + + +def test_download_uses_pinned_public_identity_and_then_verifies(checkpoint_files, monkeypatch): + """Disable implicit credentials and reject a downloaded shard that fails verification.""" + root, shard = checkpoint_files + download = Mock() + monkeypatch.setitem(sys.modules, 'huggingface_hub', SimpleNamespace(snapshot_download=download)) + assert utils.download_checkpoint(root.parent) == root + arguments = download.call_args[1] + assert arguments['repo_id'] == utils.MODEL_ID + assert arguments['revision'] == utils.REVISION + assert arguments['token'] is False + assert arguments['local_dir'] == str(root) + assert shard.name in arguments['allow_patterns'] + download.side_effect = lambda **kwargs: shard.write_bytes(b'x' * shard.stat().st_size) + with pytest.raises(ValueError, match='SHA256'): + utils.download_checkpoint(root.parent) + + +@pytest.mark.parametrize('timeout', [0, -1, float('nan')]) +def test_invalid_worker_deadline_fails_before_launch(tmp_path, timeout): + """A nonfinite or expired budget must not start a worker.""" + with pytest.raises(TimeoutError): + utils.run_worker([sys.executable, '-c', 'pass'], tmp_path / 'worker.log', timeout) + + +def test_worker_interrupt_is_failure(): + """A termination request must unwind the worker's normal success path.""" + with pytest.raises(TimeoutError, match='interrupted'): + utils.interrupt_worker(signal.SIGTERM, None) + + +def test_supervisor_requires_kernel_ownership_support(monkeypatch): + """Fail before spawning when kernel ownership setup is unavailable.""" + monkeypatch.setattr(utils.signal, 'signal', Mock()) + monkeypatch.setattr(ctypes, 'CDLL', lambda *args, **kwargs: SimpleNamespace(prctl=lambda *args: -1)) + monkeypatch.setattr(ctypes, 'get_errno', lambda: 13) + spawn = Mock() + monkeypatch.setattr(utils.subprocess, 'Popen', spawn) + with pytest.raises(OSError): + utils.supervise_worker([sys.executable, '-c', 'pass'], 1, os.getppid()) + spawn.assert_not_called() + + +def test_timeout_survives_failed_descendant_cleanup(tmp_path, monkeypatch, capsys): + """A cleanup failure after the deadline stays a timeout and keeps its own details.""" + worker = SimpleNamespace(poll=lambda: None, wait=Mock()) + monkeypatch.setattr(utils.signal, 'signal', Mock()) + monkeypatch.setattr(ctypes, 'CDLL', lambda *args, **kwargs: SimpleNamespace(prctl=lambda *args: 0)) + monkeypatch.setattr(utils.subprocess, 'Popen', lambda command: worker) + monkeypatch.setattr(utils, '_stop_children', Mock(side_effect=RuntimeError('descendants did not exit: [4242]'))) + assert utils.supervise_worker([sys.executable, '-c', 'pass'], 0.05, os.getppid()) == 126 + assert '[4242]' in capsys.readouterr().err + worker.wait.assert_not_called() + supervisor = SimpleNamespace(wait=lambda timeout: 126, poll=lambda: 126) + monkeypatch.setattr(utils.subprocess, 'Popen', lambda *args, **kwargs: supervisor) + with pytest.raises(TimeoutError, match='deadline and its descendants did not exit'): + utils.run_worker([sys.executable, '-c', 'pass'], tmp_path / 'worker.log', 5) + + +@pytest.mark.parametrize( + 'environment, accepted', [ + ('', True), + ('PROC_RANK=0 WORLD_SIZE=1 OMPI_COMM_WORLD_SIZE=1', True), + ('PROC_RANK=1', False), + ('WORLD_SIZE=1 OMPI_COMM_WORLD_SIZE=8', False), + ('OMPI_COMM_WORLD_SIZE=1 WORLD_SIZE=2', False), + ('PROC_RANK=', False), + ] +) +def test_launcher_variables_are_checked_independently(environment, accepted): + """A local rank or any one distributed world size above one means another launcher.""" + variables = dict(item.split('=', 1) for item in environment.split()) + if accepted: + utils.validate_single_launcher(variables) + else: + with pytest.raises(ValueError, match='another launcher'): + utils.validate_single_launcher(variables) + + +# Per-run model cache removal. +def test_removes_only_the_run_cache(tmp_path): + """Delete the downloaded checkpoint while keeping the run's report and logs.""" + cache = tmp_path / 'cache' + (cache / 'checkpoint').mkdir(parents=True) + (cache / 'checkpoint' / 'model-00001-of-000004.safetensors').write_bytes(b'weights') + (tmp_path / 'report.json').write_text('{}') + cleanup.remove_model_cache(cache, time.monotonic() + 30) + assert not cache.exists() + assert (tmp_path / 'report.json').is_file() + + +def test_cleanup_does_not_start_without_budget(tmp_path, monkeypatch): + """Never start an unbounded deletion after the deadline.""" + run = Mock() + monkeypatch.setattr(cleanup.subprocess, 'run', run) + with pytest.raises(TimeoutError, match='No time remains'): + cleanup.remove_model_cache(tmp_path / 'cache', time.monotonic()) + run.assert_not_called() + + +@pytest.mark.parametrize( + 'failure', + [PermissionError('read-only cache'), + subprocess.CalledProcessError(1, ['cleanup'], output='read-only cache')] +) +def test_filesystem_errors_are_logged(tmp_path, monkeypatch, failure): + """Report a cleanup error without treating it as a failed measurement.""" + log_error = Mock() + monkeypatch.setattr(cleanup.subprocess, 'run', Mock(side_effect=failure)) + monkeypatch.setattr(cleanup.logger, 'error', log_error) + cleanup.remove_model_cache(tmp_path / 'cache', time.monotonic() + 30) + log_error.assert_called_once() + assert 'read-only cache' in str(log_error.call_args[0][-1]) + + +@pytest.mark.parametrize('interrupted', [False, True]) +def test_cleanup_timeout_reaps_its_process(tmp_path, monkeypatch, interrupted): + """Stop and reap a real stalled cleanup child on either its deadline or controller interruption.""" + cache = tmp_path / 'cache' + cache.mkdir() + children = [] + popen = subprocess.Popen + + def stalled_cleanup(command, **kwargs): + child = popen([sys.executable, '-c', 'import time; time.sleep(30)'], **kwargs) + children.append(child) + if interrupted: + monkeypatch.setattr(child, 'communicate', Mock(side_effect=TimeoutError('controller interrupted'))) + return child + + monkeypatch.setattr(cleanup.subprocess, 'Popen', stalled_cleanup) + start = time.monotonic() + try: + with pytest.raises(TimeoutError): + cleanup.remove_model_cache(cache, start + 0.25) + assert time.monotonic() - start < 3 + assert len(children) == 1 + assert children[0].returncode is not None + assert cache.is_dir() + finally: + for child in children: + if child.poll() is None: + child.kill() + child.wait(timeout=5) + + +@pytest.mark.parametrize('deadline,budget', [(400.0, cleanup.FAILURE_CLEANUP_GRACE_SECONDS), (1000.0, 500.0)]) +def test_failure_cleanup_uses_the_remaining_budget_or_grace(tmp_path, monkeypatch, deadline, budget): + """Give a failed run's cleanup the rest of its budget, or a fixed grace once that budget is spent.""" + run = Mock() + monkeypatch.setattr(cleanup, 'time', SimpleNamespace(monotonic=lambda: 500.0)) + monkeypatch.setattr(cleanup.subprocess, 'run', run) + cleanup.remove_model_cache_after_failure(tmp_path / 'cache', deadline) + assert run.call_args[1]['timeout'] == budget + + +@pytest.mark.parametrize( + 'failure', [subprocess.TimeoutExpired(['cleanup'], 1), + TimeoutError('Killed by SIGTERM or timeout!')] +) +def test_failure_cleanup_never_raises_a_timeout(tmp_path, monkeypatch, failure): + """Log an unfinished cleanup so that the failed run keeps its original error.""" + log_error = Mock() + monkeypatch.setattr(cleanup.subprocess, 'run', Mock(side_effect=failure)) + monkeypatch.setattr(cleanup.logger, 'error', log_error) + cleanup.remove_model_cache_after_failure(tmp_path / 'cache', time.monotonic()) + log_error.assert_called_once() + assert 'after a failed run' in log_error.call_args[0][0] + + +# Official-code reference. +@pytest.fixture +def reference(monkeypatch): + """Return the reference and redirect only test tensor creation to CPU.""" + tensor = torch.tensor + + def cpu_tensor(data, *args, **kwargs): + if kwargs.get('device') == 'cuda': + kwargs['device'] = 'cpu' + return tensor(data, *args, **kwargs) + + monkeypatch.setattr(torch, 'tensor', cpu_tensor) + return reference_module + + +class ReferenceFixture: + """Expose token-independent logits while checking cached attention shapes.""" + def __init__(self): + """Track cache and full-prefix calls separately.""" + self.calls = [] + + def eval(self): + """Retain the minimal evaluation interface used by the oracle.""" + return self + + def __call__(self, input_ids, attention_mask, past_key_values=None, use_cache=True): + """Require a mask for all past and current positions, including one-token decode.""" + length = input_ids.shape[1] + total = length + (past_key_values or 0) + assert attention_mask.shape == (1, total) + assert attention_mask.all().item() + self.calls.append((length, total, past_key_values, use_cache)) + logits = torch.tensor([0.0, 1.0, 2.0, 3.0]).reshape(1, 1, 4).repeat(1, length, 1) + return SimpleNamespace(logits=logits, past_key_values=total if use_cache else None) + + +def request_fixture(): + """Provide exact fixture probabilities rather than a model-quality claim.""" + probabilities = torch.tensor([0.0, 1.0, 2.0, 3.0]).log_softmax(-1).tolist() + return { + 'prompt_token_ids': [1, 2], + 'token_ids': [3, 3], + 'logprobs': [{str(index): value + for index, value in enumerate(probabilities)} for _ in range(2)], + } + + +def test_cached_decode_mask_covers_full_prefix(reference): + """The second cache call has one input token but a three-position mask.""" + model = ReferenceFixture() + result = reference.inference_reference(model, [request_fixture()]) + assert model.calls == [(2, 2, None, True), (2, 2, None, False), (1, 3, 2, True), (3, 3, None, False)] + assert len(result['comparisons']) == 2 + assert all(row['cache_max_abs_error'] == 0 for row in result['comparisons']) + + +@pytest.mark.parametrize('requests', [[], [{'prompt_token_ids': [], 'token_ids': [], 'logprobs': []}]]) +def test_incomplete_reference_requests_fail(reference, requests): + """Never accept an empty or truncated numerical workload.""" + with pytest.raises(ValueError, match='nonempty|Incomplete'): + reference.inference_reference(ReferenceFixture(), requests) + + +def test_reference_requires_greedy_token_agreement(reference): + """Finite probabilities alone must not certify an incorrect generated token.""" + request = request_fixture() + request['token_ids'][0] = 1 + with pytest.raises(RuntimeError, match='greedy token'): + reference.inference_reference(ReferenceFixture(), [request]) + + +def test_reference_does_not_ignore_probability_mismatch(reference): + """Keep the numerical gate even when all generated tokens are correct.""" + request = request_fixture() + request['logprobs'][0]['3'] += 1.0 + with pytest.raises(AssertionError, match='request 0 step 0'): + reference.inference_reference(ReferenceFixture(), [request]) + + +@pytest.mark.parametrize('positions', [[], [0], [1], [0, 0, 1], [1, 0], [0, 2], [False, 1]]) +def test_invalid_full_prefix_sampling_fails(reference, positions): + """Do not accept malformed or first/final-step-incomplete numerical evidence.""" + request = request_fixture() + request['full_prefix_steps'] = positions + with pytest.raises(ValueError, match='reference positions'): + reference.inference_reference(ReferenceFixture(), [request]) + + +class TrainingReferenceFixture: + """Small autograd fixture for global-batch partitioning, not GPU model validation.""" + def __init__(self): + """Create the named parameters required by reference sampling.""" + names = [ + 'model.embed_tokens.weight', + 'model.layers.0.self_attn.q_proj.weight', + 'model.layers.0.self_attn.kv_a_proj_with_mqa.weight', + 'model.layers.0.mlp.down_proj.weight', + 'model.layers.1.mlp.gate.weight', + 'model.layers.1.mlp.experts.0.down_proj.weight', + ] + self.parameters = {name: torch.nn.Parameter(torch.ones(2, 2)) for name in names} + self.batches = [] + self.checkpointing = False + + def train(self): + """Expose the reference model's training-mode interface.""" + return self + + def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs): + """Require the memory-bounded nonreentrant reference policy.""" + assert gradient_checkpointing_kwargs == {'use_reentrant': False} + self.checkpointing = True + + def named_parameters(self): + """Expose stable names for independently selected gradient probes.""" + return self.parameters.items() + + def get_parameter(self, name): + """Look up the same parameter on each logical rank batch.""" + return self.parameters[name] + + def zero_grad(self, set_to_none): + """Discard local gradients before the next reference batch.""" + assert set_to_none + for parameter in self.parameters.values(): + parameter.grad = None + + def __call__(self, input_ids, labels, use_cache): + """Produce input-dependent gradients that differ between rank batches.""" + assert not use_cache and torch.equal(input_ids, labels) + self.batches.append(input_ids.clone()) + loss = sum(parameter.sum() for parameter in self.parameters.values()) * input_ids.float().mean() + return SimpleNamespace(loss=loss) + + +def test_training_reference_averages_distinct_real_profile_rank_batches(reference, monkeypatch): + """Check different rank inputs and float32 gradient averaging rather than replicated tokens.""" + monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: ([[1, 2, 4, 8]], 16)) + model = TrainingReferenceFixture() + result = reference.training_reference(model, 'unused', batch_size=2, seq_len=32, world_size=3) + expected = torch.tensor(result['tokens']).float().mean().item() + assert model.checkpointing + assert len(result['tokens']) == 6 and all(len(row) == 32 for row in result['tokens']) + assert len(model.batches) == 3 and not torch.equal(model.batches[0], model.batches[1]) + assert result['world_size'] == 3 and result['batch_size'] == 2 and result['seq_len'] == 32 + assert result['loss'] == pytest.approx(sum(result['loss_per_rank']) / 3) + for probe in result['gradients'].values(): + assert probe['values'] == pytest.approx([expected] * len(probe['indices'])) + assert all(parameter.grad is None for parameter in model.parameters.values()) + + +def test_targeted_reference_matches_full_backward_without_unneeded_gradients(reference, monkeypatch): + """Preserve full-model derivatives while avoiding storage for unsampled parameter gradients.""" + documents = [[1, 2, 4, 8]] + monkeypatch.setattr(reference, 'fixed_documents', lambda checkpoint: (documents, 16)) + model = TrainingReferenceFixture() + ignored = torch.nn.Parameter(torch.tensor([2.0])) + model.parameters['model.layers.2.unprobed.weight'] = ignored + tokens = reference.packed_tokens(documents, 16, 32, 6) + expected = {} + for rank in range(2): + model.zero_grad(set_to_none=True) + inputs = torch.tensor(tokens[rank * 3:(rank + 1) * 3]) + model(input_ids=inputs, labels=inputs, use_cache=False).loss.backward() + for name, parameter in model.parameters.items(): + expected[name] = expected.get(name, torch.zeros_like(parameter)) + parameter.grad.detach() / 2 + model.zero_grad(set_to_none=True) + grad = Mock(wraps=torch.autograd.grad) + monkeypatch.setattr(torch.autograd, 'grad', grad) + result = reference.training_reference(model, 'unused', batch_size=3, seq_len=32, world_size=2) + assert grad.call_count == 2 + for call in grad.call_args_list: + assert all(parameter is not ignored for parameter in call[0][1]) + for name, probe in result['gradients'].items(): + assert probe['values'] == pytest.approx(expected[name].flatten()[probe['indices']].tolist()) + assert all(parameter.requires_grad and parameter.grad is None for parameter in model.parameters.values()) + + +@pytest.mark.parametrize('batch_size,seq_len,world_size', [(0, 32, 1), (1, 16, 1), (1, 32, 0)]) +def test_training_reference_rejects_invalid_profile(reference, batch_size, seq_len, world_size): + """Invalid global-batch definitions must fail before any model work.""" + with pytest.raises(ValueError, match='reference profile'): + reference.training_reference(TrainingReferenceFixture(), 'unused', batch_size, seq_len, world_size) + + +@pytest.fixture +def loading_contract(reference, tmp_path, monkeypatch): + """Mock library boundaries while exercising all loader identity checks.""" + if sys.version_info < (3, 10): + pytest.skip('The standalone model runtime requires Python 3.10 or later.') + import importlib.metadata + from superbench.benchmarks.model_benchmarks.deepseek_v2_lite.utils import EXPECTED_CONFIG + + (tmp_path / 'config.json').write_text(json.dumps(dict(EXPECTED_CONFIG, model_type='deepseek_v2'))) + parameter = SimpleNamespace(numel=lambda: reference.PARAMETER_COUNT, requires_grad=True) + model = SimpleNamespace(parameters=lambda: [parameter]) + loading = {key: [] for key in ['missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs']} + loader = Mock(return_value=(model, loading)) + tokenizer = SimpleNamespace(encode=Mock(return_value=[1, 2]), eos_token_id=9) + tokenizer_loader = Mock(return_value=tokenizer) + monkeypatch.setitem( + sys.modules, 'transformers', + SimpleNamespace( + AutoModelForCausalLM=SimpleNamespace(from_pretrained=loader), + AutoTokenizer=SimpleNamespace(from_pretrained=tokenizer_loader), + ) + ) + version = importlib.metadata.version + monkeypatch.setattr( + importlib.metadata, 'version', lambda name: '4.46.3' if name == 'transformers' else version(name) + ) + monkeypatch.setattr(torch.cuda, 'is_available', lambda: True) + return SimpleNamespace( + path=tmp_path, + model=model, + parameter=parameter, + loading=loading, + loader=loader, + tokenizer=tokenizer, + tokenizer_loader=tokenizer_loader, + ) + + +def test_official_loader_contract(reference, loading_contract): + """Require local official-code loading and complete loading diagnostics.""" + item = loading_contract + assert reference.load_model(str(item.path), torch.bfloat16) is item.model + options = item.loader.call_args[1] + assert options['torch_dtype'] == torch.bfloat16 + assert options['local_files_only'] and options['trust_remote_code'] and options['use_safetensors'] + assert options['attn_implementation'] == 'eager' and options['output_loading_info'] + documents, eos = reference.fixed_documents(str(item.path)) + assert len(documents) == len(reference.FIXED_TEXTS) and eos == 9 + assert item.tokenizer_loader.call_args[1]['local_files_only'] + assert item.tokenizer.encode.call_count == len(reference.FIXED_TEXTS) + + +@pytest.mark.parametrize('field', ['missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs']) +def test_loader_diagnostics_cannot_be_ignored(reference, loading_contract, field): + """Partial or incompatible loading must fail before reference execution.""" + loading_contract.loading[field] = ['invalid checkpoint'] + with pytest.raises(RuntimeError, match='checkpoint loading'): + reference.load_model(str(loading_contract.path), torch.bfloat16) + + +@pytest.mark.parametrize('failure', ['count', 'frozen', 'gpu', 'version']) +def test_loader_rejects_wrong_model_or_runtime(reference, loading_contract, monkeypatch, failure): + """Do not replace full-model GPU verification with a smaller or unsupported runtime.""" + item = loading_contract + if failure == 'count': + item.parameter.numel = lambda: 1 + elif failure == 'frozen': + item.parameter.requires_grad = False + elif failure == 'gpu': + monkeypatch.setattr(torch.cuda, 'is_available', lambda: False) + else: + import importlib.metadata + monkeypatch.setattr(importlib.metadata, 'version', lambda name: '0.0') + with pytest.raises(RuntimeError): + reference.load_model(str(item.path), torch.bfloat16) + + +@pytest.mark.parametrize('mode', ['training', 'inference']) +def test_reference_entrypoint_uses_expected_dtype_and_teardown(reference, tmp_path, monkeypatch, mode): + """Exercise orchestration with fake model work, not GPU numerical acceptance.""" + model = Mock() + model.cuda.return_value = model + loader = Mock(return_value=model) + monkeypatch.setattr(reference, 'load_model', loader) + monkeypatch.setattr(reference, 'training_reference', Mock(return_value={'loss': 1.0})) + monkeypatch.setattr(reference, 'inference_reference', Mock(return_value={'comparisons': []})) + monkeypatch.setattr(torch.cuda, 'set_device', Mock()) + monkeypatch.setattr(torch.cuda, 'synchronize', Mock()) + cleanup = Mock() + monkeypatch.setattr(torch.cuda, 'empty_cache', cleanup) + monkeypatch.setattr(torch.backends.cuda.matmul, 'allow_tf32', False) + monkeypatch.setenv('TORCH_ALLOW_TF32_CUBLAS_OVERRIDE', '0') + requests = tmp_path / 'requests.json' + requests.write_text('[]') + output = tmp_path / 'report.json' + monkeypatch.setattr( + sys, 'argv', [ + 'reference', + '--checkpoint', + str(tmp_path), + '--mode', + mode, + '--requests', + str(requests), + '--output', + str(output), + ] + ) + reference.main() + report = json.loads(output.read_text()) + expected = torch.bfloat16 if mode == 'training' else torch.float32 + assert loader.call_args[0][1] == expected + assert report['reference_dtype'] == str(expected) + assert report['correctness_passed'] and report['teardown_complete'] and not report['tf32_allowed'] + cleanup.assert_called_once() + + +def test_worker_environment_reaches_the_worker(tmp_path, monkeypatch): + """Put this package first on the worker search path and pass it through the supervisor.""" + monkeypatch.setenv('PYTHONPATH', 'existing') + expected = os.pathsep.join([str(Path(utils.__file__).resolve().parents[1]), 'existing']) + command = [sys.executable, '-c', 'import os, sys; assert os.environ["PYTHONPATH"] == sys.argv[1]', expected] + utils.run_worker(command, tmp_path / 'worker.log', 5, env=utils.worker_environment()) + + +def test_worker_modules_import_without_superbench(tmp_path): + """Worker interpreters lack SuperBench and site packages, so loading a worker module must need neither.""" + package = Path(utils.__file__).resolve().parent + # The cache helper uses the SuperBench logger and runs only in the adapter process. + names = sorted(path.stem for path in package.glob('*.py') if path.stem not in ('__init__', 'cache')) + assert {'reference', 'utils'} <= set(names) + code = ( + 'import importlib, sys; [importlib.import_module(name) for name in sys.argv[1:]]; ' + 'assert "superbench" not in sys.modules' + ) + modules = ['{}.{}'.format(package.name, name) for name in names] + utils.subprocess.run( + [sys.executable, '-S', '-c', code, *modules], env=utils.worker_environment(), cwd=str(tmp_path), check=True + ) diff --git a/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py b/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py new file mode 100644 index 000000000..fe6a95a96 --- /dev/null +++ b/tests/benchmarks/model_benchmarks/test_vllm_deepseek_v2_lite.py @@ -0,0 +1,1167 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""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 + +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 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.""" + 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), + ) + + +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(), + 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(tmp_path, parameters): + """Reject unsupported precisions, dimensions and multi-profile timing.""" + 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 + + +@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') + 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]), + ('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, env): + successful_worker(command, log, timeout, env) + output = Path(command[command.index('--output') + 1]) + report = adapter.read_json(output) + report[field] = value + write_json(output, report) + + monkeypatch.setattr(adapter, 'run_worker', invalid_worker) + assert not benchmark.run() + assert benchmark.return_code == ReturnCode.RUNTIME_EXCEPTION_ERROR + + +def test_deadline_failure(benchmark, monkeypatch): + """A watchdog exit cannot be reported as a successful under-hour run.""" + def timeout(command, log, seconds, env): + raise TimeoutError('whole job deadline') + + monkeypatch.setattr(adapter, 'run_worker', timeout) + assert not benchmark.run() + assert benchmark.return_code == ReturnCode.KILLED_BY_TIMEOUT + + +@pytest.mark.parametrize('outcome', ['success', 'failure', 'timeout']) +def test_model_cache_is_removed_after_every_run(benchmark, monkeypatch, outcome): + """Delete the per-run checkpoint cache on every exit path while keeping reports and logs.""" + jobs = [] + + def worker(command, log, timeout, env): + cache = Path(command[command.index('--cache_dir') + 1]) + (cache / 'checkpoint').mkdir(parents=True) + (cache / 'checkpoint' / 'model-00001-of-000004.safetensors').write_bytes(b'weights') + log.write_text('worker log\n') + jobs.append(cache.parent) + if outcome == 'failure': + raise RuntimeError('worker failed') + if outcome == 'timeout': + raise TimeoutError('whole job deadline') + successful_worker(command, log, timeout, env) + + monkeypatch.setattr(adapter, 'run_worker', worker) + assert benchmark.run() is (outcome == 'success') + assert not (jobs[0] / 'cache').exists() + assert (jobs[0] / 'worker.log').read_text() == 'worker log\n' + assert (jobs[0] / 'report.json').is_file() is (outcome == 'success') + + +@pytest.mark.parametrize('cleanup_seconds', [7, 50, 70]) +def test_cache_cleanup_counts_toward_the_job_deadline(benchmark, monkeypatch, cleanup_seconds): + """Include cleanup in elapsed time and reject the exact deadline as well as an overrun.""" + clock = [100.0] + run_cleanup = subprocess.run + + def worker(command, log, timeout, env): + assert timeout == 40 + Path(command[command.index('--cache_dir') + 1]).mkdir(parents=True) + successful_worker(command, log, timeout, env) + clock[0] += 10 + + def cleanup(command, **kwargs): + assert kwargs['timeout'] == 50 + result = run_cleanup(command, **kwargs) + clock[0] += cleanup_seconds + return result + + fake_time = SimpleNamespace(monotonic=lambda: clock[0]) + monkeypatch.setattr(adapter, 'time', fake_time) + monkeypatch.setattr(cache_cleanup, 'time', fake_time) + monkeypatch.setattr(adapter, 'run_worker', worker) + monkeypatch.setattr(cache_cleanup.subprocess, 'run', cleanup) + assert benchmark.run() is (cleanup_seconds < 50) + if cleanup_seconds < 50: + assert benchmark.return_code == ReturnCode.SUCCESS + assert benchmark.result['end_to_end_seconds'] == [10 + cleanup_seconds] + assert benchmark.result['bf16_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 + + +@pytest.mark.parametrize( + 'failure,code', [ + (RuntimeError('worker failed'), ReturnCode.RUNTIME_EXCEPTION_ERROR), + (TimeoutError('whole job deadline'), ReturnCode.KILLED_BY_TIMEOUT), + ] +) +def test_unfinished_failure_cleanup_keeps_the_original_error(benchmark, monkeypatch, failure, code): + """Report the worker failure rather than a later cleanup timeout, and log both.""" + log_error = Mock() + + def worker(command, log, timeout, env): + Path(command[command.index('--cache_dir') + 1]).mkdir(parents=True) + raise failure + + monkeypatch.setattr(adapter, 'run_worker', worker) + monkeypatch.setattr(cache_cleanup.subprocess, 'run', Mock(side_effect=subprocess.TimeoutExpired(['cleanup'], 1))) + monkeypatch.setattr(adapter.logger, 'error', log_error) + assert not benchmark.run() + assert benchmark.return_code == code + messages = [call[0][0] % call[0][1:] for call in log_error.call_args_list] + assert any(str(failure) in message for message in messages) + assert any('after a failed run' in message for message in messages) + + +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', '--cache_root "{}" --numerical_policy h100_bf16_v6'.format(tmp_path) + ) + 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, env): + 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 + + +# 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) 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 \