Download scripts/audit_solutions.py from humanfia-lab/inference-kernels: direct link, hf CLI and curl.
- Browser
- Download file 16.2 kB
-
https://huggingface.co/datasets/humanfia-lab/inference-kernels/resolve/main/scripts/audit_solutions.py
- Command line
-
hf download hf://datasets/humanfia-lab/inference-kernels/scripts/audit_solutions.py
-
curl -L -o audit_solutions.py https://huggingface.co/datasets/humanfia-lab/inference-kernels/resolve/main/scripts/audit_solutions.py
16.2 kB
| """Validate and time actual solutions against independent task references.""" | |
| import argparse | |
| import contextlib | |
| import fcntl | |
| import hashlib | |
| import importlib.util | |
| import json | |
| import os | |
| from pathlib import Path | |
| import statistics | |
| import sys | |
| import time | |
| import traceback | |
| from task_acceptance import compare_output | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1]) | |
| parser.add_argument( | |
| "--data-root", type=Path, help="Optional materialized dataset with the same paths" | |
| ) | |
| parser.add_argument("--lock-directory", type=Path, required=True) | |
| parser.add_argument( | |
| "--cache-directory", type=Path, help="Writable module and reference cache" | |
| ) | |
| parser.add_argument("--definition", action="append") | |
| parser.add_argument("--suite", choices=["first", "dev", "all"], default="first") | |
| parser.add_argument("--only-default", action="store_true") | |
| parser.add_argument("--report", required=True, type=Path) | |
| parser.add_argument("--validation-only", action="store_true") | |
| parser.add_argument("--scale-probe", action="store_true") | |
| parser.add_argument("--gpu", required=True) | |
| parser.add_argument("--workload", action="append") | |
| parser.add_argument("--solution", action="append") | |
| parser.add_argument( | |
| "--candidate", | |
| action="append", | |
| default=[], | |
| help="Extra run() module for comparing a candidate on one selected definition", | |
| ) | |
| parser.add_argument("--reference-cache", action="store_true") | |
| parser.add_argument("--graph-timing", action="store_true") | |
| parser.add_argument( | |
| "--strict-diagnostic", | |
| action="store_true", | |
| help="Also report the historical FP32 bound for GDN; does not affect task acceptance", | |
| ) | |
| args = parser.parse_args() | |
| SOURCE = args.root.resolve() | |
| DATA = args.data_root.resolve() if args.data_root else SOURCE | |
| CACHE = ( | |
| args.cache_directory.resolve() | |
| if args.cache_directory | |
| else SOURCE / "results/audit-cache" | |
| ) | |
| GPU = args.gpu | |
| LOCKS = args.lock_directory | |
| LOCKS.mkdir(exist_ok=True, parents=True) | |
| os.environ["CUDA_VISIBLE_DEVICES"] = GPU | |
| stack = contextlib.ExitStack() | |
| for suffix in ["", ".lock"]: | |
| handle = stack.enter_context((LOCKS / (GPU + suffix)).open("a+")) | |
| fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) | |
| import torch | |
| from safetensors.torch import load_file | |
| torch.set_num_threads(8) | |
| torch.backends.cuda.matmul.allow_tf32 = False | |
| torch._inductor.config.compile_threads = 1 | |
| def load_function(name, path): | |
| identifier = "_audit_" + hashlib.sha256(name.encode()).hexdigest()[:20] | |
| package = path.parent | |
| spec = importlib.util.spec_from_file_location( | |
| identifier, package / "__init__.py", submodule_search_locations=[str(package)] | |
| ) | |
| if path.name != "main.py": | |
| spec = importlib.util.spec_from_file_location(identifier, path) | |
| module = importlib.util.module_from_spec(spec) | |
| sys.modules[identifier] = module | |
| spec.loader.exec_module(module) | |
| if path.name == "main.py": | |
| spec = importlib.util.spec_from_file_location(identifier + ".main", path) | |
| child = importlib.util.module_from_spec(spec) | |
| sys.modules[spec.name] = child | |
| spec.loader.exec_module(child) | |
| module = child | |
| return module.run, getattr(module, "prepare", None) | |
| def normalize(result, definition): | |
| return ( | |
| list(result.values()) | |
| if isinstance(result, dict) | |
| else list(result) | |
| if isinstance(result, (tuple, list)) | |
| else [result] | |
| ) | |
| def compare(actual, expected, definition, config): | |
| values = normalize(actual, definition) | |
| assert len(values) == len(expected) | |
| metrics = {} | |
| for name, value, reference in zip(definition["outputs"], values, expected): | |
| metrics[name] = compare_output(value, reference, config["tolerance"]) | |
| return metrics | |
| def measure(function, inputs, timing): | |
| for _ in range(timing["warmup"]): | |
| _result = function(*inputs) | |
| torch.cuda.synchronize() | |
| samples = [] | |
| for _ in range(timing["iters"] * timing["trials"]): | |
| start = torch.cuda.Event(enable_timing=True) | |
| end = torch.cuda.Event(enable_timing=True) | |
| start.record() | |
| _result = function(*inputs) | |
| end.record() | |
| end.synchronize() | |
| samples.append(start.elapsed_time(end) * 1000) | |
| return { | |
| "median_us": statistics.median(samples), | |
| "samples_us": samples, | |
| "method": "CUDA events over eager calls", | |
| } | |
| def measure_graph(function, inputs, timing, definition, config, expected): | |
| for _ in range(max(3, timing["warmup"])): | |
| result = function(*inputs) | |
| torch.cuda.synchronize() | |
| graph = torch.cuda.CUDAGraph() | |
| with torch.cuda.graph(graph): | |
| for _ in range(timing["iters"]): | |
| result = function(*inputs) | |
| graph.replay() | |
| torch.cuda.synchronize() | |
| compare(result, expected, definition, config) | |
| samples = [] | |
| for _ in range(timing["trials"]): | |
| start = torch.cuda.Event(enable_timing=True) | |
| end = torch.cuda.Event(enable_timing=True) | |
| start.record() | |
| graph.replay() | |
| end.record() | |
| end.synchronize() | |
| samples.append(start.elapsed_time(end) * 1000 / timing["iters"]) | |
| return { | |
| "median_us": statistics.median(samples), | |
| "samples_us": samples, | |
| "method": "CUDA graph, iters calls per replay", | |
| "calls_per_replay": timing["iters"], | |
| } | |
| definitions = { | |
| json.loads(f.read_text())["name"]: json.loads(f.read_text()) | |
| for f in (SOURCE / "definitions").rglob("*.json") | |
| } | |
| solutions = {} | |
| for f in (SOURCE / "solutions").rglob("*.json"): | |
| s = json.loads(f.read_text()) | |
| solutions.setdefault(s["definition"], []).append(s) | |
| rows_by_name = { | |
| f.stem: [json.loads(l)["workload"] for l in f.read_text().splitlines()] | |
| for f in (SOURCE / "workloads").rglob("*.jsonl") | |
| } | |
| args.report.parent.mkdir(exist_ok=True, parents=True) | |
| failures = 0 | |
| with args.report.open("w") as report, torch.inference_mode(): | |
| def emit(row): | |
| report.write(json.dumps(row) + "\n") | |
| report.flush() | |
| emit( | |
| { | |
| "type": "environment", | |
| "gpu": torch.cuda.get_device_name(), | |
| "torch": torch.__version__, | |
| "suite": args.suite, | |
| "pythonpath": os.environ.get("PYTHONPATH"), | |
| "started_at": time.time(), | |
| } | |
| ) | |
| for name, definition in definitions.items(): | |
| if args.definition and name not in args.definition: | |
| continue | |
| config = json.loads((SOURCE / "tasks" / f"{name}.json").read_text()) | |
| rows = rows_by_name[name] | |
| if args.suite == "dev": | |
| rows = [row for row in rows if row["uuid"] in config["dev"]] | |
| if args.suite == "first": | |
| rows = rows[:1] | |
| if args.workload: | |
| rows = [row for row in rows if row["uuid"] in args.workload] | |
| candidates = [] | |
| for solution in solutions[name]: | |
| if args.only_default and solution["name"] == "sglang_" + name: | |
| continue | |
| digest = hashlib.sha256( | |
| json.dumps(solution, sort_keys=True).encode() | |
| ).hexdigest() | |
| package = CACHE / "modules" / digest | |
| for source in solution["sources"]: | |
| target = package / source["path"] | |
| if not target.resolve().is_relative_to(package.resolve()): | |
| raise ValueError("Source path escapes package") | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| target.write_text(source["content"]) | |
| (package / "__init__.py").touch() | |
| entry = solution["spec"]["entry_point"].split("::")[0] | |
| candidates.append((solution["name"], package / entry)) | |
| if args.candidate: | |
| assert args.definition and len(args.definition) == 1 | |
| candidates.extend((Path(p).stem, Path(p)) for p in args.candidate) | |
| if args.solution: | |
| candidates = [(s, p) for s, p in candidates if s in args.solution] | |
| ns = {} | |
| exec(definition["reference"], ns) | |
| reference = ns["run"] | |
| for solution, path in candidates: | |
| try: | |
| function, prepare = load_function(solution, path) | |
| except Exception: | |
| failures += 1 | |
| emit( | |
| { | |
| "type": "load", | |
| "definition": name, | |
| "solution": solution, | |
| "status": "failed", | |
| "error": traceback.format_exc(), | |
| } | |
| ) | |
| print("LOAD FAILED", name, solution, flush=True) | |
| continue | |
| for row in rows: | |
| inputs = [] | |
| saved = [] | |
| expected = [] | |
| result = { | |
| "type": "workload", | |
| "definition": name, | |
| "solution": solution, | |
| "uuid": row["uuid"], | |
| "axes": row["axes"], | |
| "solution_sha256": hashlib.sha256(path.read_bytes()).hexdigest(), | |
| "definition_sha256": hashlib.sha256( | |
| json.dumps(definition, sort_keys=True).encode() | |
| ).hexdigest(), | |
| "task_sha256": hashlib.sha256( | |
| json.dumps(config, sort_keys=True).encode() | |
| ).hexdigest(), | |
| } | |
| try: | |
| for key in definition["inputs"]: | |
| desc = row["inputs"][key] | |
| value = ( | |
| desc["value"] | |
| if desc["type"] == "scalar" | |
| else load_file(str(DATA / desc["path"]), device="cuda")[ | |
| desc["tensor_key"] | |
| ] | |
| ) | |
| inputs.append(value) | |
| saved.append( | |
| value.clone() if isinstance(value, torch.Tensor) else value | |
| ) | |
| cache_key = hashlib.sha256( | |
| json.dumps( | |
| { | |
| "reference": definition["reference"], | |
| "row": row, | |
| "torch": torch.__version__, | |
| }, | |
| sort_keys=True, | |
| ).encode() | |
| ).hexdigest() | |
| cache = CACHE / "references" / (cache_key + ".pt") | |
| if args.reference_cache and cache.exists(): | |
| expected = [ | |
| value.to("cuda") | |
| for value in torch.load(cache, weights_only=True) | |
| ] | |
| else: | |
| expected = [ | |
| value.clone() | |
| for value in normalize(reference(*inputs), definition) | |
| ] | |
| if args.reference_cache: | |
| cache.parent.mkdir(exist_ok=True, parents=True) | |
| torch.save([value.cpu() for value in expected], cache) | |
| actual_result = function(*inputs) | |
| result["errors"] = compare( | |
| actual_result, expected, definition, config | |
| ) | |
| if args.strict_diagnostic and name.startswith("gdn_"): | |
| result["strict_fp32_diagnostic"] = {} | |
| for key, value, target in zip( | |
| definition["outputs"], | |
| normalize(actual_result, definition), | |
| expected, | |
| ): | |
| if value.dtype == torch.float32: | |
| close = torch.isclose( | |
| value, target, rtol=1e-4, atol=2e-5 | |
| ) | |
| result["strict_fp32_diagnostic"][key] = { | |
| "rtol": 1e-4, | |
| "atol": 2e-5, | |
| "mismatched_elements": int((~close).sum()), | |
| "elements": close.numel(), | |
| "passes": bool(close.all()), | |
| } | |
| for key, value, original in zip( | |
| definition["inputs"], inputs, saved | |
| ): | |
| if isinstance(value, torch.Tensor): | |
| assert torch.equal( | |
| value.contiguous().view(torch.uint8), | |
| original.contiguous().view(torch.uint8), | |
| ), key + " input mutated" | |
| if args.scale_probe and "scale" in definition["inputs"]: | |
| index = list(definition["inputs"]).index("scale") | |
| original = inputs[index] | |
| inputs[index] = ( | |
| definition["axes"]["head_size"]["value"] ** -0.5 | |
| if original is None or original == 0 | |
| else original | |
| ) * 0.5 | |
| target = [ | |
| value.clone() | |
| for value in normalize(reference(*inputs), definition) | |
| ] | |
| result["scale_probe"] = compare( | |
| function(*inputs), target, definition, config | |
| ) | |
| inputs[index] = original | |
| if not args.validation_only: | |
| result["run_timing"] = measure( | |
| function, inputs, config["timing"] | |
| ) | |
| if prepare: | |
| launch = prepare(*inputs) | |
| result["prepared_timing"] = measure( | |
| lambda *unused: launch(), inputs, config["timing"] | |
| ) | |
| if args.graph_timing: | |
| try: | |
| launch_function = ( | |
| (lambda *unused: launch()) if prepare else function | |
| ) | |
| result["graph_timing"] = measure_graph( | |
| launch_function, | |
| inputs, | |
| config["timing"], | |
| definition, | |
| config, | |
| expected, | |
| ) | |
| except Exception: | |
| result["graph_error"] = traceback.format_exc() | |
| for key, value, original in zip( | |
| definition["inputs"], inputs, saved | |
| ): | |
| if isinstance(value, torch.Tensor): | |
| assert torch.equal( | |
| value.contiguous().view(torch.uint8), | |
| original.contiguous().view(torch.uint8), | |
| ), key + " input mutated during timing" | |
| result["inputs_unchanged"] = True | |
| result["status"] = "passed" | |
| except Exception: | |
| failures += 1 | |
| result.update(status="failed", error=traceback.format_exc()) | |
| emit(result) | |
| print( | |
| result["status"], | |
| name, | |
| solution, | |
| row["axes"], | |
| result.get("run_timing", {}).get("median_us"), | |
| flush=True, | |
| ) | |
| inputs = saved = expected = actual_result = None | |
| function = prepare = None | |
| if failures: | |
| raise SystemExit(f"{failures} failed cases; see {args.report}") | |