gpu-kernel-benchmark / kernel_bench /memory_profile.py
code-roamer's picture
Publish GPU Kernel Benchmark v0.8.1 public edition
5d12def verified
Raw History Blame Contribute Delete
3.78 kB
"""Fresh-process allocator accounting, including submission-owned persistent buffers."""
import argparse
import gc
import json
from pathlib import Path
import torch
def synchronize_collect():
gc.collect()
torch.cuda.synchronize()
def storage_map(values):
if isinstance(values, torch.Tensor):
storage = values.untyped_storage()
return {storage.data_ptr(): storage.nbytes()}
result = {}
if isinstance(values, (tuple, list)):
for value in values:
result.update(storage_map(value))
return result
def profile(factory, inputs, warmup=6):
"""Call in a fresh process after allocating inputs but before loading submission.
Total added = retained allocations + steady-call peak above the warmed allocator.
Input storage is excluded from output bytes; output aliases count only once.
Native allocations outside PyTorch and graph-private pools are not included.
"""
synchronize_collect()
origin = torch.cuda.memory_allocated()
fn = factory()
synchronize_collect()
imported = torch.cuda.memory_allocated()
retained = []
for _ in range(warmup):
out = fn(*inputs)
torch.cuda.synchronize()
del out
synchronize_collect()
retained.append(torch.cuda.memory_allocated() - origin)
before = torch.cuda.memory_allocated()
torch.cuda.reset_peak_memory_stats()
out = fn(*inputs)
torch.cuda.synchronize()
peak = torch.cuda.max_memory_allocated()
output_storages, input_storages = storage_map(out), storage_map(inputs)
result = {
"scope": "fresh-process PyTorch allocator; warmed kernel call; no CUDA Graph pools or native CUDA allocations",
"input_storage_bytes": sum(input_storages.values()),
"import_retained_bytes": imported - origin,
"warmup_retained_bytes": retained,
"persistent_after_warmup_bytes": before - origin,
"steady_incremental_peak_bytes": peak - before,
"steady_total_added_peak_bytes": peak - origin,
"output_new_storage_bytes": sum(size for ptr, size in output_storages.items() if ptr not in input_storages),
"output_aliases_input": bool(output_storages.keys() & input_storages.keys()),
}
del out
synchronize_collect()
result["retained_after_call_bytes"] = torch.cuda.memory_allocated() - origin
result["retained_growth_last_call_bytes"] = result["retained_after_call_bytes"] - retained[-1]
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--candidate", required=True)
parser.add_argument("--implementation", choices=["baseline", "candidate"], required=True)
parser.add_argument("--case-json", type=Path, required=True)
parser.add_argument("--seed", type=int, required=True)
parser.add_argument("--out", type=Path, required=True)
args = parser.parse_args()
from . import baselines
from .evaluate import load_candidate
from .tasks import make_inputs
from .__main__ import write_json
case = json.loads(args.case_json.read_text())
torch.cuda.set_device(0)
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = False
with torch.inference_mode():
inputs = make_inputs(case, args.seed)
factory = (lambda: baselines.resolve(case)[0]) if args.implementation == "baseline" else (
lambda: load_candidate(args.candidate, case["task"]))
result = profile(factory, inputs)
write_json(args.out, {"status": "passed", "implementation": args.implementation,
"case_id": case["id"], "seed": args.seed, **result})
if __name__ == "__main__":
main()