-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
benchmark.py
190 lines (131 loc) · 4.95 KB
/
benchmark.py
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import glob
import json
from fvcore.nn import FlopCountAnalysis, flop_count_table
import os.path
import typing
import typing
import warnings
from pprint import pprint
import numpy as np
import pytorch_lightning as pl
import torch
from pytorch_lightning.callbacks import RichModelSummary
from pytorch_lightning.profilers import AdvancedProfiler, PyTorchProfiler
from pytorch_lightning.strategies import DDPStrategy
from torch import nn
from torch.distributed import fsdp as fsdp_
from core import LightningSystem, data
from core.data.augmentation import StemAugmentor
from utils.config import dict_to_trainer_kwargs, read_nested_yaml
torch.set_float32_matmul_precision("medium")
from torch._dynamo import config
config.verbose = True
config.cache_size_limit = 1024
from typing import Any
import copy
import torchmetrics as tm
from pytorch_benchmark import benchmark
import pandas as pd
torch.backends.cudnn.benchmark = False
def fvcore(
config_path: str,
fs: int = 44100,
chunk_size_seconds: float = 6.0,
) -> None:
config = read_nested_yaml(config_path)
config_ = copy.deepcopy(config)
pprint(config)
pl.seed_everything(seed=config["seed"], workers=True)
model = LightningSystem(config["system"]).to("cuda")
dummy_inputs = {
"audio": {
"mixture": torch.randn((1, 1, int(fs * chunk_size_seconds))).to("cuda"),
}
}
flops = FlopCountAnalysis(model, dummy_inputs)
print(np.round(flops.total() / (1024**3), 1))
print(flop_count_table(flops))
def bench(
config_path: str,
fs: int = 44100,
chunk_size_seconds: float = 6.0,
device: str = "cpu",
) -> None:
config = read_nested_yaml(config_path)
config_ = copy.deepcopy(config)
pprint(config)
pl.seed_everything(seed=config["seed"], workers=True)
class Wrapper(nn.Module):
def __init__(self, model):
super().__init__()
self.model = model.to(device)
def forward(self, x):
return self.model({
"audio": {
"mixture": x.to(device)
}
})
model = LightningSystem(config["system"]).to(device)
model = Wrapper(model).to(device)
dummy_inputs = torch.randn((1, 1, int(fs * chunk_size_seconds))).to(device)
def transfer_to_device_fn(x, *args, **kwargs):
return x
# flops = model(dummy_inputs)
flops = benchmark(model, dummy_inputs, transfer_to_device_fn=transfer_to_device_fn)
basename = os.path.basename(config_path).split(".")[0]
if device != "cuda":
basename += f"-{device}"
with open(f"{os.environ['PROJECT_ROOT']}/benchmarks/{basename}.json", "w") as f:
json.dump(flops, f, indent=4)
# print(np.round(torch.cuda.max_memory_allocated() / 1024**3, 1))
def summary(benchmark_path: str = f"{os.environ['PROJECT_ROOT']}/benchmarks") -> None:
benches = glob.glob(f"{benchmark_path}/*.json")
dfs = []
for bench in benches:
with open(bench, "r") as f:
data = json.load(f)
if "cpu" in bench:
continue
model = bench.split("/")[-1].split(".")[0]
if "umx" in model:
model = "umx"
band = ""
nband = None
elif "demucs" in model:
model = "demucs"
band = ""
nband = None
elif "3s" in model:
band = model.split("3s-")[-1].split("-")[0]
nband = int(band[-2:]) if band != "vox7" else None
model = "bandit"
else:
model = "bsrnn" + ("-large" if "large" in model else "")
band = "vox7"
nband = None
# use flops from fvcore, not pytorch_benchmark
# pytorch_benchmark flops use ptops and might not be accurate for RNN
df = {
"model": model,
"band": band,
"nband": nband,
# "flops": data["flops"] / (1024 ** 3),
"params": data["params"] / (10**6),
"peak_memory": data["memory"]["batch_size_1"]["max_inference_bytes"] / (1024*1024),
f"batch_per_second_cuda": data["timing"]["batch_size_1"]["total"]["metrics"]["batches_per_second_mean"],
}
bench_cpu = bench.replace(".json", "-cpu.json")
if os.path.exists(bench_cpu):
with open(bench_cpu, "r") as f:
data = json.load(f)
df[f"batch_per_second_cpu"] = data["timing"]["batch_size_1"]["on_device_inference"]["metrics"]["batches_per_second_mean"]
dfs.append(df)
df = pd.DataFrame.from_records(dfs).sort_values(by=["model", "nband", "band"])
df[df["model"].isin(["bsrnn", "bsrnn-large"])][["params"]] *= 3
df["cuda_speedup"] = df["batch_per_second_cuda"] / df["batch_per_second_cpu"]
df.to_csv(f"{benchmark_path}/summary.csv", index=False)
df = df.drop(columns=["nband", "params"])
print(df.to_latex(index=False, float_format="%.2f"))
if __name__ == "__main__":
import fire
fire.Fire()