forked from microsoft/torchgeo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
benchmark.py
executable file
·293 lines (254 loc) · 8.25 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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
#!/usr/bin/env python3
"""dataset and sampler benchmarking script."""
import argparse
import csv
import os
import time
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision.models import resnet34
from torchgeo.datasets import CDL, Landsat8, stack_samples
from torchgeo.samplers import GridGeoSampler, RandomBatchGeoSampler, RandomGeoSampler
def set_up_parser() -> argparse.ArgumentParser:
"""Set up the argument parser.
Returns:
the argument parser
"""
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument(
"--landsat-root",
default=os.path.join("data", "landsat"),
help="directory containing Landsat data",
metavar="ROOT",
)
parser.add_argument(
"--cdl-root",
default=os.path.join("data", "cdl"),
help="directory containing CDL data",
metavar="ROOT",
)
parser.add_argument(
"-d", "--device", default=0, type=int, help="CPU/GPU ID to use", metavar="ID"
)
parser.add_argument(
"-c",
"--cache",
action="store_true",
help="cache file handles during data loading",
)
parser.add_argument(
"-b",
"--batch-size",
default=2 ** 4,
type=int,
help="number of samples in each mini-batch",
metavar="SIZE",
)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
"-n",
"--num-batches",
type=int,
help="number of batches to load",
metavar="SIZE",
)
group.add_argument(
"-e",
"--epoch-size",
type=int,
help="number of samples to load, should be evenly divisible by batch size",
metavar="SIZE",
)
parser.add_argument(
"-p",
"--patch-size",
default=224,
type=int,
help="height/width of each patch",
metavar="SIZE",
)
parser.add_argument(
"-s",
"--stride",
default=112,
type=int,
help="sampling stride for GridGeoSampler",
)
parser.add_argument(
"-w",
"--num-workers",
default=0,
type=int,
help="number of workers for parallel data loading",
metavar="NUM",
)
parser.add_argument(
"--seed", default=0, type=int, help="random seed for reproducibility"
)
parser.add_argument(
"--output-fn",
default="benchmark-results.csv",
type=str,
help="path to the CSV file to write results",
metavar="FILE",
)
parser.add_argument(
"-v", "--verbose", action="store_true", help="print results to stdout"
)
return parser
def main(args: argparse.Namespace) -> None:
"""High-level pipeline.
Benchmarks performance of various samplers with and without caching.
Args:
args: command-line arguments
"""
bands = ["B1", "B2", "B3", "B4", "B5", "B6", "B7"]
# Benchmark samplers
# Initialize datasets
cdl = CDL(args.cdl_root, cache=args.cache)
landsat = Landsat8(
args.landsat_root, crs=cdl.crs, res=cdl.res, cache=args.cache, bands=bands
)
dataset = landsat & cdl
# Initialize samplers
if args.epoch_size:
length = args.epoch_size
num_batches = args.epoch_size // args.batch_size
elif args.num_batches:
length = args.num_batches * args.batch_size
num_batches = args.num_batches
# Convert from pixel coords to CRS coords
size = args.patch_size * cdl.res
stride = args.stride * cdl.res
samplers = [
RandomGeoSampler(landsat, size=size, length=length),
GridGeoSampler(landsat, size=size, stride=stride),
RandomBatchGeoSampler(
landsat, size=size, batch_size=args.batch_size, length=length
),
]
results_rows = []
for sampler in samplers:
if args.verbose:
print(f"\n{sampler.__class__.__name__}:")
if isinstance(sampler, RandomBatchGeoSampler):
dataloader = DataLoader(
dataset,
batch_sampler=sampler,
num_workers=args.num_workers,
collate_fn=stack_samples,
)
else:
dataloader = DataLoader(
dataset,
batch_size=args.batch_size,
sampler=sampler, # type: ignore[arg-type]
num_workers=args.num_workers,
collate_fn=stack_samples,
)
tic = time.time()
num_total_patches = 0
for i, batch in enumerate(dataloader):
num_total_patches += args.batch_size
# This is to stop the GridGeoSampler from enumerating everything
if i == num_batches - 1:
break
toc = time.time()
duration = toc - tic
if args.verbose:
print(f" duration: {duration:.3f} sec")
print(f" count: {num_total_patches} patches")
print(f" rate: {num_total_patches / duration:.3f} patches/sec")
if args.cache:
if args.verbose:
print(landsat._cached_load_warp_file.cache_info())
# Clear cache for fair comparison between samplers
# Both `landsat` and `cdl` share the same cache
landsat._cached_load_warp_file.cache_clear()
results_rows.append(
{
"cached": args.cache,
"seed": args.seed,
"duration": duration,
"count": num_total_patches,
"rate": num_total_patches / duration,
"sampler": sampler.__class__.__name__,
"batch_size": args.batch_size,
"num_workers": args.num_workers,
}
)
# Benchmark model
model = resnet34()
# Change number of input channels to match Landsat
model.conv1 = nn.Conv2d( # type: ignore[attr-defined]
len(bands), 64, kernel_size=7, stride=2, padding=3, bias=False
)
criterion = nn.CrossEntropyLoss() # type: ignore[attr-defined]
params = model.parameters()
optimizer = optim.SGD(params, lr=0.0001)
device = torch.device( # type: ignore[attr-defined]
"cuda" if torch.cuda.is_available() else "cpu", args.device
)
model = model.to(device)
tic = time.time()
num_total_patches = 0
for _ in range(num_batches):
num_total_patches += args.batch_size
x = torch.rand(args.batch_size, len(bands), args.patch_size, args.patch_size)
# y = torch.randint(0, 256, (args.batch_size, args.patch_size, args.patch_size))
y = torch.randint(0, 256, (args.batch_size,)) # type: ignore[attr-defined]
x = x.to(device)
y = y.to(device)
optimizer.zero_grad()
prediction = model(x)
loss = criterion(prediction, y)
loss.backward()
optimizer.step()
toc = time.time()
duration = toc - tic
if args.verbose:
print("\nResNet-34:")
print(f" duration: {duration:.3f} sec")
print(f" count: {num_total_patches} patches")
print(f" rate: {num_total_patches / duration:.3f} patches/sec")
results_rows.append(
{
"cached": args.cache,
"seed": args.seed,
"duration": duration,
"count": num_total_patches,
"rate": num_total_patches / duration,
"sampler": "ResNet-34",
"batch_size": args.batch_size,
"num_workers": args.num_workers,
}
)
fieldnames = [
"cached",
"seed",
"duration",
"count",
"rate",
"sampler",
"batch_size",
"num_workers",
]
if not os.path.exists(args.output_fn):
with open(args.output_fn, "w") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
with open(args.output_fn, "a") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writerows(results_rows)
if __name__ == "__main__":
parser = set_up_parser()
args = parser.parse_args()
if args.epoch_size:
assert args.epoch_size % args.batch_size == 0
pl.seed_everything(args.seed)
main(args)