Debian Codegraph @

DisplayCAL/multiprocess.py

raw
1 """Utilities for parallel processing with multiprocessing.
2
3 It includes functions and classes to manage worker pools, handle task
4 distribution, and process data slices efficiently.
5 """
6
7 from __future__ import annotations
8
9 import contextlib
10 import errno
11 import logging
12 import math
13 import multiprocessing as mp
14 import multiprocessing.pool
15 import sys
16 import threading
17 from queue import Empty
18 from typing import TYPE_CHECKING, Any, Callable, TextIO
19
20 if TYPE_CHECKING:
21 from collections.abc import Iterable
22
23
24 # BUG #715 : Limiting the total workers/CPUs to 32
25 MAX_CPUS = 32
26
27
28 def cpu_count(limit_by_total_vmem: bool = True) -> int:
29 """Return the number of CPUs in the system.
30
31 If psutil is installed, the number of reported CPUs is limited according to
32 total RAM by assuming 1 GB for each CPU + 1 GB for the system, unless
33 limit_by_total_vmem is False, to allow a reasonable amount of memory for
34 each CPU.
35
36 Return fallback value of 1 if CPU count cannot be determined.
37
38 Args:
39 limit_by_total_vmem (bool, optional): If True, limit the reported CPU
40 count according to total RAM. Defaults to True.
41
42 Returns:
43 int: The number of CPUs in the system, limited by total RAM if
44 specified.
45 """
46 max_cpus = min(sys.maxsize, MAX_CPUS)
47 if limit_by_total_vmem:
48 try:
49 import psutil
50 except (ImportError, RuntimeError):
51 pass
52 else:
53 # Limit reported CPUs according to total RAM.
54 # We use total instead of available because we assume the system is
55 # smart enough to swap memory used by inactive processes to disk to
56 # free up more physical RAM for active processes.
57 with contextlib.suppress(Exception):
58 max_cpus = min(
59 int(psutil.virtual_memory().total / (1024**3) - 1), MAX_CPUS
60 )
61 try:
62 return max(min(mp.cpu_count(), max_cpus), 1)
63 except Exception:
64 return 1
65
66
67 def pool_slice(
68 func: Callable,
69 data_in: Iterable,
70 args: None | tuple = None,
71 kwds: None | dict = None,
72 num_workers: None | int = None,
73 thread_abort: None | threading.Thread = None,
74 logfile: None | TextIO = None,
75 num_batches: int = 1,
76 progress: float = 0,
77 ) -> list:
78 """Process data in slices using a pool of workers and return the results.
79
80 The individual worker results are returned in the same order as the
81 original input data, irrespective of the order in which the workers
82 finished (FIFO).
83
84 Progress percentage is written to optional logfile using a background
85 thread that monitors a queue.
86
87 Note that 'func' is supposed to periodically check thread_abort.event which
88 is passed as the first argument to 'func', and put its progress percentage
89 into the queue which is passed as the second argument to 'func'.
90
91 Args:
92 func (Callable): The function to be applied to each slice of data.
93 data_in (Iterable): The input data to be processed.
94 args (None | tuple, optional): Additional positional arguments to pass
95 to 'func'. Defaults to None.
96 kwds (None | dict, optional): Additional keyword arguments to pass to
97 'func'. Defaults to None.
98 num_workers (None | int, optional): The number of worker processes to
99 use. If None, it will be set to the number of CPUs in the system.
100 Defaults to None.
101 thread_abort (None | threading.Thread, optional): A thread with an
102 'event' attribute (threading.Event) that can be used to signal
103 abortion of processing. Defaults to None.
104 logfile (None | TextIO, optional): A file-like object to write progress
105 percentage to. If None, progress will not be logged. Defaults to
106 None.
107 num_batches (int, optional): The number of batches to split the work
108 into. This can be used to limit memory usage when processing a
109 large amount of data. Defaults to 1.
110 progress (float, optional): Initial progress percentage. Defaults to
111 0.
112
113 Returns:
114 list: A list of results from processing each slice of data.
115 """
116 if args is None:
117 args = ()
118
119 if kwds is None:
120 kwds = {}
121
122 num_workers, num_batches, chunk_size = determine_worker_count(
123 data_in, num_workers, num_batches
124 )
125 pool_class, manager, event, thread_abort_event, progress_queue = (
126 initialize_pool_manager(num_workers, thread_abort)
127 )
128 # don't remove "_thread" to keep the thread alive to log the progress.
129 _thread = start_progress_logging(
130 num_workers,
131 num_batches,
132 progress,
133 progress_queue,
134 logfile,
135 )
136 pool, results = execute_worker_pool(
137 func,
138 data_in,
139 args,
140 kwds,
141 num_workers,
142 num_batches,
143 chunk_size,
144 pool_class,
145 thread_abort_event,
146 progress_queue,
147 )
148 return get_results(results, pool, manager, event, thread_abort)
149
150
151 def determine_worker_count(
152 data_in: Iterable,
153 num_workers: None | int,
154 num_batches: int,
155 ) -> tuple[int, int, float]:
156 """Determine the number of workers, batches, and chunk size.
157
158 Args:
159 data_in (Iterable): The input data to be processed.
160 num_workers (None | int): The number of worker processes to use.
161 If None, it will be set to the number of CPUs in the system.
162 num_batches (int): The number of batches to split the work into.
163
164 Returns:
165 tuple[int, int, float]: A tuple containing:
166 - The number of worker processes to use.
167 - The number of batches to split the work into.
168 - The size of each chunk to process.
169 """
170 from DisplayCAL.config import getcfg
171
172 num_workers = cpu_count() if num_workers is None else min(num_workers, MAX_CPUS)
173 num_workers = max(min(int(num_workers), len(data_in)), 1)
174 max_workers = getcfg("multiprocessing.max_cpus")
175 num_workers = min(num_workers, max_workers) if max_workers else num_workers
176
177 # Splitting the workload into batches only makes sense if there are
178 # multiple workers
179 num_batches = 1 if (num_workers == 1 or not num_batches) else num_workers
180 chunk_size = float(len(data_in)) / (num_workers * num_batches)
181 if chunk_size < 1:
182 num_batches = 1
183 chunk_size = float(len(data_in)) / num_workers
184 return num_workers, num_batches, chunk_size
185
186
187 def initialize_pool_manager(
188 num_workers: int,
189 thread_abort: None | threading.Thread,
190 ) -> tuple[
191 type,
192 None | mp.Manager,
193 None | threading.Event,
194 None | threading.Event,
195 mp.Queue,
196 ]:
197 """Initialize the worker pool and manager for inter-process communication.
198
199 Args:
200 num_workers (int): The number of worker processes to use.
201 thread_abort (None | threading.Thread): A thread with an 'event'
202 attribute (threading.Event) that can be used to signal abortion
203 of processing. Defaults to None.
204
205 Returns:
206 tuple[
207 type,
208 None | multiprocessing.Manager,
209 None | threading.Event,
210 None | threading.Event,
211 multiprocessing.Queue
212 ]: A tuple containing:
213 - The class to use for the worker pool.
214 - The manager for inter-process communication, or None if not used.
215 - The original event from thread_abort, or None if not used.
216 - The event to signal thread abort, or None if not used.
217 - The queue to send progress updates.
218 """
219 # Do it all in in the main thread of the current instance, by default
220 pool_class = FakePool
221 manager = None
222 event = None
223 queue_class = FakeQueue
224 if num_workers > 1:
225 pool_class = NonDaemonicPool
226 manager = mp.Manager()
227 if thread_abort is not None and not isinstance(
228 thread_abort.event, mp.managers.EventProxy
229 ):
230 # Replace the event with a managed instance that is compatible
231 # with pool
232 event = thread_abort.event
233 thread_abort.event = manager.Event()
234 if event.is_set():
235 thread_abort.event.set()
236 else:
237 event = None
238 queue_class = manager.Queue
239
240 thread_abort_event = thread_abort.event if thread_abort is not None else None
241 progress_queue = queue_class()
242
243 return pool_class, manager, event, thread_abort_event, progress_queue
244
245
246 def start_progress_logging(
247 num_workers: int,
248 num_batches: int,
249 progress: float,
250 progress_queue: mp.Queue,
251 logfile: None | TextIO,
252 ) -> None | threading.Thread:
253 """Start a background thread to log progress percentage to logfile.
254
255 Args:
256 num_workers (int): Number of worker processes.
257 num_batches (int): The number of batches to split the work into.
258 progress (float): Initial progress percentage.
259 progress_queue (mp.Queue): Queue to send progress updates.
260 logfile (None | TextIO): A file-like object to write progress
261 percentage to. If None, progress will not be logged.
262
263 Returns:
264 None | threading.Thread: The thread that logs progress, or None if
265 logfile is None.
266 """
267 if not logfile:
268 return None
269
270 def progress_logger(num_workers: int, progress: float = 0.0) -> None:
271 """Log progress percentage to logfile.
272
273 Args:
274 num_workers (int): Number of worker processes.
275 progress (float, optional): Initial progress percentage.
276 Defaults to 0.0.
277 """
278 eof_count = 0
279 prevperc = -1
280 while progress < 100 * num_workers:
281 try:
282 inc = progress_queue.get(True, 0.1)
283 if isinstance(inc, Exception):
284 raise inc
285 progress += inc
286 except Empty:
287 continue
288 except OSError:
289 break
290 except EOFError:
291 eof_count += 1
292 if eof_count == num_workers:
293 break
294 perc = round(progress / num_workers)
295 if perc > prevperc:
296 logfile.write(f"\r{perc}%")
297 prevperc = perc
298
299 thread = threading.Thread(
300 target=progress_logger,
301 args=(num_workers * num_batches, progress * num_workers * num_batches),
302 name="ProcessProgressLogger",
303 group=None,
304 )
305 thread.start()
306 return thread
307
308
309 def execute_worker_pool(
310 func: Callable,
311 data_in: Iterable,
312 args: tuple,
313 kwds: dict,
314 num_workers: int,
315 num_batches: int,
316 chunk_size: float,
317 poll_class: type,
318 thread_abort_event: threading.Event,
319 progress_queue: mp.Queue,
320 ) -> tuple[NonDaemonicPool | FakePool, list]:
321 """Execute worker pool to process data slices.
322
323 Args:
324 func (Callable): The function to be applied to each slice of data.
325 data_in (Iterable): The input data to be processed.
326 args (tuple): Additional positional arguments to pass to 'func'.
327 kwds (dict): Additional keyword arguments to pass to 'func'.
328 num_workers (int): The number of worker processes to use.
329 num_batches (int): The number of batches to split the work into.
330 chunk_size (float): The size of each chunk to process.
331 poll_class (type): The class to use for the worker pool.
332 thread_abort_event (threading.Event): Event to signal thread abort.
333 progress_queue (mp.Queue): Queue to send progress updates.
334
335 Returns:
336 tuple[NonDaemonicPool | FakePool, list]: The worker pool and a list of
337 results from processing each slice of data.
338 """
339 pool = poll_class(num_workers)
340 results = []
341 start = 0
342 for batch in range(num_batches):
343 for i in range(batch * num_workers, (batch + 1) * num_workers):
344 end = math.ceil(chunk_size * (i + 1))
345 results.append(
346 pool.apply_async(
347 WorkerFunc(func, batch == num_batches - 1),
348 (data_in[start:end], thread_abort_event, progress_queue, *args),
349 kwds,
350 )
351 )
352 start = end
353 return pool, results
354
355
356 def get_results(
357 results: list,
358 pool: NonDaemonicPool | FakePool,
359 manager: None | multiprocessing.Manager,
360 event: None | threading.Event,
361 thread_abort: None | threading.Thread,
362 ) -> list:
363 """Get results from worker pool and clean up resources.
364
365 Args:
366 results (list): List of results from worker pool.
367 pool (NonDaemonicPool | FakePool): The worker pool.
368 manager (None | multiprocessing.Manager): The manager used for
369 inter-process communication.
370 event (None | threading.Event): The original event from thread_abort.
371 thread_abort (None | threading.Thread): The thread with the event
372 attribute.
373
374 Raises:
375 Exception: If any of the worker processes raised an exception.
376
377 Returns:
378 list: A list of results from the worker processes.
379 """
380 # Get results
381 exception = None
382 data_out = []
383 for result in results:
384 result = result.get()
385 if isinstance(result, Exception):
386 exception = result
387 continue
388 data_out.append(result)
389
390 pool.close()
391 pool.join()
392
393 if manager:
394 # Need to shutdown manager so it doesn't hold files in use
395 if event:
396 # Restore original event
397 if thread_abort.event.is_set():
398 event.set()
399 thread_abort.event = event
400 manager.shutdown()
401
402 if exception:
403 raise exception
404
405 return data_out
406
407
408 class WorkerFunc:
409 """Wrap 'func' with optional arguments.
410
411 Args:
412 func (Callable): The function to wrap.
413 exit_ (bool, optional): If True, the worker process will exit after
414 processing the data. This is useful for cleaning up resources in
415 worker processes, especially on Windows where atexit handlers may
416 not run automatically.
417 """
418
419 def __init__(self, func: Callable, exit_: bool = False) -> None:
420 self.func = func
421 self.exit = exit_
422
423 def __call__(
424 self,
425 data: Iterable,
426 thread_abort_event: threading.Event,
427 progress_queue: mp.Queue,
428 *args,
429 **kwds,
430 ) -> Any | Exception: # noqa: ANN401
431 """Call the wrapped function with the given data and arguments.
432
433 Args:
434 data (Iterable): The data to process.
435 thread_abort_event (threading.Event): Event to signal thread abort.
436 progress_queue (multiprocessing.Queue): Queue to send progress updates.
437 *args: Positional arguments to pass to the wrapped function.
438 **kwds: Keyword arguments to pass to the wrapped function.
439
440 Returns:
441 Exception | result: The result of the function call, or an exception
442 if one occurred.
443 """
444 try:
445 return self.func(data, thread_abort_event, progress_queue, *args, **kwds)
446 except Exception as exception:
447 if (
448 not getattr(sys, "_sigbreak", False)
449 or not isinstance(exception, IOError)
450 or exception.args[0] != errno.EPIPE
451 ):
452 import traceback
453
454 print(traceback.format_exc())
455 return exception
456 finally:
457 progress_queue.put(EOFError())
458 if mp.current_process().name != "MainProcess":
459 print("Exiting worker process", mp.current_process().name)
460 if sys.platform == "win32" and self.exit:
461 # Exit handlers registered with atexit will not normally
462 # run when a multiprocessing subprocess exits. We are only
463 # interested in our own exit handler though.
464 # Note all of this only applies to Windows, as it doesn't
465 # have fork().
466
467 # This is not working with Ptyhon 3 as atexit is reimplemented in C
468 # and atexit._exithandlers are not available.
469 # for func, targs, kargs in atexit._exithandlers:
470 # # Find our lockfile removal exit handler
471 # if (
472 # targs
473 # and isinstance(targs[0], str)
474 # and targs[0].endswith(".lock")
475 # ):
476 # print("Removing lockfile", targs[0])
477 # try:
478 # func(*targs, **kargs)
479 # except Exception as exception:
480 # print("Could not remove lockfile:", exception)
481
482 # Logging is normally shutdown by atexit, as well. Do
483 # it explicitly instead.
484 logging.shutdown()
485
486
487 class Mapper:
488 """Wrap 'func' with optional arguments.
489
490 To be used as function argument for Pool.map
491
492 Args:
493 func (Callable): The function to wrap.
494 *args: Positional arguments to pass to the wrapped function.
495 **kwds: Keyword arguments to pass to the wrapped function.
496 """
497
498 def __init__(self, func: Callable, *args, **kwds) -> None:
499 self.func = WorkerFunc(func)
500 self.args = args
501 self.kwds = kwds
502
503 def __call__(self, iterable: Iterable) -> list:
504 """Call the wrapped function with the given iterable.
505
506 Args:
507 iterable (Iterable): The iterable to process with the wrapped function.
508
509 Returns:
510 list: The result of applying the wrapped function to the iterable.
511 """
512 return self.func(iterable, *self.args, **self.kwds)
513
514
515 class NonDaemonicProcess(mp.Process):
516 """Process that is not daemonic.
517
518 This is needed for Windows, as daemonic processes cannot have
519 children. This is a problem when using multiprocessing.Pool,
520 as the worker processes are daemonic and they create child
521 processes when they call the function.
522 """
523
524 @property
525 def daemon(self) -> bool:
526 """Return False, as this process is always non-daemonic.
527
528 Returns:
529 bool: Always False, indicating that this process is non-daemonic.
530 """
531 return False
532
533 @daemon.setter
534 def daemon(self, daemonic: bool) -> None:
535 """Set the process as non-daemonic.
536
537 Args:
538 daemonic (bool): This is ignored, as this process is always
539 non-daemonic.
540 """
541 return
542
543
544 class NonDaemonicPool(mp.pool.Pool):
545 """Pool that has non-daemonic workers."""
546
547 def Process(self, *args, **kwargs) -> NonDaemonicProcess: # noqa: N802
548 """Return a non-daemonic process.
549
550 This is needed for Windows, as daemonic processes cannot have
551 children. This is a problem when using multiprocessing.Pool,
552 as the worker processes are daemonic and they create child
553 processes when they call the function.
554
555 Returns:
556 NonDaemonicProcess: A non-daemonic process.
557 """
558 # Process is a function after Python 3.7+
559 # Process = NonDaemonicProcess -- This will not work with Python3.7+
560 proc = super().Process(*args, **kwargs)
561 proc.__class__ = NonDaemonicProcess # TODO: This is not cool, find a better way
562 # of doing it.
563 return proc
564
565
566 class FakeManager:
567 """Fake manager."""
568
569 def Queue(self) -> FakeQueue: # noqa: N802
570 """Return a fake queue.
571
572 Returns:
573 FakeQueue: A fake queue that does not use multiprocessing.
574 """
575 return FakeQueue()
576
577 def Value(self, typecode: str, *args, **kwds) -> mp.managers.Value: # noqa: N802
578 """Return a fake Value.
579
580 Args:
581 typecode (str): The type code for the value.
582 *args: Positional arguments to pass to the Value constructor.
583 **kwds: Keyword arguments to pass to the Value constructor.
584
585 Returns:
586 mp.managers.Value: A fake Value that does not use multiprocessing.
587 """
588 return mp.managers.Value(typecode, *args, **kwds)
589
590 def shutdown(self) -> None:
591 """Shutdown the fake manager."""
592
593
594 class FakePool:
595 """Fake pool.
596
597 This is a fake pool that does not use multiprocessing. It is used for
598 testing purposes or when multiprocessing is not available or not needed.
599 It does not create worker processes and runs the function in the main
600 thread. It is a drop-in replacement for multiprocessing.Pool.
601 It does not support any of the advanced features of multiprocessing.Pool,
602 such as process management, task tracking, or error handling.
603 It is only suitable for simple use cases where the function can be run
604 synchronously in the main thread without any parallelism.
605
606 Args:
607 processes (None | int, optional): Number of worker processes to use.
608 Not used in this fake pool.
609 initializer (None | callable, optional): Function to run when a worker
610 process starts. Not used in this fake pool.
611 initargs (tuple, optional): Arguments to pass to the initializer
612 function. Not used in this fake pool.
613 maxtasksperchild (None | int, optional): Maximum number of tasks a
614 worker can complete before it is replaced. Not used in this fake
615 pool.
616 """
617
618 def __init__(
619 self,
620 processes: None | int = None,
621 initializer: None | Callable = None,
622 initargs: tuple = (),
623 maxtasksperchild: None | int = None,
624 ) -> None:
625 pass
626
627 def apply_async(self, func: Callable, args: tuple, kwds: dict) -> Result:
628 """Apply function asynchronously.
629
630 Args:
631 func (Callable): The function to apply.
632 args (tuple): The positional arguments to pass to the function.
633 kwds (dict): The keyword arguments to pass to the function.
634
635 Returns:
636 Result: A Result instance containing the result of the function call.
637 """
638 return Result(func(*args, **kwds))
639
640 def close(self) -> NonDaemonicPool:
641 """Close the pool."""
642
643 def join(self) -> None:
644 """Wait for the worker processes to finish."""
645
646 def map(
647 self, func: Callable, iterable: Iterable, chunksize: None | int = None
648 ) -> list:
649 """Map function over iterable using the given function.
650
651 Args:
652 func (Callable): The function to apply to each item in the
653 iterable.
654 iterable (Iterable): The iterable to process.
655 chunksize (None | int, optional): The size of each chunk to
656 process. Not used in this fake pool.
657
658 Returns:
659 list: A list of results from applying the function to each item
660 in the iterable.
661 """
662 return func(iterable)
663
664 def terminate(self) -> None:
665 """Terminate the pool."""
666
667
668 class FakeQueue:
669 """Fake queue."""
670
671 def __init__(self) -> None:
672 self.queue = []
673
674 def get(self, block: bool = True, timeout: None | float = None) -> None | Any: # noqa: ANN401
675 """Get an item from the queue.
676
677 Args:
678 block (bool): If True, block until an item is available.
679 timeout (None | float): Timeout for blocking, not used in this fake
680 queue.
681
682 Raises:
683 Empty: If the queue is empty.
684
685 Returns:
686 None | Any: The item from the queue, or None if the queue is empty.
687 """
688 try:
689 return self.queue.pop()
690 except Exception as e:
691 raise Empty from e
692
693 def join(self) -> None:
694 """Wait until all items in the queue have been processed."""
695
696 def put(self, item: Any, block: bool = True, timeout: None | float = None) -> None: # noqa: ANN401
697 """Put an item into the queue.
698
699 Args:
700 item (Any): The item to be added to the queue.
701 block (bool): If True, block until the item is added.
702 timeout (None | float): Timeout for blocking, not used in this fake
703 queue.
704 """
705 self.queue.append(item)
706
707
708 class Result:
709 """Result proxy.
710
711 Args:
712 result (Any): The result to be returned by the get() method.
713 """
714
715 def __init__(self, result: Any) -> None: # noqa: ANN401
716 self.result = result
717
718 def get(self) -> WorkerFunc:
719 """Return result.
720
721 Returns:
722 WorkerFunc: WorkerFunc instance as the result.
723 """
724 return self.result