-
Notifications
You must be signed in to change notification settings - Fork 47
/
parallel_easy.py
346 lines (285 loc) · 10.8 KB
/
parallel_easy.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
"""
Functions to assist in parallel processing with Python 2.7.
* Memory-friendly iterator functionality (wrapping Pool.imap).
* Exit with Ctrl-C.
* Easy use of n_jobs. (e.g. when n_jobs == 1, processing is serial)
* Similar to joblib.Parallel but with the addition of imap functionality
and a more effective way of handling Ctrl-C exit (we add a timeout).
"""
import itertools
from multiprocessing import Pool, cpu_count
from multiprocessing.pool import IMapUnorderedIterator, IMapIterator
import cPickle
import sys
###############################################################################
# Globals
###############################################################################
# Used as the timeout
GOOGLE = 1e100
###############################################################################
# Functions
###############################################################################
def imap_easy(func, iterable, n_jobs, chunksize, ordered=True):
"""
Returns a parallel iterator of func over iterable.
Worker processes return one "chunk" of data at a time, and the iterator
allows you to deal with each chunk as they come back, so memory can be
handled efficiently.
Parameters
----------
func : Function of one variable
You can use functools.partial to build this.
A lambda function will not work
iterable : List, iterator, etc...
func is applied to this
n_jobs : Integer
The number of jobs to use for the computation. If -1 all CPUs are used.
If 1 is given, no parallel computing code is used at all, which is
useful for debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are
used. Thus for n_jobs = -2, all CPUs but one are used.
chunksize : Integer
Jobs/results will be sent between master/slave processes in chunks of
size chunksize. If chunksize is too small, communication overhead
slows things down. If chunksize is too large, one process ends up
doing too much work (and large results will up in memory).
ordered : Boolean
If True, results are dished out in the order corresponding to iterable.
If False, results are dished out in whatever order workers return them.
Examples
--------
>>> from functools import partial
>>> from rosetta.parallel.parallel_easy import imap_easy
>>> def abfunc(x, a, b=1):
... return x * a * b
>>> some_numbers = range(3)
>>> func = partial(abfunc, 2, b=3)
>>> results_iterator = imap_easy(func, some_numbers, 2, 5)
>>> for result in results_iterator:
... print result
0
6
12
"""
n_jobs = _n_jobs_wrap(n_jobs)
if n_jobs == 1:
results_iter = itertools.imap(func, iterable)
else:
_trypickle(func)
pool = Pool(n_jobs)
if ordered:
results_iter = pool.imap(func, iterable, chunksize=chunksize)
else:
results_iter = pool.imap_unordered(
func, iterable, chunksize=chunksize)
return results_iter
def map_easy(func, iterable, n_jobs):
"""
Returns a parallel map of func over iterable.
Returns all results at once, so if results are big memory issues may arise
Parameters
----------
func : Function of one variable
You can use functools.partial to build this.
A lambda function will not work
iterable : List, iterator, etc...
func is applied to this
n_jobs : Integer
The number of jobs to use for the computation. If -1 all CPUs are used.
If 1 is given, no parallel computing code is used at all, which is
useful for debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are
used. Thus for n_jobs = -2, all CPUs but one are used.
Examples
--------
>>> from functools import partial
>>> from rosetta.parallel.parallel_easy import map_easy
>>> def abfunc(x, a, b=1):
... return x * a * b
>>> some_numbers = range(5)
>>> func = partial(abfunc, 2, b=3)
>>> map_easy(func, some_numbers)
[0, 6, 12, 18, 24]
"""
n_jobs = _n_jobs_wrap(n_jobs)
if n_jobs == 1:
return map(func, iterable)
else:
_trypickle(func)
pool = Pool(n_jobs)
return pool.map_async(func, iterable).get(GOOGLE)
def map_easy_padded_blocks(func, iterable, n_jobs, pad, blocksize=None):
"""
Returns a parallel map of func over iterable, computed by splitting
iterable into padded blocks, then piecing the result together.
Parameters
----------
func : Function of one variable
You can use functools.partial to build this.
A lambda function will not work
iterable : List, iterator, etc...
func is applied to this
n_jobs : Integer
The number of jobs to use for the computation. If -1 all CPUs are used.
If 1 is given, no parallel computing code is used at all, which is
useful for debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are
used. Thus for n_jobs = -2, all CPUs but one are used.
pad : Nonnegative Integer
Each block is processed with pad extra on each side.
blocksize : Nonnegative Integer
If None, use 100 * pad
Returns
-------
result : List
Equivalent to list(func(iterable))
Examples
--------
>>> numbers = [0, 0, 2, -1, 4, 2, 6, 7, 6, 9]
>>> pad = 1
>>> n_jobs = -1
>>> def rightmax(mylist):
... return [max(mylist[i: i+2]) for i in range(len(mylist))]
>>> result = map_easy_padded_blocks(rightmax, numbers, n_jobs, pad)
>>> benchmark = rightmax(numbers)
>>> result == benchmark
True
"""
mylist = list(iterable)
# We will pad each side of the blocks with this to avoid edge effects.
max_blocksize = len(mylist) - pad - 1
if blocksize is None:
blocksize = min(max_blocksize, 100 * pad)
assert pad + blocksize < len(mylist)
# Get an iterator over padded blocks
block_idx, pads_used = _get_split_idx(len(mylist), blocksize, pad=pad)
block_iter = (mylist[start: end] for start, end in block_idx)
# Process each block
processed_blocks = map_easy(func, block_iter, n_jobs)
result = []
for block, (leftpad, rightpad) in zip(processed_blocks, pads_used):
result += block[leftpad: len(block) - rightpad]
return result
def _get_split_idx(N, blocksize, pad=0):
"""
Returns a list of indexes dividing an array into blocks of size blocksize
with optional padding. Padding takes into account that the resultant block
must fit within the original array.
Parameters
----------
N : Nonnegative integer
Total array length
blocksize : Nonnegative integer
Size of each block
pad : Nonnegative integer
Pad to add on either side of each index
Returns
-------
split_idx : List of 2-tuples
Indices to create splits
pads_used : List of 2-tuples
Pads that were actually used on either side
Examples
--------
>>> split_idx, pads_used = _get_split_idx(5, 2)
>>> print split_idx
[(0, 2), (2, 4), (4, 5)]
>>> print pads_used
[(0, 0), (0, 0), (0, 0)]
>>> _get_split_idx(5, 2, pad=1)
>>> print split_idx
[(0, 3), (1, 5), (3, 5)]
>>> print pads_used
[(0, 1), (1, 1), (1, 0)]
"""
num_fullsplits = N // blocksize
remainder = N % blocksize
split_idx = []
pads_used = []
for i in range(num_fullsplits):
start = max(0, i * blocksize - pad)
end = min(N, (i + 1) * blocksize + pad)
split_idx.append((start, end))
leftpad = i * blocksize - start
rightpad = end - (i + 1) * blocksize
pads_used.append((leftpad, rightpad))
# Append the last split if there is a remainder
if remainder:
start = max(0, num_fullsplits * blocksize - pad)
split_idx.append((start, N))
leftpad = num_fullsplits * blocksize - start
pads_used.append((leftpad, 0))
return split_idx, pads_used
def _n_jobs_wrap(n_jobs):
"""
For dealing with positive or negative n_jobs.
Parameters
----------
n_jobs : Integer
Returns
-------
n_jobs_modified : Integer
If -1, equal to multiprocessing.cpu_count() (all CPU's used).
If 1 is given, no parallel computing code is used at all, which is
useful for debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are
used. Thus for n_jobs = -2, all CPUs but one are used.
"""
if not isinstance(n_jobs, int):
raise ValueError(
"type(n_jobs) = %s, but n_jobs should be an int" % type(n_jobs))
if (n_jobs == 0) or (n_jobs < -1 * cpu_count()):
msg = "Must have -1 + cpu_count() <= n_jobs < 0 OR 1 <= n_jobs"
raise ValueError("n_jobs = %d, but %s" % (n_jobs, msg))
if n_jobs < 0:
n_jobs = max(cpu_count() + 1 + n_jobs, 1)
return n_jobs
def _imap_wrap(func):
"""
Adds timeout to IMapIterator and IMapUnorderedIterator.
This allows exit upon Ctrl-C. This is a fix
of the known python bug bugs.python.org/issue8296 given by
https://gist.github.com/aljungberg/626518
Parameters
----------
func : Either IMapIterator or IMapUnorderedIterator
Returns
-------
wrap : Function
Wrapped version of func, with timeout specified
"""
# func will be a next() method of IMapIterator.
# Note that the first argument to methods are always 'self'.
def wrap(self, timeout=None):
return func(self, timeout=timeout if timeout is not None else GOOGLE)
return wrap
def _trypickle(func):
"""
Attempts to pickle func since multiprocessing needs to do this.
"""
genericmsg = "Pickling of func (necessary for multiprocessing) failed."
boundmethodmsg = genericmsg + '\n\n' + """
func contained a bound method, and these cannot be pickled. This causes
multiprocessing to fail. Possible causes/solutions:
Cause 1) You used a lambda function or an object's method, e.g.
my_object.myfunc
Solution 1) Wrap the method or lambda function, e.g.
def func(x):
return my_object.myfunc(x)
Cause 2) You are pickling an object that had an attribute equal to a
method or lambda func, e.g. self.myfunc = self.mymethod.
Solution 2) Don't do this.
"""
try:
cPickle.dumps(func)
except TypeError as e:
if 'instancemethod' in e.message:
sys.stderr.write(boundmethodmsg + "\n")
else:
sys.stderr.write(genericmsg + '\n')
raise
except:
sys.stderr.write(genericmsg + '\n')
raise
# Redefine IMapUnorderedIterator so we can exit with Ctrl-C
IMapUnorderedIterator.next = _imap_wrap(IMapUnorderedIterator.next)
IMapIterator.next = _imap_wrap(IMapIterator.next)
if __name__ == '__main__':
# Can't get doctest to work with multiprocessing...
pass