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 c7847d0a7..964abf1ea 100644 --- a/docs/user-tutorial/benchmarks/model-benchmarks.md +++ b/docs/user-tutorial/benchmarks/model-benchmarks.md @@ -201,3 +201,57 @@ below 3600 seconds and covers the whole job. | deepseek-v2-lite-training/bf16_train_gradient_norm | norm | The average global gradient norm before clipping. | | deepseek-v2-lite-training/end_to_end_seconds | time (s) | The complete job time, including checkpoint download and cache deletion. | | deepseek-v2-lite-training/checkpoint_bytes | size (bytes) | The total size of the checkpoint weight files. | + +## 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 c02c8e4ca..a8605cb34 100644 --- a/superbench/benchmarks/model_benchmarks/__init__.py +++ b/superbench/benchmarks/model_benchmarks/__init__.py @@ -12,10 +12,11 @@ from superbench.benchmarks.model_benchmarks.pytorch_llama import PytorchLlama from superbench.benchmarks.model_benchmarks.pytorch_mixtral import PytorchMixtral from superbench.benchmarks.model_benchmarks.pytorch_deepseek_v2_lite import DeepSeekV2LiteTraining +from superbench.benchmarks.model_benchmarks.vllm_deepseek_v2_lite import DeepSeekV2LiteInference __all__ = [ 'ModelBenchmark', 'PytorchBERT', 'PytorchGPT2', 'PytorchCNN', 'PytorchLSTM', 'MegatronGPT', 'PytorchLlama', - 'PytorchMixtral', 'DeepSeekV2LiteTraining' + 'PytorchMixtral', 'DeepSeekV2LiteTraining', 'DeepSeekV2LiteInference' ] if PytorchMixtral is not None: 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/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_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 01516bb12..11baf5ef3 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 @@ -273,6 +275,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 --retries 5 --timeout 120 --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 --retries 5 --timeout 120 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 --retries 5 --timeout 120 --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 \