parallel.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from toolz.itertoolz import partition_all
  2. from toolz.compatibility import reduce, map
  3. from toolz.utils import no_default
  4. def fold(binop, seq, default=no_default, map=map, chunksize=128, combine=None):
  5. """
  6. Reduce without guarantee of ordered reduction.
  7. inputs:
  8. ``binop`` - associative operator. The associative property allows us to
  9. leverage a parallel map to perform reductions in parallel.
  10. ``seq`` - a sequence to be aggregated
  11. ``default`` - an identity element like 0 for ``add`` or 1 for mul
  12. ``map`` - an implementation of ``map``. This may be parallel and
  13. determines how work is distributed.
  14. ``chunksize`` - Number of elements of ``seq`` that should be handled
  15. within a single function call
  16. ``combine`` - Binary operator to combine two intermediate results.
  17. If ``binop`` is of type (total, item) -> total
  18. then ``combine`` is of type (total, total) -> total
  19. Defaults to ``binop`` for common case of operators like add
  20. Fold chunks up the collection into blocks of size ``chunksize`` and then
  21. feeds each of these to calls to ``reduce``. This work is distributed
  22. with a call to ``map``, gathered back and then refolded to finish the
  23. computation. In this way ``fold`` specifies only how to chunk up data but
  24. leaves the distribution of this work to an externally provided ``map``
  25. function. This function can be sequential or rely on multithreading,
  26. multiprocessing, or even distributed solutions.
  27. If ``map`` intends to serialize functions it should be prepared to accept
  28. and serialize lambdas. Note that the standard ``pickle`` module fails
  29. here.
  30. Example
  31. -------
  32. >>> # Provide a parallel map to accomplish a parallel sum
  33. >>> from operator import add
  34. >>> fold(add, [1, 2, 3, 4], chunksize=2, map=map)
  35. 10
  36. """
  37. if combine is None:
  38. combine = binop
  39. chunks = partition_all(chunksize, seq)
  40. # Evaluate sequence in chunks via map
  41. if default == no_default:
  42. results = map(lambda chunk: reduce(binop, chunk), chunks)
  43. else:
  44. results = map(lambda chunk: reduce(binop, chunk, default), chunks)
  45. results = list(results) # TODO: Support complete laziness
  46. if len(results) == 1: # Return completed result
  47. return results[0]
  48. else: # Recurse to reaggregate intermediate results
  49. return fold(combine, results, map=map, chunksize=chunksize)