-
Notifications
You must be signed in to change notification settings - Fork 19
/
AsyncIterator.lua
282 lines (236 loc) · 7.72 KB
/
AsyncIterator.lua
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
------------------------------------------------------------------------
--[[ AsyncIterator ]]--
-- Decorates a DataLoader to make it multi-threaded.
------------------------------------------------------------------------
local dl = require 'dataload._env'
local AsyncIterator, parent = torch.class('dl.AsyncIterator', 'dl.DataLoader', dl)
function AsyncIterator:__init(dataset, nthread, verbose, serialmode, threadInit)
self.dataset = dataset
assert(torch.isTypeOf(self.dataset, "dl.DataLoader"))
self.nthread = nthread or 2
self.verbose = verbose == 'nil' and true or verbose
self.serialmode = serialmode or 'ascii'
assert(self.serialmode == "ascii" or self.serialmode == "binary","Serial mode can only be acsii or binary")
threadInit = threadInit or function() end
assert(torch.type(threadInit) == 'function')
-- reset that shouldn't be shared by threads
self.dataset:reset()
-- upvalues should be local
local verbose = self.verbose
local datasetstr = torch.serialize(dataset, self.serialmode)
local mainSeed = os.time()
-- the torch threads library handles the multi-threading for us
local threads = require 'threads'
-- so that the tensors don't get serialized, i.e. threads share them
threads.Threads.serialization('threads.sharedserialize')
-- build a Threads pool
self.threads = threads.Threads(
nthread, -- the following functions are executed in each thread
function()
dl = require 'dataload'
end,
threadInit,
function(idx)
local success, err = pcall(function()
t = {}
t.id = idx
local seed = mainSeed + idx
math.randomseed(seed)
torch.manualSeed(seed)
if verbose then
print(string.format('Starting worker thread with id: %d seed: %d', t.id, seed))
end
-- dataset is serialized in main thread and deserialized in dataset
t.dataset = torch.deserialize(datasetstr,self.serialmode)
end)
if not success then
print(err)
error""
end
end
)
self.recvqueue = torchx.Queue()
self.ninprogress = 0
end
function AsyncIterator:forceCollectGarbage()
-- Collect garbage in all worker threads
self.threads:synchronize()
self.threads:specific(true)
for threadId=1,self.nthread do
self.threads:addjob(threadId, function()
collectgarbage()
end)
end
self.threads:synchronize()
self.threads:specific(false)
-- Collect garbage in main thread
collectgarbage()
end
function AsyncIterator:collectgarbage()
self.gcdelay = self.gcdelay or 50
self.gccount = (self.gccount or 0) + 1
if self.gccount >= self.gcdelay then
self:forceCollectGarbage()
self.gccount = 0
end
end
function AsyncIterator:synchronize()
self.threads:synchronize()
while not self.recvqueue:empty() do
self.recvqueue:get()
end
self.ninprogress = 0
self.querymode = nil
self:forceCollectGarbage()
end
function AsyncIterator:reset()
self:synchronize()
parent.reset(self)
end
-- send request to worker : put request into queue
function AsyncIterator:asyncPut(fn, args, size)
assert(torch.type(fn) == 'string')
assert(torch.type(args) == 'table')
assert(torch.type(size) == 'number') -- size of batch
for i=1,1000 do
if self.threads:acceptsjob() then
break
else
sys.sleep(0.01)
end
if i==1000 then
error"infinite loop"
end
end
self.ninprogress = (self.ninprogress or 0) + 1
self.threads:addjob(
-- the job callback (runs in data-worker thread)
function()
local success, res = pcall(function()
-- fn, args and size are upvalues
local res = {t.dataset[fn](t.dataset, unpack(args))}
res.size = size
return res
end)
if not success then
print(res)
error""
end
return res
end,
-- the endcallback (runs in the main thread)
function(res)
assert(torch.type(res) == 'table')
self.recvqueue:put(res)
self.ninprogress = self.ninprogress - 1
end
)
end
-- recv results from worker : get results from queue
function AsyncIterator:asyncGet()
-- necessary because Threads:addjob sometimes calls dojob...
if self.recvqueue:empty() then
self.threads:dojob()
end
assert(not self.recvqueue:empty())
return self.recvqueue:get()
end
-- iterators : subiter, samplepairs
-- subiter : for iterating over validation and test sets.
-- Note batches are not necessarily returned in order (because asynchronous)
function AsyncIterator:subiter(batchsize, epochsize, ...)
batchsize = batchsize or 32
local dots = {...}
-- empty the async queue
self:synchronize()
self.querymode = 'subiter'
local size = self:size()
epochsize = epochsize or self:size()
self._start = self._start or 1
local nput = 0
local nget = 0 -- nsampled
local stop
local previnputs, prevtargets
local putOnly = true
-- build iterator
local iterate = function()
assert(self.querymode == 'subiter', "Can only support one iterator per synchronize()")
if nget >= epochsize then
return
end
-- asynchronously send (put) a task to a worker to be retrieved (get)
-- by a later iteration
if nput < epochsize then
local bs = math.min(nput+batchsize, epochsize) - nput
stop = math.min(self._start + bs - 1, size)
bs = stop - self._start + 1
-- if possible, reuse buffers previnputs and prevtargets
self:asyncPut('sub', {self._start, stop, previnputs, prevtargets, unpack(dots)}, bs)
nput = nput + bs
self._start = self._start + bs
if self._start >= size then
self._start = 1
end
end
if not putOnly then
local batch = self:asyncGet()
-- we will resend these buffers to the workers next call
previnputs, prevtargets = batch[1], batch[2]
nget = nget + batch.size
self:collectgarbage()
return nget, unpack(batch)
end
end
-- fill task queue with some batch requests
for tidx=1,self.nthread do
iterate()
end
putOnly = false
return iterate
end
function AsyncIterator:sampleiter(batchsize, epochsize, ...)
batchsize = batchsize or 32
local dots = {...}
-- empty the async queue
self:synchronize()
self.querymode = 'sampleiter'
local size = self:size()
epochsize = epochsize or self:size()
local nput = 0
local nget = 0 -- nsampled
local stop
local previnputs, prevtargets
local putOnly = true
-- build iterator
local iterate = function()
assert(self.querymode == 'sampleiter', "Can only support one iterator per synchronize()")
if nget >= epochsize then
return
end
-- asynchronously send (put) a task to a worker to be retrieved (get)
-- by a later iteration
if nput < epochsize then
local bs = math.min(nput+batchsize, epochsize) - nput
-- if possible, reuse buffers previnputs and prevtargets
self:asyncPut('sample', {bs, previnputs, prevtargets, unpack(dots)}, bs)
nput = nput + bs
end
if not putOnly then
local batch = self:asyncGet()
-- we will resend these buffers to the workers next call
previnputs, prevtargets = batch[1], batch[2]
nget = nget + batch.size
self:collectgarbage()
return nget, unpack(batch)
end
end
-- fill task queue with some batch requests
for tidx=1,self.nthread do
iterate()
end
putOnly = false
return iterate
end
function AsyncIterator:size(...)
return self.dataset:size(...)
end