File size: 1,564 Bytes
745627a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Pytest plugin: per-test wall time (setup/call/teardown) and peak CUDA memory, written as JSONL.

Load with `-p profile_plugin` (directory on PYTHONPATH). Output path: $PROFILE_OUT. Extra metadata copied into every
row: $PROFILE_META (JSON object). Peak memory covers the PyTorch allocator of the pytest process only (not vLLM servers
or `accelerate launch` subprocesses).
"""

import json
import os

import pytest
import torch


_rows = []
_meta = json.loads(os.environ.get("PROFILE_META", "{}"))


@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_protocol(item, nextitem):
    row = {"nodeid": item.nodeid, "file": item.nodeid.split("::")[0], "outcome": "passed"}
    item._profile_row = row
    torch.cuda.reset_peak_memory_stats()
    yield
    row["peak_alloc_mib"] = torch.cuda.max_memory_allocated() / 2**20
    row["peak_reserved_mib"] = torch.cuda.max_memory_reserved() / 2**20
    row["total_s"] = sum(row.get(f"{when}_s", 0.0) for when in ("setup", "call", "teardown"))
    _rows.append({**_meta, **row})


@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    report = outcome.get_result()
    row = item._profile_row
    row[f"{report.when}_s"] = report.duration
    if report.outcome != "passed" and row["outcome"] == "passed":
        row["outcome"] = report.outcome if report.when == "call" or report.skipped else "error"


def pytest_sessionfinish(session, exitstatus):
    with open(os.environ["PROFILE_OUT"], "w") as f:
        for row in _rows:
            f.write(json.dumps(row) + "\n")