-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathserve-imagenet-dir
executable file
·161 lines (136 loc) · 4.18 KB
/
serve-imagenet-dir
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
#!/usr/bin/python3
import argparse
import logging
import multiprocessing
import os
import sys
import numpy as np
from tensorcom import zcom
import torch
from torchvision import datasets, transforms
logger = logging.getLogger()
logger.setLevel(logging.INFO)
parser = argparse.ArgumentParser(
"""
Serve the Imagenet dataset for training.
By default, data is served as tuples (img, cls), where
img is a (batch, h, w, channel) array of type uint8
and cls is a (batch,) array of type int32.
The batch size can be adjusted using the `-b` argument.
This program uses the PyTorch data loader, but still
uses NumPy conventions for actually serving the data.
Usage:
"""
)
parser.add_argument("service_address", nargs="*")
parser.add_argument(
"-d",
"--dir",
default="./imagenet",
help="directory containing the ImagenNet dataset",
)
parser.add_argument(
"-b",
"--batch-size",
type=int,
default=32,
help="batch the input (default is no batching)",
)
parser.add_argument(
"-r", "--report", type=int, default=10, help="report on progress this frequently"
)
parser.add_argument(
"-B",
"--benchmark",
action="store_true",
help="eliminate I/O overhead by just preloading and serving one sample",
)
parser.add_argument(
"-w", "--workers", type=int, default=0, help="number of DataLoader workers"
)
parser.add_argument(
"-P",
"--parallel",
type=int,
default=0,
help="spawn multiple subprocesses for parallel I/O",
)
parser.add_argument("-S", "--no-shuffle", action="store_false")
parser.add_argument("-n", "--normalize", action="store_true")
args = parser.parse_args()
if args.service_address == []:
args.service_address = ["zpub://127.0.0.1:7880"]
if args.parallel > 0:
assert len(args.service_address) == 1
assert args.service_address[0].startswith("zpush") or args.service_address[
0
].startswith("zrpub")
args.service_address = args.service_address * args.parallel
logger.info("service:", args.service_address)
def fixtype(a):
if isinstance(a, (int, float, str)):
return a
if isinstance(a, np.ndarray):
if a.dtype == np.int64:
return a.astype(np.int32)
if a.dtype == np.float64:
return a.astype(np.float32)
return a
def start_server(con, report=args.report):
logger.info("starting server")
serve = zcom.Connection(con)
logger.info("loading dataset")
traindir = os.path.join(args.dir, "train")
valdir = os.path.join(args.dir, "val")
if args.normalize:
normalize = transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
)
train_dataset = datasets.ImageFolder(
traindir,
transforms.Compose(
[
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
]
),
)
else:
train_dataset = datasets.ImageFolder(
traindir,
transforms.Compose(
[
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
lambda x: (255 * x).type(torch.uint8),
]
),
)
logger.info("creating dataloader")
train_loader = torch.utils.data.DataLoader(
train_dataset,
batch_size=args.batch_size,
shuffle=not args.no_shuffle,
num_workers=args.workers,
pin_memory=False,
)
for i, (img, cls) in enumerate(train_loader):
if i % report == 0:
print(i, serve.stats.summary())
sys.stdout.flush()
img = img.permute(0, 2, 3, 1).numpy()
cls = cls.type(torch.int32).numpy() - 1
if i == 0:
print(img.shape, img.dtype, np.amin(img), np.amax(img))
print(cls.shape, cls.dtype)
serve.send([img, cls])
if len(args.service_address) == 1:
start_server(args.service_address[0])
else:
nproc = len(args.service_address)
pool = multiprocessing.Pool(nproc)
print(pool)
pool.map(start_server, args.service_address)