Generic function to perform parallel cumulative scan (a.k.a prefix scan) The Blelloch prefix scan is work-efficient and exposes parallelism. A parallel cumsum works by first taking the sum of each block, then do a binary tree merge followed by a fan-out (i.e., the Brent-Kung pattern).
(func, preop, binop, x, axis=None, dtype=None, out=None)
| 1035 | |
| 1036 | |
| 1037 | def prefixscan_blelloch(func, preop, binop, x, axis=None, dtype=None, out=None): |
| 1038 | """Generic function to perform parallel cumulative scan (a.k.a prefix scan) |
| 1039 | |
| 1040 | The Blelloch prefix scan is work-efficient and exposes parallelism. |
| 1041 | A parallel cumsum works by first taking the sum of each block, then do a binary tree |
| 1042 | merge followed by a fan-out (i.e., the Brent-Kung pattern). We then take the cumsum |
| 1043 | of each block and add the sum of the previous blocks. |
| 1044 | |
| 1045 | When performing a cumsum across N chunks, this method has 2 * lg(N) levels of dependencies. |
| 1046 | In contrast, the sequential method has N levels of dependencies. |
| 1047 | |
| 1048 | Floating point operations should be more accurate with this method compared to sequential. |
| 1049 | |
| 1050 | Parameters |
| 1051 | ---------- |
| 1052 | func : callable |
| 1053 | Cumulative function (e.g. ``np.cumsum``) |
| 1054 | preop : callable |
| 1055 | Function to get the final value of a cumulative function (e.g., ``np.sum``) |
| 1056 | binop : callable |
| 1057 | Associative function (e.g. ``add``) |
| 1058 | x : dask array |
| 1059 | axis : int |
| 1060 | dtype : dtype |
| 1061 | |
| 1062 | Returns |
| 1063 | ------- |
| 1064 | dask array |
| 1065 | """ |
| 1066 | if axis is None: |
| 1067 | x = x.flatten().rechunk(chunks=x.npartitions) |
| 1068 | axis = 0 |
| 1069 | if dtype is None: |
| 1070 | dtype = getattr(func(np.ones((0,), dtype=x.dtype)), "dtype", object) |
| 1071 | assert isinstance(axis, Integral) |
| 1072 | axis = validate_axis(axis, x.ndim) |
| 1073 | name = f"{func.__name__}-{tokenize(func, axis, preop, binop, x, dtype)}" |
| 1074 | base_key = (name,) |
| 1075 | |
| 1076 | # Right now, the metadata for batches is incorrect, but this should be okay |
| 1077 | batches = x.map_blocks(preop, axis=axis, keepdims=True, dtype=dtype) |
| 1078 | # We don't need the last index until the end |
| 1079 | *indices, last_index = full_indices = [ |
| 1080 | list( |
| 1081 | product( |
| 1082 | *[range(nb) if j != axis else [i] for j, nb in enumerate(x.numblocks)] |
| 1083 | ) |
| 1084 | ) |
| 1085 | for i in range(x.numblocks[axis]) |
| 1086 | ] |
| 1087 | prefix_vals = [[(batches.name,) + index for index in vals] for vals in indices] |
| 1088 | dsk = {} |
| 1089 | n_vals = len(prefix_vals) |
| 1090 | level = 0 |
| 1091 | if n_vals >= 2: |
| 1092 | # Upsweep |
| 1093 | stride = 1 |
| 1094 | stride2 = 2 |
no test coverage detected