Download gmnet/code/journal_exp/scripts/run_e12_profile.py from YFanwang/Backup: direct link, hf CLI and curl.
- Browser
- Download file 12.4 kB
-
https://huggingface.co/datasets/YFanwang/Backup/resolve/main/gmnet/code/journal_exp/scripts/run_e12_profile.py
- Command line
-
hf download hf://datasets/YFanwang/Backup/gmnet/code/journal_exp/scripts/run_e12_profile.py
-
curl -L -o run_e12_profile.py https://huggingface.co/datasets/YFanwang/Backup/resolve/main/gmnet/code/journal_exp/scripts/run_e12_profile.py
12.4 kB
| #!/usr/bin/env python3 | |
| """Profile GmNet-S3 inference without training or dataset access.""" | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import platform | |
| import sys | |
| import time | |
| from pathlib import Path | |
| from typing import Any | |
| import torch | |
| REPO_ROOT = Path(__file__).resolve().parents[1] | |
| if str(REPO_ROOT) not in sys.path: | |
| sys.path.insert(0, str(REPO_ROOT)) | |
| from gmnet.analysis import load_model_checkpoint | |
| from gmnet.analysis.profiling import benchmark_model | |
| from gmnet.analysis.profiling import percentile | |
| DEFAULT_CHECKPOINT = Path("/nfs/ywang29/GmNet/gmnet_s3.npy") | |
| DEFAULT_OUTPUT_DIR = Path("/tmp/gmnet_runs/e12_profile") | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--checkpoint", type=Path, default=DEFAULT_CHECKPOINT) | |
| parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR) | |
| parser.add_argument("--input-size", type=int, default=224) | |
| parser.add_argument("--cuda-device", default="cuda:0") | |
| parser.add_argument("--cuda-batches", type=int, nargs="+", default=[1, 32]) | |
| parser.add_argument( | |
| "--cuda-precisions", | |
| nargs="+", | |
| choices=("fp32", "bf16"), | |
| default=["fp32", "bf16"], | |
| ) | |
| parser.add_argument("--cuda-warmup", type=int, default=30) | |
| parser.add_argument("--cuda-iterations", type=int, default=100) | |
| parser.add_argument("--skip-cuda", action="store_true") | |
| parser.add_argument("--cpu", action="store_true") | |
| parser.add_argument("--cpu-batches", type=int, nargs="+", default=[1]) | |
| parser.add_argument("--cpu-precision", choices=("fp32", "bf16"), default="fp32") | |
| parser.add_argument("--cpu-warmup", type=int, default=5) | |
| parser.add_argument("--cpu-iterations", type=int, default=20) | |
| parser.add_argument("--cpu-threads", type=int, default=min(os.cpu_count() or 1, 16)) | |
| parser.add_argument("--onnx", action="store_true") | |
| parser.add_argument("--onnx-runtime", action="store_true") | |
| parser.add_argument("--onnx-opset", type=int, default=18) | |
| parser.add_argument("--onnx-warmup", type=int, default=10) | |
| parser.add_argument("--onnx-iterations", type=int, default=50) | |
| return parser.parse_args() | |
| def export_and_check_onnx( | |
| model: torch.nn.Module, | |
| *, | |
| destination: Path, | |
| input_size: int, | |
| opset: int, | |
| ) -> dict[str, Any]: | |
| import onnx | |
| destination.parent.mkdir(parents=True, exist_ok=True) | |
| model.eval().cpu() | |
| example = torch.randn(1, 3, input_size, input_size) | |
| torch.onnx.export( | |
| model, | |
| example, | |
| destination, | |
| input_names=["images"], | |
| output_names=["logits"], | |
| dynamic_axes={"images": {0: "batch"}, "logits": {0: "batch"}}, | |
| opset_version=opset, | |
| do_constant_folding=True, | |
| dynamo=False, | |
| ) | |
| graph = onnx.load(destination) | |
| onnx.checker.check_model(graph) | |
| return { | |
| "status": "checked", | |
| "path": str(destination), | |
| "size_bytes": destination.stat().st_size, | |
| "onnx_version": onnx.__version__, | |
| "opset": opset, | |
| "dynamic_batch": True, | |
| "checker": "passed", | |
| } | |
| def benchmark_onnxruntime( | |
| path: Path, | |
| *, | |
| model: torch.nn.Module, | |
| input_size: int, | |
| warmup_iterations: int, | |
| measured_iterations: int, | |
| threads: int, | |
| ) -> tuple[dict[str, Any], dict[str, Any]]: | |
| import numpy as np | |
| import onnxruntime as ort | |
| options = ort.SessionOptions() | |
| options.intra_op_num_threads = threads | |
| options.inter_op_num_threads = 1 | |
| session = ort.InferenceSession( | |
| str(path), | |
| sess_options=options, | |
| providers=["CPUExecutionProvider"], | |
| ) | |
| input_name = session.get_inputs()[0].name | |
| inputs = np.random.default_rng(20260712).standard_normal( | |
| (1, 3, input_size, input_size), dtype=np.float32 | |
| ) | |
| with torch.inference_mode(): | |
| torch_output = model(torch.from_numpy(inputs)).detach().cpu().numpy() | |
| ort_output = session.run(None, {input_name: inputs})[0] | |
| absolute_error = np.abs(torch_output - ort_output) | |
| for _ in range(warmup_iterations): | |
| session.run(None, {input_name: inputs}) | |
| timings = [] | |
| for _ in range(measured_iterations): | |
| started = time.perf_counter() | |
| outputs = session.run(None, {input_name: inputs}) | |
| timings.append((time.perf_counter() - started) * 1_000.0) | |
| if not np.isfinite(outputs[0]).all(): | |
| raise ValueError("ONNX Runtime produced non-finite output") | |
| mean_ms = sum(timings) / len(timings) | |
| measurement = { | |
| "device": "onnxruntime-cpu", | |
| "precision": "fp32", | |
| "batch_size": 1, | |
| "input_size": input_size, | |
| "warmup_iterations": warmup_iterations, | |
| "measured_iterations": measured_iterations, | |
| "latency_mean_ms": mean_ms, | |
| "latency_p50_ms": percentile(timings, 0.50), | |
| "latency_p95_ms": percentile(timings, 0.95), | |
| "throughput_mean_images_per_second": 1_000.0 / mean_ms, | |
| "throughput_at_p50_images_per_second": ( | |
| 1_000.0 / percentile(timings, 0.50) | |
| ), | |
| "peak_cuda_memory_mb": None, | |
| "current_cuda_memory_mb": None, | |
| } | |
| runtime = { | |
| "status": "completed", | |
| "onnxruntime_version": ort.__version__, | |
| "providers": session.get_providers(), | |
| "intra_op_threads": threads, | |
| "inter_op_threads": 1, | |
| "numerical_parity": { | |
| "max_absolute_error": float(absolute_error.max()), | |
| "mean_absolute_error": float(absolute_error.mean()), | |
| "top1_equal": bool( | |
| np.array_equal(torch_output.argmax(1), ort_output.argmax(1)) | |
| ), | |
| }, | |
| } | |
| return measurement, runtime | |
| def render_markdown(result: dict[str, Any]) -> str: | |
| rows = [] | |
| for measurement in result["measurements"]: | |
| peak = measurement["peak_cuda_memory_mb"] | |
| rows.append( | |
| f"| {measurement['device']} | {measurement['precision']} | " | |
| f"{measurement['batch_size']} | {measurement['latency_p50_ms']:.3f} | " | |
| f"{measurement['latency_p95_ms']:.3f} | " | |
| f"{measurement['throughput_mean_images_per_second']:.2f} | " | |
| f"{peak:.2f} |" if peak is not None else | |
| f"| {measurement['device']} | {measurement['precision']} | " | |
| f"{measurement['batch_size']} | {measurement['latency_p50_ms']:.3f} | " | |
| f"{measurement['latency_p95_ms']:.3f} | " | |
| f"{measurement['throughput_mean_images_per_second']:.2f} | n/a |" | |
| ) | |
| checkpoint = result["checkpoint"] | |
| onnx_audit = result["onnx"] | |
| runtime_audit = result["onnxruntime"] | |
| onnx_lines = [] | |
| if onnx_audit["status"] == "checked": | |
| onnx_lines.append( | |
| f"- ONNX: checker passed at opset {onnx_audit['opset']}; artifact " | |
| f"size is {onnx_audit['size_bytes']} bytes." | |
| ) | |
| if runtime_audit["status"] == "completed": | |
| parity = runtime_audit["numerical_parity"] | |
| onnx_lines.append( | |
| "- ONNX Runtime parity: max absolute error " | |
| f"{parity['max_absolute_error']:.6g}, top-1 equal " | |
| f"{parity['top1_equal']}." | |
| ) | |
| return "\n".join( | |
| [ | |
| "# E12 Local Inference Profile", | |
| "", | |
| f"- Checkpoint: `{checkpoint['path']}` (`{checkpoint['sha256']}`).", | |
| f"- Topology: `{checkpoint['selected_topology']}`.", | |
| "- Runtime: eager PyTorch, inference mode, random normalized-shape input.", | |
| "- CUDA measurements use CUDA events after warmup; CPU uses perf_counter.", | |
| *onnx_lines, | |
| "- INT8 is blocked: no validated full-model calibration/quantization " | |
| "pipeline is available.", | |
| "", | |
| "| Device | Precision | Batch | p50 (ms) | p95 (ms) | " | |
| "Mean throughput (image/s) | Peak CUDA memory (MiB) |", | |
| "|---|---|---:|---:|---:|---:|---:|", | |
| *rows, | |
| "", | |
| ] | |
| ) | |
| def main() -> int: | |
| args = parse_args() | |
| args.output_dir.mkdir(parents=True, exist_ok=True) | |
| measurements = [] | |
| checkpoint_audit: dict[str, Any] | None = None | |
| cpu_model: torch.nn.Module | None = None | |
| if not args.skip_cuda: | |
| if not torch.cuda.is_available(): | |
| raise RuntimeError("CUDA profiling requested but CUDA is unavailable") | |
| torch.backends.cudnn.benchmark = True | |
| model, checkpoint_audit = load_model_checkpoint( | |
| args.checkpoint, device=args.cuda_device | |
| ) | |
| for precision in args.cuda_precisions: | |
| for batch_size in args.cuda_batches: | |
| measurements.append( | |
| benchmark_model( | |
| model, | |
| device=args.cuda_device, | |
| batch_size=batch_size, | |
| input_size=args.input_size, | |
| precision=precision, | |
| warmup_iterations=args.cuda_warmup, | |
| measured_iterations=args.cuda_iterations, | |
| ) | |
| ) | |
| del model | |
| torch.cuda.empty_cache() | |
| if args.cpu: | |
| torch.set_num_threads(args.cpu_threads) | |
| cpu_model, cpu_audit = load_model_checkpoint(args.checkpoint, device="cpu") | |
| checkpoint_audit = checkpoint_audit or cpu_audit | |
| for batch_size in args.cpu_batches: | |
| measurements.append( | |
| benchmark_model( | |
| cpu_model, | |
| device="cpu", | |
| batch_size=batch_size, | |
| input_size=args.input_size, | |
| precision=args.cpu_precision, | |
| warmup_iterations=args.cpu_warmup, | |
| measured_iterations=args.cpu_iterations, | |
| ) | |
| ) | |
| onnx_audit: dict[str, Any] = {"status": "not_requested"} | |
| onnxruntime_audit: dict[str, Any] = {"status": "not_requested"} | |
| if args.onnx or args.onnx_runtime: | |
| if cpu_model is None: | |
| cpu_model, cpu_audit = load_model_checkpoint( | |
| args.checkpoint, device="cpu" | |
| ) | |
| checkpoint_audit = checkpoint_audit or cpu_audit | |
| onnx_path = args.output_dir / "gmnet_s3.onnx" | |
| onnx_audit = export_and_check_onnx( | |
| cpu_model, | |
| destination=onnx_path, | |
| input_size=args.input_size, | |
| opset=args.onnx_opset, | |
| ) | |
| if args.onnx_runtime: | |
| measurement, onnxruntime_audit = benchmark_onnxruntime( | |
| onnx_path, | |
| model=cpu_model, | |
| input_size=args.input_size, | |
| warmup_iterations=args.onnx_warmup, | |
| measured_iterations=args.onnx_iterations, | |
| threads=args.cpu_threads, | |
| ) | |
| measurements.append(measurement) | |
| if not measurements or checkpoint_audit is None: | |
| raise ValueError("no profiling target selected; enable CUDA or --cpu") | |
| result = { | |
| "schema_version": 1, | |
| "experiment": "E12", | |
| "status": "completed", | |
| "method": "eager_inference_cuda_events_or_cpu_perf_counter", | |
| "torch_version": torch.__version__, | |
| "cuda_version": torch.version.cuda, | |
| "cudnn_version": torch.backends.cudnn.version(), | |
| "python_version": platform.python_version(), | |
| "platform": platform.platform(), | |
| "cpu_count": os.cpu_count(), | |
| "cpu_threads_used": args.cpu_threads if args.cpu else None, | |
| "checkpoint": checkpoint_audit, | |
| "onnx": onnx_audit, | |
| "onnxruntime": onnxruntime_audit, | |
| "int8": { | |
| "status": "blocked", | |
| "reason": ( | |
| "No validated full-model INT8 calibration and quantization " | |
| "pipeline is available. Linear-only dynamic quantization is not " | |
| "reported as whole-model INT8." | |
| ), | |
| }, | |
| "measurements": measurements, | |
| } | |
| json_path = args.output_dir / "results.json" | |
| markdown_path = args.output_dir / "RESULTS.md" | |
| json_path.write_text(json.dumps(result, indent=2, sort_keys=True), encoding="utf-8") | |
| markdown_path.write_text(render_markdown(result), encoding="utf-8") | |
| print(json.dumps({"results": str(json_path), "markdown": str(markdown_path)})) | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |