distributed_do.py 11.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
import numpy as np
from .random import Random
from mpi4py import MPI

comm = MPI.COMM_WORLD
ntask = comm.Get_size()
rank = comm.Get_rank()


def shareSize(nwork, nshares, myshare):
    nbase = nwork//nshares
    return nbase if myshare>=nwork%nshares else nbase+1
Martin Reinecke's avatar
Martin Reinecke committed
13
14
15
16
17
18
def shareRange(nwork, nshares, myshare):
    nbase = nwork//nshares;
    additional = nwork%nshares;
    lo = myshare*nbase + min(myshare, additional)
    hi = lo+nbase+ (1 if myshare<additional else 0)
    return lo,hi
19
20
21
22

def get_locshape(shape, distaxis):
    if distaxis==-1:
        return shape
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
23
24
    if distaxis<0 or distaxis>=len(shape):
        print distaxis,shape
25
26
27
    shape2=list(shape)
    shape2[distaxis]=shareSize(shape[distaxis],ntask,rank)
    return tuple(shape2)
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
28
29
def local_shape(shape, distaxis):
    return get_locshape(shape,distaxis)
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

class data_object(object):
    def __init__(self, shape, data, distaxis):
        """Must not be called directly by users"""
        self._shape = shape
        self._distaxis = distaxis
        lshape = get_locshape(self._shape, self._distaxis)
        self._data = data

    def sanity_checks(self):
        # check whether the distaxis is consistent
        if self._distaxis<-1 or self._distaxis>=len(self._shape):
            raise ValueError
        itmp=np.array(self._distaxis)
        otmp=np.empty(ntask,dtype=np.int)
        comm.Allgather(itmp,otmp)
        if np.any(otmp!=self._distaxis):
            raise ValueError
        # check whether the global shape is consistent
        itmp=np.array(self._shape)
Martin Reinecke's avatar
Martin Reinecke committed
50
        otmp=np.empty((ntask,len(self._shape)),dtype=np.int)
51
52
        comm.Allgather(itmp,otmp)
        for i in range(ntask):
Martin Reinecke's avatar
Martin Reinecke committed
53
            if np.any(otmp[i,:]!=self._shape):
54
55
56
57
58
59
60
                raise ValueError
        # check shape of local data
        if self._distaxis<0:
            if self._data.shape!=self._shape:
                raise ValueError
        else:
            itmp=np.array(self._shape)
Martin Reinecke's avatar
Martin Reinecke committed
61
62
            itmp[self._distaxis] = shareSize(self._shape[self._distaxis],ntask,rank)
            if np.any(self._data.shape!=itmp):
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
                raise ValueError

    @property
    def dtype(self):
        return self._data.dtype

    @property
    def shape(self):
        return self._shape

    @property
    def size(self):
        return np.prod(self._shape)

    @property
    def real(self):
Martin Reinecke's avatar
Martin Reinecke committed
79
        return data_object(self._shape, self._data.real, self._distaxis)
80
81
82

    @property
    def imag(self):
Martin Reinecke's avatar
Martin Reinecke committed
83
        return data_object(self._shape, self._data.imag, self._distaxis)
84

Martin Reinecke's avatar
Martin Reinecke committed
85
    def _contraction_helper(self, op, mpiop, axis):
86
87
88
89
        if axis is not None:
            if len(axis)==len(self._data.shape):
                axis = None
        if axis is None:
Martin Reinecke's avatar
Martin Reinecke committed
90
91
92
93
            res = np.array(getattr(self._data, op)())
            if (self._distaxis==-1):
                return res
            res2 = np.empty(1,dtype=res.dtype)
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
94
            comm.Allreduce(res,res2,mpiop)
Martin Reinecke's avatar
Martin Reinecke committed
95
            return res2[0]
96
97
98
99

        if self._distaxis in axis:
            pass# reduce globally, redistribute the result along axis 0(?)
        else:
Martin Reinecke's avatar
Martin Reinecke committed
100
101
102
            # perform the contraction on the local data
            data = getattr(self._data, op)(axis=axis)
            #shp =
103
104
105
106
107
108
109
110
111
112
113

        # check if the result is scalar or if a result_field must be constr.
        if np.isscalar(data):
            return data
        else:
            return data_object(data)

    def sum(self, axis=None):
        return self._contraction_helper("sum", MPI.SUM, axis)

    def _binary_helper(self, other, op):
Martin Reinecke's avatar
Martin Reinecke committed
114
        a = self
115
        if isinstance(other, data_object):
Martin Reinecke's avatar
Martin Reinecke committed
116
            b = other
117
118
119
            if a._shape != b._shape:
                raise ValueError("shapes are incompatible.")
            if a._distaxis != b._distaxis:
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
120
                print (a._distaxis, b._distaxis)
121
                raise ValueError("distributions are incompatible.")
Martin Reinecke's avatar
Martin Reinecke committed
122
123
            a = a._data
            b = b._data
124
        else:
Martin Reinecke's avatar
Martin Reinecke committed
125
            a = a._data
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
            b = other

        tval = getattr(a, op)(b)
        return self if tval is a else data_object(self._shape, tval, self._distaxis)

    def __add__(self, other):
        return self._binary_helper(other, op='__add__')

    def __radd__(self, other):
        return self._binary_helper(other, op='__radd__')

    def __iadd__(self, other):
        return self._binary_helper(other, op='__iadd__')

    def __sub__(self, other):
        return self._binary_helper(other, op='__sub__')

    def __rsub__(self, other):
        return self._binary_helper(other, op='__rsub__')

    def __isub__(self, other):
        return self._binary_helper(other, op='__isub__')

    def __mul__(self, other):
        return self._binary_helper(other, op='__mul__')

    def __rmul__(self, other):
        return self._binary_helper(other, op='__rmul__')

    def __imul__(self, other):
        return self._binary_helper(other, op='__imul__')

    def __div__(self, other):
        return self._binary_helper(other, op='__div__')

    def __rdiv__(self, other):
        return self._binary_helper(other, op='__rdiv__')

    def __truediv__(self, other):
        return self._binary_helper(other, op='__truediv__')

    def __rtruediv__(self, other):
        return self._binary_helper(other, op='__rtruediv__')

    def __pow__(self, other):
        return self._binary_helper(other, op='__pow__')

    def __rpow__(self, other):
        return self._binary_helper(other, op='__rpow__')

    def __ipow__(self, other):
        return self._binary_helper(other, op='__ipow__')

    def __eq__(self, other):
        return self._binary_helper(other, op='__eq__')

    def __ne__(self, other):
        return self._binary_helper(other, op='__ne__')

    def __neg__(self):
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
186
        return data_object(self._shape,-self._data,self._distaxis)
187
188

    def __abs__(self):
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
189
        return data_object(self._shape,np.abs(self._data),self._distaxis)
190

Martin Reinecke's avatar
fixes    
Martin Reinecke committed
191
192
    #def ravel(self):
    #    return data_object(self._data.ravel())
193

Martin Reinecke's avatar
fixes    
Martin Reinecke committed
194
195
    #def reshape(self, shape):
    #    return data_object(self._data.reshape(shape))
196
197
198
199
200
201
202
203

    def all(self):
        return self._data.all()

    def any(self):
        return self._data.any()


Martin Reinecke's avatar
Martin Reinecke committed
204
def full(shape, fill_value, dtype=None, distaxis=0):
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
205
    return data_object(shape, np.full(get_locshape(shape, distaxis), fill_value, dtype), distaxis)
206
207


Martin Reinecke's avatar
fixes    
Martin Reinecke committed
208
209
def empty(shape, dtype=None, distaxis=0):
    return data_object(shape, np.empty(get_locshape(shape, distaxis), dtype), distaxis)
210
211


Martin Reinecke's avatar
fixes    
Martin Reinecke committed
212
213
def zeros(shape, dtype=None, distaxis=0):
    return data_object(shape, np.zeros(get_locshape(shape, distaxis), dtype), distaxis)
214
215


Martin Reinecke's avatar
fixes    
Martin Reinecke committed
216
217
def ones(shape, dtype=None, distaxis=0):
    return data_object(shape, np.ones(get_locshape(shape, distaxis), dtype), distaxis)
218
219
220
221
222
223
224


def empty_like(a, dtype=None):
    return data_object(np.empty_like(a._data, dtype))


def vdot(a, b):
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
225
226
227
228
    tmp = np.vdot(a._data.ravel(), b._data.ravel())
    res = np.empty(1,dtype=type(tmp))
    comm.Allreduce(tmp,res,MPI.SUM)
    return res
229
230
231
232
233
234
235


def _math_helper(x, function, out):
    if out is not None:
        function(x._data, out=out._data)
        return out
    else:
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
236
        return data_object(x.shape,function(x._data),x._distaxis)
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


def abs(a, out=None):
    return _math_helper(a, np.abs, out)


def exp(a, out=None):
    return _math_helper(a, np.exp, out)


def log(a, out=None):
    return _math_helper(a, np.log, out)


def sqrt(a, out=None):
    return _math_helper(a, np.sqrt, out)


def bincount(x, weights=None, minlength=None):
    if weights is not None:
        weights = weights._data
    res = np.bincount(x._data, weights, minlength)
    return data_object(res)


def from_object(object, dtype=None, copy=True):
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
263
    return data_object(object._shape, np.array(object._data, dtype=dtype, copy=copy), distaxis=object._distaxis)
264
265


Martin Reinecke's avatar
fixes    
Martin Reinecke committed
266
def from_random(random_type, shape, dtype=np.float64, distaxis=0, **kwargs):
267
    generator_function = getattr(Random, random_type)
Martin Reinecke's avatar
fixes    
Martin Reinecke committed
268
269
    lshape = get_locshape(shape, distaxis)
    return data_object(shape, generator_function(dtype=dtype, shape=lshape, **kwargs), distaxis=distaxis)
270
271
272
273
274
275


def to_ndarray(arr):
    return arr._data


Martin Reinecke's avatar
fixes    
Martin Reinecke committed
276
277
def from_ndarray(arr,distaxis=0):
    return data_object(arr.shape,arr,distaxis)
Martin Reinecke's avatar
Martin Reinecke committed
278
279
280
281
282
283


def local_data(arr):
    return arr._data


Martin Reinecke's avatar
fixes    
Martin Reinecke committed
284
285
286
287
def ibegin(arr):
    res = [0] * arr._data.ndim
    res[arr._distaxis] = shareRange(arr._shape[arr._distaxis],ntask,rank)[0]
    return tuple(res)
Martin Reinecke's avatar
Martin Reinecke committed
288
289


Martin Reinecke's avatar
fixes    
Martin Reinecke committed
290
291
292
293
def np_allreduce_sum(arr):
    res = np.empty_like(arr)
    comm.Allreduce(arr,res,MPI.SUM)
    return res
Martin Reinecke's avatar
Martin Reinecke committed
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312


def distaxis(arr):
    return arr._distaxis


def from_local_data (shape, arr, distaxis):
    return data_object(shape, arr, distaxis)


def from_global_data (arr, distaxis=0):
    if distaxis==-1:
        return data_object(arr.shape, arr, distaxis)
    lo, hi = shareRange(arr.shape[distaxis],ntask,rank)
    sl = [slice(None)]*len(arr.shape)
    sl[distaxis]=slice(lo,hi)
    return data_object(arr.shape, arr[sl], distaxis)


Martin Reinecke's avatar
fixes    
Martin Reinecke committed
313
314
315
316
317
318
319
def to_global_data (arr):
    if arr._distaxis==-1:
        return arr._data
    tmp = redistribute(arr, dist=-1)
    return tmp._data


Martin Reinecke's avatar
Martin Reinecke committed
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
def redistribute (arr, dist=None, nodist=None):
    if dist is not None:
        if nodist is not None:
            raise ValueError
        if dist==arr._distaxis:
            return arr
    else:
        if nodist is None:
            raise ValueError
        if arr._distaxis not in nodist:
            return arr
        dist=-1
        for i in range(len(arr.shape)):
            if i not in nodist:
                dist=i
                break
    if arr._distaxis==-1:  # just pick the proper subset
        return from_global_data(arr._data, dist)
    if dist==-1: # gather data
        tmp = np.moveaxis(arr._data, arr._distaxis, 0)
        slabsize=np.prod(tmp.shape[1:])*tmp.itemsize
        sz=np.empty(ntask,dtype=np.int)
        for i in range(ntask):
            sz[i]=slabsize*shareSize(arr.shape[arr._distaxis],ntask,i)
        disp=np.empty(ntask,dtype=np.int)
        disp[0]=0
        disp[1:]=np.cumsum(sz[:-1])
        tmp=tmp.flatten()
        out = np.empty(arr.size,dtype=arr.dtype)
        print tmp.shape, out.shape, sz, disp
        comm.Allgatherv(tmp,[out,sz,disp,MPI.BYTE])
        out = out.reshape(arr._shape)
        out = np.moveaxis(out, 0, arr._distaxis)
        return from_global_data (out, distaxis=-1)
    # real redistribution via Alltoallv
    tmp = np.moveaxis(arr._data, (dist, arr._distaxis), (0, 1))
    tshape = tmp.shape
    slabsize=np.prod(tmp.shape[2:])*tmp.itemsize
    ssz=np.empty(ntask,dtype=np.int)
    rsz=np.empty(ntask,dtype=np.int)
    for i in range(ntask):
        ssz[i]=slabsize*tmp.shape[1]*shareSize(arr.shape[dist],ntask,i)
        rsz[i]=slabsize*shareSize(arr.shape[dist],ntask,rank)*shareSize(arr.shape[arr._distaxis],ntask,i)
    sdisp=np.empty(ntask,dtype=np.int)
    rdisp=np.empty(ntask,dtype=np.int)
    sdisp[0]=0
    rdisp[0]=0
    sdisp[1:]=np.cumsum(ssz[:-1])
    rdisp[1:]=np.cumsum(rsz[:-1])
    print ssz, rsz
    tmp=tmp.flatten()
    out = np.empty(np.prod(get_locshape(arr.shape,dist)),dtype=arr.dtype)
    s_msg = [tmp, (ssz, sdisp), MPI.BYTE]
    r_msg = [out, (rsz, rdisp), MPI.BYTE]
    comm.Alltoallv(s_msg, r_msg)
    new_shape = [shareSize(arr.shape[dist],ntask,rank), arr.shape[arr._distaxis]] +list(tshape[2:])
    out=out.reshape(new_shape)
    out = np.moveaxis(out, (0, 1), (dist, arr._distaxis))
    return from_local_data (arr.shape, out, dist)


def default_distaxis():
    return 0