File size: 3,779 Bytes
5d12def
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
"""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()