pool.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. """Custom implementation of multiprocessing.Pool with custom pickler.
  2. This module provides efficient ways of working with data stored in
  3. shared memory with numpy.memmap arrays without inducing any memory
  4. copy between the parent and child processes.
  5. This module should not be imported if multiprocessing is not
  6. available as it implements subclasses of multiprocessing Pool
  7. that uses a custom alternative to SimpleQueue.
  8. """
  9. # Author: Olivier Grisel <olivier.grisel@ensta.org>
  10. # Copyright: 2012, Olivier Grisel
  11. # License: BSD 3 clause
  12. import copyreg
  13. import sys
  14. import warnings
  15. from time import sleep
  16. try:
  17. WindowsError
  18. except NameError:
  19. WindowsError = type(None)
  20. from io import BytesIO
  21. # We need the class definition to derive from it, not the multiprocessing.Pool
  22. # factory function
  23. from multiprocessing.pool import Pool
  24. from pickle import HIGHEST_PROTOCOL, Pickler
  25. from ._memmapping_reducer import TemporaryResourcesManager, get_memmapping_reducers
  26. from ._multiprocessing_helpers import assert_spawning, mp
  27. try:
  28. import numpy as np
  29. except ImportError:
  30. np = None
  31. ###############################################################################
  32. # Enable custom pickling in Pool queues
  33. class CustomizablePickler(Pickler):
  34. """Pickler that accepts custom reducers.
  35. TODO python2_drop : can this be simplified ?
  36. HIGHEST_PROTOCOL is selected by default as this pickler is used
  37. to pickle ephemeral datastructures for interprocess communication
  38. hence no backward compatibility is required.
  39. `reducers` is expected to be a dictionary with key/values
  40. being `(type, callable)` pairs where `callable` is a function that
  41. give an instance of `type` will return a tuple `(constructor,
  42. tuple_of_objects)` to rebuild an instance out of the pickled
  43. `tuple_of_objects` as would return a `__reduce__` method. See the
  44. standard library documentation on pickling for more details.
  45. """
  46. # We override the pure Python pickler as its the only way to be able to
  47. # customize the dispatch table without side effects in Python 2.7
  48. # to 3.2. For Python 3.3+ leverage the new dispatch_table
  49. # feature from https://bugs.python.org/issue14166 that makes it possible
  50. # to use the C implementation of the Pickler which is faster.
  51. def __init__(self, writer, reducers=None, protocol=HIGHEST_PROTOCOL):
  52. Pickler.__init__(self, writer, protocol=protocol)
  53. if reducers is None:
  54. reducers = {}
  55. if hasattr(Pickler, "dispatch"):
  56. # Make the dispatch registry an instance level attribute instead of
  57. # a reference to the class dictionary under Python 2
  58. self.dispatch = Pickler.dispatch.copy()
  59. else:
  60. # Under Python 3 initialize the dispatch table with a copy of the
  61. # default registry
  62. self.dispatch_table = copyreg.dispatch_table.copy()
  63. for type, reduce_func in reducers.items():
  64. self.register(type, reduce_func)
  65. def register(self, type, reduce_func):
  66. """Attach a reducer function to a given type in the dispatch table."""
  67. if hasattr(Pickler, "dispatch"):
  68. # Python 2 pickler dispatching is not explicitly customizable.
  69. # Let us use a closure to workaround this limitation.
  70. def dispatcher(self, obj):
  71. reduced = reduce_func(obj)
  72. self.save_reduce(obj=obj, *reduced)
  73. self.dispatch[type] = dispatcher
  74. else:
  75. self.dispatch_table[type] = reduce_func
  76. class CustomizablePicklingQueue(object):
  77. """Locked Pipe implementation that uses a customizable pickler.
  78. This class is an alternative to the multiprocessing implementation
  79. of SimpleQueue in order to make it possible to pass custom
  80. pickling reducers, for instance to avoid memory copy when passing
  81. memory mapped datastructures.
  82. `reducers` is expected to be a dict with key / values being
  83. `(type, callable)` pairs where `callable` is a function that, given an
  84. instance of `type`, will return a tuple `(constructor, tuple_of_objects)`
  85. to rebuild an instance out of the pickled `tuple_of_objects` as would
  86. return a `__reduce__` method.
  87. See the standard library documentation on pickling for more details.
  88. """
  89. def __init__(self, context, reducers=None):
  90. self._reducers = reducers
  91. self._reader, self._writer = context.Pipe(duplex=False)
  92. self._rlock = context.Lock()
  93. if sys.platform == "win32":
  94. self._wlock = None
  95. else:
  96. self._wlock = context.Lock()
  97. self._make_methods()
  98. def __getstate__(self):
  99. assert_spawning(self)
  100. return (self._reader, self._writer, self._rlock, self._wlock, self._reducers)
  101. def __setstate__(self, state):
  102. (self._reader, self._writer, self._rlock, self._wlock, self._reducers) = state
  103. self._make_methods()
  104. def empty(self):
  105. return not self._reader.poll()
  106. def _make_methods(self):
  107. self._recv = recv = self._reader.recv
  108. racquire, rrelease = self._rlock.acquire, self._rlock.release
  109. def get():
  110. racquire()
  111. try:
  112. return recv()
  113. finally:
  114. rrelease()
  115. self.get = get
  116. if self._reducers:
  117. def send(obj):
  118. buffer = BytesIO()
  119. CustomizablePickler(buffer, self._reducers).dump(obj)
  120. self._writer.send_bytes(buffer.getvalue())
  121. self._send = send
  122. else:
  123. self._send = send = self._writer.send
  124. if self._wlock is None:
  125. # writes to a message oriented win32 pipe are atomic
  126. self.put = send
  127. else:
  128. wlock_acquire, wlock_release = (self._wlock.acquire, self._wlock.release)
  129. def put(obj):
  130. wlock_acquire()
  131. try:
  132. return send(obj)
  133. finally:
  134. wlock_release()
  135. self.put = put
  136. class PicklingPool(Pool):
  137. """Pool implementation with customizable pickling reducers.
  138. This is useful to control how data is shipped between processes
  139. and makes it possible to use shared memory without useless
  140. copies induces by the default pickling methods of the original
  141. objects passed as arguments to dispatch.
  142. `forward_reducers` and `backward_reducers` are expected to be
  143. dictionaries with key/values being `(type, callable)` pairs where
  144. `callable` is a function that, given an instance of `type`, will return a
  145. tuple `(constructor, tuple_of_objects)` to rebuild an instance out of the
  146. pickled `tuple_of_objects` as would return a `__reduce__` method.
  147. See the standard library documentation about pickling for more details.
  148. """
  149. def __init__(
  150. self, processes=None, forward_reducers=None, backward_reducers=None, **kwargs
  151. ):
  152. if forward_reducers is None:
  153. forward_reducers = dict()
  154. if backward_reducers is None:
  155. backward_reducers = dict()
  156. self._forward_reducers = forward_reducers
  157. self._backward_reducers = backward_reducers
  158. poolargs = dict(processes=processes)
  159. poolargs.update(kwargs)
  160. super(PicklingPool, self).__init__(**poolargs)
  161. def _setup_queues(self):
  162. context = getattr(self, "_ctx", mp)
  163. self._inqueue = CustomizablePicklingQueue(context, self._forward_reducers)
  164. self._outqueue = CustomizablePicklingQueue(context, self._backward_reducers)
  165. self._quick_put = self._inqueue._send
  166. self._quick_get = self._outqueue._recv
  167. class MemmappingPool(PicklingPool):
  168. """Process pool that shares large arrays to avoid memory copy.
  169. This drop-in replacement for `multiprocessing.pool.Pool` makes
  170. it possible to work efficiently with shared memory in a numpy
  171. context.
  172. Existing instances of numpy.memmap are preserved: the child
  173. suprocesses will have access to the same shared memory in the
  174. original mode except for the 'w+' mode that is automatically
  175. transformed as 'r+' to avoid zeroing the original data upon
  176. instantiation.
  177. Furthermore large arrays from the parent process are automatically
  178. dumped to a temporary folder on the filesystem such as child
  179. processes to access their content via memmapping (file system
  180. backed shared memory).
  181. Note: it is important to call the terminate method to collect
  182. the temporary folder used by the pool.
  183. Parameters
  184. ----------
  185. processes: int, optional
  186. Number of worker processes running concurrently in the pool.
  187. initializer: callable, optional
  188. Callable executed on worker process creation.
  189. initargs: tuple, optional
  190. Arguments passed to the initializer callable.
  191. temp_folder: (str, callable) optional
  192. If str:
  193. Folder to be used by the pool for memmapping large arrays
  194. for sharing memory with worker processes. If None, this will try in
  195. order:
  196. - a folder pointed by the JOBLIB_TEMP_FOLDER environment variable,
  197. - /dev/shm if the folder exists and is writable: this is a RAMdisk
  198. filesystem available by default on modern Linux distributions,
  199. - the default system temporary folder that can be overridden
  200. with TMP, TMPDIR or TEMP environment variables, typically /tmp
  201. under Unix operating systems.
  202. if callable:
  203. An callable in charge of dynamically resolving a temporary folder
  204. for memmapping large arrays.
  205. max_nbytes int or None, optional, 1e6 by default
  206. Threshold on the size of arrays passed to the workers that
  207. triggers automated memory mapping in temp_folder.
  208. Use None to disable memmapping of large arrays.
  209. mmap_mode: {'r+', 'r', 'w+', 'c'}
  210. Memmapping mode for numpy arrays passed to workers.
  211. See 'max_nbytes' parameter documentation for more details.
  212. forward_reducers: dictionary, optional
  213. Reducers used to pickle objects passed from main process to worker
  214. processes: see below.
  215. backward_reducers: dictionary, optional
  216. Reducers used to pickle return values from workers back to the
  217. main process.
  218. verbose: int, optional
  219. Make it possible to monitor how the communication of numpy arrays
  220. with the subprocess is handled (pickling or memmapping)
  221. prewarm: bool or str, optional, "auto" by default.
  222. If True, force a read on newly memmapped array to make sure that OS
  223. pre-cache it in memory. This can be useful to avoid concurrent disk
  224. access when the same data array is passed to different worker
  225. processes. If "auto" (by default), prewarm is set to True, unless the
  226. Linux shared memory partition /dev/shm is available and used as temp
  227. folder.
  228. `forward_reducers` and `backward_reducers` are expected to be
  229. dictionaries with key/values being `(type, callable)` pairs where
  230. `callable` is a function that give an instance of `type` will return
  231. a tuple `(constructor, tuple_of_objects)` to rebuild an instance out
  232. of the pickled `tuple_of_objects` as would return a `__reduce__`
  233. method. See the standard library documentation on pickling for more
  234. details.
  235. """
  236. def __init__(
  237. self,
  238. processes=None,
  239. temp_folder=None,
  240. max_nbytes=1e6,
  241. mmap_mode="r",
  242. forward_reducers=None,
  243. backward_reducers=None,
  244. verbose=0,
  245. prewarm=False,
  246. **kwargs,
  247. ):
  248. manager = TemporaryResourcesManager(temp_folder)
  249. self._temp_folder_manager = manager
  250. # The usage of a temp_folder_resolver over a simple temp_folder is
  251. # superfluous for multiprocessing pools, as they don't get reused, see
  252. # get_memmapping_executor for more details. We still use it for code
  253. # simplicity.
  254. forward_reducers, backward_reducers = get_memmapping_reducers(
  255. temp_folder_resolver=manager.resolve_temp_folder_name,
  256. max_nbytes=max_nbytes,
  257. mmap_mode=mmap_mode,
  258. forward_reducers=forward_reducers,
  259. backward_reducers=backward_reducers,
  260. verbose=verbose,
  261. unlink_on_gc_collect=False,
  262. prewarm=prewarm,
  263. )
  264. poolargs = dict(
  265. processes=processes,
  266. forward_reducers=forward_reducers,
  267. backward_reducers=backward_reducers,
  268. )
  269. poolargs.update(kwargs)
  270. super(MemmappingPool, self).__init__(**poolargs)
  271. def terminate(self):
  272. n_retries = 10
  273. for i in range(n_retries):
  274. try:
  275. super(MemmappingPool, self).terminate()
  276. break
  277. except OSError as e:
  278. if isinstance(e, WindowsError):
  279. # Workaround occasional "[Error 5] Access is denied" issue
  280. # when trying to terminate a process under windows.
  281. sleep(0.1)
  282. if i + 1 == n_retries:
  283. warnings.warn(
  284. "Failed to terminate worker processes in"
  285. " multiprocessing pool: %r" % e
  286. )
  287. # Clean up the temporary resources as the workers should now be off.
  288. self._temp_folder_manager._clean_temporary_resources()
  289. @property
  290. def _temp_folder(self):
  291. # Legacy property in tests. could be removed if we refactored the
  292. # memmapping tests. SHOULD ONLY BE USED IN TESTS!
  293. # We cache this property because it is called late in the tests - at
  294. # this point, all context have been unregistered, and
  295. # resolve_temp_folder_name raises an error.
  296. if getattr(self, "_cached_temp_folder", None) is not None:
  297. return self._cached_temp_folder
  298. else:
  299. self._cached_temp_folder = (
  300. self._temp_folder_manager.resolve_temp_folder_name()
  301. ) # noqa
  302. return self._cached_temp_folder