"""Run W1-01 on this host and write reports/w1_01_infra_report.json.""" import argparse import asyncio from contextlib import contextmanager import csv from datetime import datetime, timedelta, timezone import importlib import json import os from pathlib import Path import random import re import signal import socket from statistics import mean import subprocess import sys import time from prepare_models import MODELS, ROOT, digest REPORTS = ROOT / "reports" BENCH_MODEL = "Qwen2.5-14B-Instruct" CONCURRENCY = 64 REQUESTS = 128 INPUT_TOKENS = 2048 OUTPUT_TOKENS = 256 def smi(*arguments): return subprocess.check_output(["nvidia-smi", *arguments], text=True, timeout=30) def inspect_gpu(report): columns = ("index", "name", "memory.total", "memory.used", "driver_version", "uuid", "pci.bus_id") output = smi("--query-gpu=" + ",".join(columns), "--format=csv,noheader,nounits") topology = re.sub(r"\x1b\[[0-9;]*m", "", smi("topo", "-m")) processes = smi("--query-compute-apps=pid,gpu_uuid,used_memory", "--format=csv,noheader,nounits") print(output, topology, f"Compute processes before tests: {processes.strip() or 'none'}", sep="\n", flush=True) cards = [] for index, name, total, used, driver, uuid, pci in csv.reader(output.splitlines(), skipinitialspace=True): cards.append({ "index": int(index), "model": name, "memory_mib": int(total), "memory_used_before_tests_mib": int(used), "driver_version": driver, "uuid": uuid, "pci_bus_id": pci, }) cards.sort(key=lambda card: card["index"]) peers = [line.split()[1:1 + len(cards)] for line in topology.splitlines() if re.match(r"^GPU\d+\s+", line)] links = {link for row in peers for link in row if link != "X"} interconnect = ( "NVLink" if links and all(link.startswith("NV") for link in links) else "Mixed" if any(link.startswith("NV") for link in links) else "PCIe" if links else None ) report.update( gpu_count=len(cards), gpus=cards, gpu_topology=topology, gpu_model_and_vram_gb=", ".join( f"GPU {card['index']}: {card['model']} {card['memory_mib'] / 1024:.2f} GiB" for card in cards ), interconnect_type=interconnect, compute_processes_before_tests=processes.splitlines(), gpu_idle_at_start=not processes.strip(), eight_a100_present=len(cards) == 8 and all("A100" in card["model"] for card in cards), ) return cards def nccl_worker(): import torch import torch.distributed as dist rank = int(os.environ["LOCAL_RANK"]) torch.cuda.set_device(rank) dist.init_process_group("nccl", timeout=timedelta(seconds=90)) try: tensor = torch.full((1024 * 1024,), rank + 1, dtype=torch.float32, device=f"cuda:{rank}") dist.all_reduce(tensor) torch.cuda.synchronize() expected = dist.get_world_size() * (dist.get_world_size() + 1) // 2 torch.testing.assert_close(tensor, torch.full_like(tensor, expected), rtol=0, atol=0) print(f"rank {rank}: 1,048,576 values equal {expected}", flush=True) finally: dist.destroy_process_group() def child_env(cards, *, vllm=False): device_ids = (str(card["index"]) if vllm else card["uuid"] for card in cards) env = dict( os.environ, CUDA_VISIBLE_DEVICES=",".join(device_ids), CUDA_DEVICE_ORDER="PCI_BUS_ID", VLLM_USE_MODELSCOPE="false", HF_HUB_OFFLINE="1", TRANSFORMERS_OFFLINE="1", HF_DATASETS_OFFLINE="1", OMP_NUM_THREADS="1", ) # Triton compiles a C extension at server startup. Use local venv headers when present. include = Path(sys.prefix) / "include" / f"python{sys.version_info.major}.{sys.version_info.minor}" if vllm and (include / "Python.h").is_file(): for name in ("C_INCLUDE_PATH", "CPLUS_INCLUDE_PATH"): paths = [str(include), env.get(name)] env[name] = os.pathsep.join(path for path in paths if path) return env def training_probe(cards, report): import torch from packaging.version import Version versions = {"python": sys.version.split()[0], "torch": torch.__version__, "cuda": torch.version.cuda, "nccl": list(torch.cuda.nccl.version())} report.update( runtime_versions=versions, cuda_and_torch_version=f"CUDA {versions['cuda']}, torch {versions['torch']}", torch_cuda_device_count=torch.cuda.device_count(), torch_compute_capabilities=[ list(torch.cuda.get_device_capability(index)) for index in range(torch.cuda.device_count()) ], ) print(f"Runtime: {versions}; torch sees {torch.cuda.device_count()} GPUs", flush=True) imports = {} for name in ("verl", "ray", "flash_attn", "duckdb", "accelerate", "vllm", "pyarrow", "polars", "pandas", "scipy", "networkx", "pytest"): try: module = importlib.import_module(name) imports[name] = {"pass": True, "version": getattr(module, "__version__", None)} except Exception as error: imports[name] = {"pass": False, "error": repr(error)} report["dependency_imports"] = imports print(f"Dependency imports: {json.dumps(imports)}", flush=True) report["runtime_requirements_pass"] = ( sys.version_info[:2] in ((3, 10), (3, 11)) and Version(versions["cuda"]) >= Version("12.1") and Version(versions["torch"]) >= Version("2.4.0") and imports["vllm"]["pass"] and Version(imports["vllm"]["version"]) >= Version("0.6.3") and torch.cuda.device_count() == len(cards) == 8 ) report["verl_and_flash_attn_import_pass"] = all( imports[name]["pass"] for name in ("verl", "ray", "flash_attn", "duckdb") ) for index in range(torch.cuda.device_count()): values = torch.ones((1024 * 1024,), device=f"cuda:{index}") assert values.sum().item() == 1024 * 1024 del values report["gpu_tensor_allocation_pass"] = torch.cuda.device_count() == 8 if imports["flash_attn"]["pass"]: from flash_attn import flash_attn_func query = torch.ones((1, 32, 2, 64), dtype=torch.float16, device="cuda:0") output = flash_attn_func(query, query, query) torch.testing.assert_close(output, query) report["flash_attention_kernel_pass"] = True for index in range(torch.cuda.device_count()): with torch.cuda.device(index): torch.cuda.empty_cache() def check_model_files(model): path = ROOT / "models" / model manifest = json.loads((path / "SHA256SUMS.json").read_text()) if manifest["repo"] != f"Qwen/{model}": raise ValueError(f"Wrong repository in manifest for {model}") entries = {entry["name"]: entry for entry in manifest["files"]} index = json.loads((path / "model.safetensors.index.json").read_text()) shards = set(index["weight_map"].values()) if not shards or not shards.issubset(entries): raise ValueError(f"Safetensor shards missing from manifest for {model}") for entry in entries.values(): file = path / entry["name"] if file.stat().st_size != entry["size"] or digest(file, "sha256") != entry["sha256"]: raise ValueError(f"Wrong size or SHA256 for {file}") return {"revision": manifest["revision"], "sha256_pass": True, "weight_shards": len(shards)} def free_port(): with socket.socket() as server: server.bind(("127.0.0.1", 0)) return server.getsockname()[1] @contextmanager def serve(model, cards, benchmark=False): import httpx port = free_port() base = f"http://127.0.0.1:{port}" path = ROOT / "models" / model log_path = REPORTS / f"vllm-{model}.log" command = [ sys.executable, "-m", "vllm.entrypoints.openai.api_server", "--host", "127.0.0.1", "--port", str(port), "--model", str(path), "--served-model-name", model, "--tensor-parallel-size", str(len(cards)), "--distributed-executor-backend", "mp", "--dtype", "bfloat16", "--generation-config", "vllm", "--max-model-len", str(INPUT_TOKENS + OUTPUT_TOKENS), "--max-num-seqs", str(CONCURRENCY if benchmark else 8), "--max-num-batched-tokens", "8192", "--gpu-memory-utilization", "0.85", "--enable-prefix-caching", "--enable-auto-tool-choice", "--tool-call-parser", "hermes", ] print(f"Starting {model} TP={len(cards)} on GPUs {[c['index'] for c in cards]}. Log: {log_path}", flush=True) with log_path.open("w") as log, httpx.Client(trust_env=False, timeout=5) as client: log.write(f"{' '.join(command)}\n") log.flush() process = subprocess.Popen( command, stdout=log, stderr=subprocess.STDOUT, env=child_env(cards, vllm=True), start_new_session=True, ) try: deadline = time.monotonic() + 1800 while time.monotonic() < deadline: if process.poll() is not None: raise RuntimeError(f"{model} server exited {process.returncode}; see {log_path}") try: if client.get(f"{base}/health").is_success: break except httpx.TransportError: pass time.sleep(2) else: raise TimeoutError(f"{model} startup timed out; see {log_path}") yield base finally: try: os.killpg(process.pid, signal.SIGTERM) process.wait(timeout=30) except subprocess.TimeoutExpired: os.killpg(process.pid, signal.SIGKILL) process.wait() except ProcessLookupError: process.wait() def generate(base, model): import httpx with httpx.Client(trust_env=False, timeout=120) as client: response = client.post(f"{base}/v1/chat/completions", json={ "model": model, "messages": [ {"role": "user", "content": "Write one short sentence explaining what a GPU does."}, ], "max_tokens": 32, "temperature": 0, }) response.raise_for_status() result = response.json() content = result["choices"][0]["message"]["content"] if not content or not content.strip() or result["usage"]["completion_tokens"] <= 0: raise ValueError(f"{model} produced no text") print(f"Offline generation {model}: {content!r}", flush=True) return content def tool_check(base, model): import httpx with httpx.Client(trust_env=False, timeout=120) as client: response = client.post(f"{base}/v1/chat/completions", json={ "model": model, "messages": [ {"role": "user", "content": "Call get_weather for Shanghai. Use the tool now."}, ], "tools": [{"type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a city.", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}, }}], "tool_choice": "auto", "temperature": 0, "max_tokens": 96, }) response.raise_for_status() choice = response.json()["choices"][0] for call in choice["message"].get("tool_calls") or []: function = call["function"] if function["name"] == "get_weather" and "shanghai" in json.loads(function["arguments"])["city"].lower(): print(f"OpenAI automatic tool calling: {function}", flush=True) return True raise ValueError(f"Expected parsed get_weather call, received {choice}") async def run_benchmark(base): import httpx from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained(ROOT / "models" / BENCH_MODEL, local_files_only=True) vocabulary = sorted(token_id for token, token_id in tokenizer.get_vocab().items() if re.fullmatch(r"[A-Za-z]{3,9}", token)) rng = random.Random(101) prefixes = rng.sample(vocabulary, REQUESTS) prompts = [ [prefix] + rng.choices(vocabulary, k=INPUT_TOKENS - 1) for prefix in prefixes ] semaphore = asyncio.Semaphore(CONCURRENCY) limits = httpx.Limits(max_connections=CONCURRENCY, max_keepalive_connections=CONCURRENCY) async with httpx.AsyncClient(trust_env=False, timeout=180, limits=limits) as client: async def request(prompt): async with semaphore: start = time.perf_counter() first_text = None usage = None async with client.stream("POST", f"{base}/v1/completions", json={ "model": BENCH_MODEL, "prompt": prompt, "add_special_tokens": False, "max_tokens": OUTPUT_TOKENS, "ignore_eos": True, "temperature": 0, "stream": True, "stream_options": {"include_usage": True}, }) as response: if not response.is_success: raise RuntimeError(f"HTTP {response.status_code}: {await response.aread()!r}") async for line in response.aiter_lines(): if not line.startswith("data: ") or line == "data: [DONE]": continue event = json.loads(line[6:]) if "error" in event: raise RuntimeError(event["error"]) if first_text is None and any(c.get("text") for c in event.get("choices", [])): first_text = time.perf_counter() if event.get("usage"): usage = event["usage"] if first_text is None or usage is None: raise ValueError("Stream was missing first text or server-side token counts") if usage["prompt_tokens"] != INPUT_TOKENS or usage["completion_tokens"] != OUTPUT_TOKENS: raise ValueError(f"Unexpected per-request token counts: {usage}") return (first_text - start) * 1000, usage["completion_tokens"] started = time.perf_counter() outcomes = await asyncio.gather(*(request(prompt) for prompt in prompts), return_exceptions=True) elapsed = time.perf_counter() - started successes = [item for item in outcomes if isinstance(item, tuple)] errors = [str(item) for item in outcomes if isinstance(item, BaseException)] total_tokens = sum(tokens for _, tokens in successes) return { "concurrency": CONCURRENCY, "requests": REQUESTS, "successful_requests": len(successes), "input_tokens_per_request": INPUT_TOKENS, "output_tokens_per_request": OUTPUT_TOKENS, "prefix_caching_enabled": True, "prompt_design": "Seeded token IDs with unique first tokens", "tensor_parallel_size": 4, "gpu_indices": [0, 1, 2, 3], "wall_time_sec": round(elapsed, 4), "total_output_tokens": total_tokens, "mean_ttft_ms": round(mean(ttft for ttft, _ in successes), 3) if successes else None, "output_throughput_tokens_per_sec": round(total_tokens / elapsed, 3), "request_error_count": len(errors), "example_request_errors": errors[:10], } def main(): import traceback parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--hardware-only", action="store_true", help="Run hardware, NCCL and dependency probes.") parser.add_argument("--wait-for-lock-seconds", type=int, default=0, help="Wait for concurrent dependency installation before probing imports.") args = parser.parse_args() if args.wait_for_lock_seconds < 0: parser.error("--wait-for-lock-seconds must be nonnegative") if args.hardware_only: name = "w1_01_hardware_probe.json" else: name = "w1_01_infra_report.json" report = { "started_utc": datetime.now(timezone.utc).isoformat(), "gpu_count": None, "gpu_model_and_vram_gb": None, "interconnect_type": None, "cuda_and_torch_version": None, "nccl_8gpu_allreduce_pass": False, "verl_and_flash_attn_import_pass": False, "gpu_tensor_allocation_pass": False, "flash_attention_kernel_pass": False, "dependency_imports": {}, "models_verified": [], "model_details": {}, "openai_tool_calling_pass": False, "errors": {}, "vllm_4gpu_14b_benchmark": { "concurrency": CONCURRENCY, "mean_ttft_ms": None, "output_throughput_tokens_per_sec": None, }, } def record_error(stage, error): report["errors"][stage] = str(error) traceback.print_exc() try: cards = inspect_gpu(report) if len(cards) != 8 or not report["gpu_idle_at_start"]: raise RuntimeError("Eight visible GPUs without active compute processes are required for execution.") env = child_env(cards) os.environ["CUDA_VISIBLE_DEVICES"] = env["CUDA_VISIBLE_DEVICES"] try: subprocess.run([ sys.executable, "-m", "torch.distributed.run", "--standalone", "--nnodes=1", "--nproc-per-node=8", str(Path(__file__).resolve()), "--nccl-worker", ], check=True, env=env, timeout=180) report["nccl_8gpu_allreduce_pass"] = True except Exception as error: record_error("nccl", error) if not args.hardware_only: for model in MODELS: try: report["model_details"][model] = check_model_files(model) print(f"SHA256 verified: {model}", flush=True) is_benchmark = model == BENCH_MODEL with serve(model, cards[:1] if model == "Qwen2.5-7B-Instruct" else cards[:4], benchmark=is_benchmark) as base: report["model_details"][model]["offline_generation"] = generate(base, model) report["models_verified"].append(model) if is_benchmark: try: report["openai_tool_calling_pass"] = tool_check(base, model) except Exception as error: record_error("openai_tool_calling", error) report["vllm_4gpu_14b_benchmark"] = asyncio.run(run_benchmark(base)) except Exception as error: record_error(model, error) lock = ROOT / "envs" / "requirements_lock.txt" if args.wait_for_lock_seconds and not lock.is_file(): print("GPU and model probes finished. Waiting for the dependency lock before import checks.", flush=True) deadline = time.monotonic() + args.wait_for_lock_seconds while not lock.is_file() and time.monotonic() < deadline: time.sleep(5) try: training_probe(cards, report) except Exception as error: record_error("training_probe", error) except Exception as error: record_error("hardware", error) benchmark = report["vllm_4gpu_14b_benchmark"] log_path = REPORTS / f"vllm-{BENCH_MODEL}.log" if not args.hardware_only and log_path.exists(): benchmark["oom_detected"] = bool(re.search( r"out of memory|outofmemoryerror|CUBLAS_STATUS_ALLOC_FAILED", log_path.read_text(errors="replace"), re.IGNORECASE, )) benchmark["throughput_pass"] = ( benchmark.get("successful_requests") == REQUESTS and benchmark["output_throughput_tokens_per_sec"] >= 2000 and not benchmark.get("oom_detected") ) report["requirements_lock_present"] = (ROOT / "envs" / "requirements_lock.txt").is_file() report["w1_01_pass"] = ( not args.hardware_only and not report["errors"] and report.get("eight_a100_present", False) and report["nccl_8gpu_allreduce_pass"] and report.get("runtime_requirements_pass", False) and report["gpu_tensor_allocation_pass"] and report["flash_attention_kernel_pass"] and all(item["pass"] for item in report["dependency_imports"].values()) and set(report["models_verified"]) == set(MODELS) and report["openai_tool_calling_pass"] and benchmark["throughput_pass"] and report["requirements_lock_present"] ) if not args.hardware_only: report["acceptance_summary"] = { "eight_idle_a100_and_nccl": bool( report.get("eight_a100_present") and report.get("gpu_idle_at_start") and report["nccl_8gpu_allreduce_pass"] ), "three_models_offline": set(report["models_verified"]) == set(MODELS), "benchmark_at_least_2000_tokens_per_sec_no_oom": benchmark["throughput_pass"], "dependency_lock": report["requirements_lock_present"], } report["finished_utc"] = datetime.now(timezone.utc).isoformat() REPORTS.mkdir(exist_ok=True) path = REPORTS / name temp = path.with_suffix(".tmp") temp.write_text(json.dumps(report, indent=2) + "\n") temp.replace(path) print(f"Report: {path}", flush=True) print(json.dumps(report, indent=2), flush=True) return 0 if report["w1_01_pass"] or ( args.hardware_only and not report["errors"] and report["nccl_8gpu_allreduce_pass"] ) else 1 if __name__ == "__main__": if sys.argv[1:] == ["--nccl-worker"]: nccl_worker() else: raise SystemExit(main())