L iS dZddlmZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl mZddlmZmZmZddlmZddlmZddlmZd d lmZd d lmZmZmZmZm Z m!Z!m"Z"d d l#m$Z$m%Z%d d l&m'Z'd dl(m)Z)m*Z*e"e!dZ+da,dZ-dZ.ddhZ/eee+d<d dl0m1Z1ee+d<da,dZ.e jdZ3dZ4de4iZ5e$de$de$de$de$de$de$de$ddZ6dZ7dZ8dZ9e6de6de6dfd Z:e6de6de6dfd!Z;Gd"d#Z<Gd$d%e<Z=dZ>e?ed&rCejjd'd(jxsdZCeCejeC)Z>Gd*d+eEZFd,ZGd-ZHd.ZId8d/ZJd0ZKd1ZLGd2d3eEZMd8d4ZNd9d5ZOGd6d7e)ZPy):z+ Helpers for embarrassingly parallel code. )divisionN) nullcontext)floorlog10sqrt) TimeoutError)Integral)uuid4)mp)AutoBatchingMixinFallbackToBackend LokyBackendMultiprocessingBackendParallelBackendBaseSequentialBackendThreadingBackend) _Sentinel eval_expr)memstr_to_bytes)Loggershort_format_time) threading sequentialrmultiprocessingloky)rch ddlm}td|y#t$r}d}t||d}~wwxYw)zDRegister Dask Backend if called with parallel_config(backend="dask")r )DaskDistributedBackenddaskzTo use the dask.distributed backend you must install both the `dask` and distributed modules. See https://dask.pydata.org/en/latest/install.html for more information.N)_daskrregister_parallel_backend ImportError)remsgs U/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/joblib/parallel.py_register_daskr&Hs> &1!&*@A &  #A%&s 1,1r) default_value1Mr)backendn_jobsverbose temp_folder max_nbytes mmap_modepreferrequire) processesthreadsN) sharedmemNcZ|t|ur|S||t|ur||S|jS)zReturn the value of a parallel config parameter Explicitly setting it in Parallel has priority over setting in a parallel_(config/backend) context manager. )default_parallel_configr')paramcontext_configkeys r%_get_config_paramr:osC  +C00 c"9#">>c""   r0r1r,cRt|||\}}ttd|d}||fS)!Return the active default backendr+)_get_active_backendr:r6)r0r1r,r*configr+s r%get_active_backendr@s4 *&'7COGV 6x@&( SF F?r;cDttdt}ttd|d}t||d}t||d}t||d}|tvrt d|dt|t vrt d|d t |d k(r|d k(r t d d }|ttd}d}|j}t|dd}t|dd}|d k(xr| xs| xr |dk(xr| } | xr |d k(xr|} | rmtt|} |dk\r<|r:td| jjd|jjd|j} d| d<| | fS| r%tt|} | |jfS||fS)r=r?r*r0r1r,zprefer=z. is not a valid backend hint, expected one of zrequire=z4 is not a valid backend constraint, expected one of r2r4zJprefer == 'processes' and require == 'sharedmem' are inconsistent settingsTr nesting_levelF uses_threadssupports_sharedmemr3 zUsing z as joblib backend instead of z8 as the latter does not provide shared memory semantics.r r+)getattr_backendr6r:VALID_BACKEND_HINTS ValueErrorVALID_BACKEND_CONSTRAINTSBACKENDSDEFAULT_BACKENDrCDEFAULT_THREAD_BACKENDprint __class____name__copyDEFAULT_PROCESS_BACKEND)r0r1r,backend_configr*explicit_backendrCrDrE force_threadsforce_processessharedmem_backend thread_configprocess_backends r%r>r>s.Xx1HIN *NIGv~x @FCGCG ((fX23 5  //wi 89 ;  K!7 X  ?+!< ))M7NE:L *>F +F4F0F I9!4I\9I+*Uv/DUO%%;<'  b=- *44==>?--4->->-G-G,HIJJ  '++- "# h -//##:;-X 3 3 555 N ""r;c veZdZdZedfededededededed d d d Zd ZdZdZdZ y )parallel_configaSet the default backend or configuration for :class:`~joblib.Parallel`. This is an alternative to directly passing keyword arguments to the :class:`~joblib.Parallel` class constructor. It is particularly useful when calling into library code that uses joblib internally but does not expose the various parallel configuration arguments in its own API. Parameters ---------- backend: str or ParallelBackendBase instance, default=None If ``backend`` is a string it must match a previously registered implementation using the :func:`~register_parallel_backend` function. By default the following backends are available: - 'loky': single-host, process-based parallelism (used by default), - 'threading': single-host, thread-based parallelism, - 'multiprocessing': legacy single-host, process-based parallelism. 'loky' is recommended to run functions that manipulate Python objects. 'threading' is a low-overhead alternative that is most efficient for functions that release the Global Interpreter Lock: e.g. I/O-bound code or CPU-bound code in a few calls to native code that explicitly releases the GIL. Note that on some rare systems (such as pyodide), multiprocessing and loky may not be available, in which case joblib defaults to threading. In addition, if the ``dask`` and ``distributed`` Python packages are installed, it is possible to use the 'dask' backend for better scheduling of nested parallel calls without over-subscription and potentially distribute parallel calls over a networked cluster of several hosts. It is also possible to use the distributed 'ray' backend for distributing the workload to a cluster of nodes. See more details in the Examples section below. Alternatively the backend can be passed directly as an instance. n_jobs: int, default=None The maximum number of concurrently running jobs, such as the number of Python worker processes when ``backend="loky"`` or the size of the thread-pool when ``backend="threading"``. This argument is converted to an integer, rounded below for float. If -1 is given, `joblib` tries to use all CPUs. The number of CPUs ``n_cpus`` is obtained with :func:`~cpu_count`. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. For instance, using ``n_jobs=-2`` will result in all CPUs but one being used. This argument can also go above ``n_cpus``, which will cause oversubscription. In some cases, slight oversubscription can be beneficial, e.g., for tasks with large I/O operations. If 1 is given, no parallel computing code is used at all, and the behavior amounts to a simple python `for` loop. This mode is not compatible with `timeout`. None is a marker for 'unset' that will be interpreted as n_jobs=1 unless the call is performed under a :func:`~parallel_config` context manager that sets another value for ``n_jobs``. If n_jobs = 0 then a ValueError is raised. verbose: int, default=0 The verbosity level: if non zero, progress messages are printed. Above 50, the output is sent to stdout. The frequency of the messages increases with the verbosity level. If it more than 10, all iterations are reported. temp_folder: str or None, default=None Folder to be used by the pool for memmapping large arrays for sharing memory with worker processes. If None, this will try in order: - a folder pointed by the ``JOBLIB_TEMP_FOLDER`` environment variable, - ``/dev/shm`` if the folder exists and is writable: this is a RAM disk filesystem available by default on modern Linux distributions, - the default system temporary folder that can be overridden with ``TMP``, ``TMPDIR`` or ``TEMP`` environment variables, typically ``/tmp`` under Unix operating systems. max_nbytes: int, str, or None, optional, default='1M' Threshold on the size of arrays passed to the workers that triggers automated memory mapping in temp_folder. Can be an int in Bytes, or a human-readable string, e.g., '1M' for 1 megabyte. Use None to disable memmapping of large arrays. mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, default='r' Memmapping mode for numpy arrays passed to workers. None will disable memmapping, other modes defined in the numpy.memmap doc: https://numpy.org/doc/stable/reference/generated/numpy.memmap.html Also, see 'max_nbytes' parameter documentation for more details. prefer: str in {'processes', 'threads'} or None, default=None Soft hint to choose the default backend. The default process-based backend is 'loky' and the default thread-based backend is 'threading'. Ignored if the ``backend`` parameter is specified. require: 'sharedmem' or None, default=None Hard constraint to select the backend. If set to 'sharedmem', the selected backend will be single-host and thread-based. inner_max_num_threads: int, default=None If not None, overwrites the limit set on the number of threads usable in some third-party library threadpools like OpenBLAS, MKL or OpenMP. This is only used with the ``loky`` backend. backend_params: dict Additional parameters to pass to the backend constructor when backend is a string. Notes ----- Joblib tries to limit the oversubscription by limiting the number of threads usable in some third-party library threadpools like OpenBLAS, MKL or OpenMP. The default limit in each worker is set to ``max(cpu_count() // effective_n_jobs, 1)`` but this limit can be overwritten with the ``inner_max_num_threads`` argument which will be used to set this limit in the child processes. .. versionadded:: 1.3 Examples -------- >>> from operator import neg >>> with parallel_config(backend='threading'): ... print(Parallel()(delayed(neg)(i + 1) for i in range(5))) ... [-1, -2, -3, -4, -5] To use the 'ray' joblib backend add the following lines: >>> from ray.util.joblib import register_ray # doctest: +SKIP >>> register_ray() # doctest: +SKIP >>> with parallel_config(backend="ray"): # doctest: +SKIP ... print(Parallel()(delayed(neg)(i + 1) for i in range(5))) [-1, -2, -3, -4, -5] r*r+r,r-r.r/r0r1N)r+r,r-r.r/r0r1inner_max_num_threadsc ttdt|_|j|| fi| }||||||||d} |jj |_|j j| jD cic]\} } t| tr| | c} } ttd|j ycc} } w)Nr?)r+r,r-r.r/r0r1r*) rGrHr6old_parallel_config_check_backendrRr\updateitems isinstancersetattr)selfr*r+r,r-r.r/r0r1r]backend_params new_configkvs r%__init__zparallel_config.__init__ks$+8X?V#W %$%%g/DWW&$"   $77<<> ##(..0 Qda 1i8PQT Q  (D$8$89 Rs C C c |tdur|t|dkDr td|St|tr|t vr|t vrt |}|np|tvr"Q& : ! ,$$--./22 99 >3 >9,AG )  (!55i@N!8!CC ! . < < $1G !r;c|jSN)r\res r% __enter__zparallel_config.__enter__s###r;c$|jyr) unregister)retypevalue tracebacks r%__exit__zparallel_config.__exit__s  r;c:ttd|jy)Nr?)rdrHr_rs r%rzparallel_config.unregisters(D$<$<=r;) rQ __module__ __qualname____doc__r6rjr`rrrrtr;r%r\r\spIZ( 2":'x0' 2+M:*<8)+6&x0' 2"":H8t$>r;r\c,eZdZdZ dfd ZdZxZS)parallel_backenda Change the default backend used by Parallel inside a with block. .. warning:: It is advised to use the :class:`~joblib.parallel_config` context manager instead, which allows more fine-grained control over the backend configuration. If ``backend`` is a string it must match a previously registered implementation using the :func:`~register_parallel_backend` function. By default the following backends are available: - 'loky': single-host, process-based parallelism (used by default), - 'threading': single-host, thread-based parallelism, - 'multiprocessing': legacy single-host, process-based parallelism. 'loky' is recommended to run functions that manipulate Python objects. 'threading' is a low-overhead alternative that is most efficient for functions that release the Global Interpreter Lock: e.g. I/O-bound code or CPU-bound code in a few calls to native code that explicitly releases the GIL. Note that on some rare systems (such as Pyodide), multiprocessing and loky may not be available, in which case joblib defaults to threading. You can also use the `Dask `_ joblib backend to distribute work across machines. This works well with scikit-learn estimators with the ``n_jobs`` parameter, for example:: >>> import joblib # doctest: +SKIP >>> from sklearn.model_selection import GridSearchCV # doctest: +SKIP >>> from dask.distributed import Client, LocalCluster # doctest: +SKIP >>> # create a local Dask cluster >>> cluster = LocalCluster() # doctest: +SKIP >>> client = Client(cluster) # doctest: +SKIP >>> grid_search = GridSearchCV(estimator, param_grid, n_jobs=-1) ... # doctest: +SKIP >>> with joblib.parallel_backend("dask", scatter=[X, y]): # doctest: +SKIP ... grid_search.fit(X, y) It is also possible to use the distributed 'ray' backend for distributing the workload to a cluster of nodes. To use the 'ray' joblib backend add the following lines:: >>> from ray.util.joblib import register_ray # doctest: +SKIP >>> register_ray() # doctest: +SKIP >>> with parallel_backend("ray"): # doctest: +SKIP ... print(Parallel()(delayed(neg)(i + 1) for i in range(5))) [-1, -2, -3, -4, -5] Alternatively the backend can be passed directly as an instance. By default all available workers will be used (``n_jobs=-1``) unless the caller passes an explicit value for the ``n_jobs`` parameter. This is an alternative to passing a ``backend='backend_name'`` argument to the :class:`~Parallel` class constructor. It is particularly useful when calling into library code that uses joblib internally but does not expose the backend argument in its own API. >>> from operator import neg >>> with parallel_backend('threading'): ... print(Parallel()(delayed(neg)(i + 1) for i in range(5))) ... [-1, -2, -3, -4, -5] Joblib also tries to limit the oversubscription by limiting the number of threads usable in some third-party library threadpools like OpenBLAS, MKL or OpenMP. The default limit in each worker is set to ``max(cpu_count() // effective_n_jobs, 1)`` but this limit can be overwritten with the ``inner_max_num_threads`` argument which will be used to set this limit in the child processes. .. versionadded:: 0.10 See Also -------- joblib.parallel_config: context manager to change the backend configuration. c t|d|||d||jd|_n#|jd|jdf|_|jd|jdf|_y)N)r*r+r]r*r+rt)superrjr_old_backend_and_jobsr\new_backend_and_jobs)rer*r+r]rfrPs r%rjzparallel_backend.__init__$s  "7     # # +(,D %((3((2)D %   +   *% !r;c|jSr)rrs r%rzparallel_backend.__enter__:s(((r;)N)rQrrrrjr __classcell__rPs@r%rrsNb9= ,)r;r get_contextJOBLIB_START_METHOD)methodc,eZdZdZ ddZdZdZdZy) BatchedCallszCWrap a sequence of (func, args, kwargs) tuples as a single callableNct||_t|j|_||_t |t r|\|_|_n|dc|_|_|||_ yi|_ yr) listrbru_size_reducer_callbackrctuplerH_n_jobs _pickle_cache)reiterator_slicebackend_and_jobsreducer_callback pickle_caches r%rjzBatchedCalls.__init__Msf.) _ !1 & .*: 'DM4<+;D 'DM4<-9-E\2r;c t|j|j5|jDcgc]\}}}||i|c}}}cdddScc}}}w#1swYyxYw)N)r*r+)r\rHrrb)refuncargskwargss r%__call__zBatchedCalls.__call__[s^T]]4<< H PDHJJOO.@dD&D$)&)O P PO P PsAA AAA$c|j|jt|j|j|jfd|j ffSr)rrrbrHrrrs r% __reduce__zBatchedCalls.__reduce__asL  ! ! -  " " $  ZZ$--6d>P>P Q  r;c|jSr)rrs r%__len__zBatchedCalls.__len__js zzr;)NN)rQrrrrjrrrrtr;r%rrJs"MUY NP  r;rDoneErrorPendingc<tytj|S)aReturn the number of CPUs. This delegates to loky.cpu_count that takes into account additional constraints such as Linux CFS scheduler quotas (typically set by container runtimes such as docker) and CPU affinity (for instance using the taskset command on Linux). Parameters ---------- only_physical_cores : boolean, default=False If True, does not take hyperthreading / SMT logical cores into account. r only_physical_cores)r r cpu_countrs r%rrws z >>.A BBr;c|sy|dkDry|dk(rydd|z dzz}t||z }t|dz|z }t|t|k(S) zReturns False for indices increasingly apart, the distance depending on the value of verbose. We use a lag increasing as the square of index TrFFrg? ror )rint)indexr,scale next_scales r%_verbosity_filterrse  2 zR'\a''G  !EuqyG+,J z?c%j ((r;cjfd} tj|}|S#t$rY|SwxYw)z6Decorator used to capture the arguments of a function.c||fSrrt)rrfunctions r%delayed_functionz!delayed..delayed_functionsv%%r;) functoolswrapsAttributeError)rrs` r%delayedrsF&;49??845EF  ;: ;s % 22cFeZdZdZdZdZdZdZdZdZ dZ d Z d Z y ) BatchCompletionCallBackaCallback to keep track of completed results and schedule the next tasks. This callable is executed by the parent process whenever a worker process has completed a batch of tasks. It is used for progress reporting, to update estimate of the batch processing duration and to schedule the next batch of tasks to be processed. It is assumed that this callback will always be triggered by the backend right after the end of a task, in case of success as well as in case of failure. c||_||_||_|j|_d|_d|_|jjsd|_ yt|_ yr) dispatch_timestamp batch_sizeparallel_call_idparallel_call_id_completion_timeout_counterjobrHsupports_retrieve_callbackstatus TASK_PENDING)rerrrs r%rjz BatchCompletionCallBack.__init__sX"4$  ( 1 1+/(  ;;DK'DKr;c||_y)z)Register the object returned by `submit`.N)r)rers r% register_jobz$BatchCompletionCallBack.register_jobs r;cT|jj}|jr|jS |j |j |}t |t}|j||jS#t$r}t |t}Yd}~@d}~wwxYw)aHReturns the raw result of the task that was submitted. If the task raised an exception rather than returning, this same exception will be raised instead. If the backend supports the retrieval callback, it is assumed that this method is only called after the result has been registered. It is ensured by checking that `self.status(timeout)` does not return TASK_PENDING. In this case, `get_result` directly returns the registered result (or raise the registered exception). For other backends, there are no such assumptions, but `get_result` still needs to synchronously retrieve the result before it can return it or raise. It will block at most `self.timeout` seconds waiting for retrieval to complete, after that it raises a TimeoutError. timeoutresultrN) rrHr_return_or_raiseretrieve_resultrdict TASK_DONE BaseException TASK_ERROR_register_outcome)rerr*routcomer#s r% get_resultz"BatchCompletionCallBack.get_results$--((  - -((* * 8,,TXXw,GF&;G w'$$&&  8!J7G 8s.B B' B""B'cl |jtk(r |j|j|`S#|`wxYwr)rr_resultrs r%rz(BatchCompletionCallBack._return_or_raises/ {{j(ll"<<  s*/3c"||jtk7r |jStj}|j||_||jz |kDr*t t t }|j||jS)zGet the status of the task. This function also checks if the timeout has been reached and register the TimeoutError outcome when it is the case. r)rrtimerrrrr)rernowrs r% get_statusz"BatchCompletionCallBack.get_status sx ?dkk\9;; iik  + + 3/2D , $22 2g =,.DG  " "7 +{{r;c|jjjs|jy|jj5|jj |j k7r dddy|jjr dddy|j|i|}dddr|jyy#1swYxYw)z@Function called by the callback thread after a job is completed.N) rrHr _dispatch_new_lockrr _aborting_retrieve_result)rerr job_succeededs r%rz BatchCompletionCallBack.__call__"s }}%%@@     ]]  C }}%%)>)>>  C C}}&& C C2D114B6BM C"      # C Cs%C6CCC ctj|jz }|jjj |j ||jj 5|jxj|j z c_|jj|jj|jjdddy#1swYyxYw)z1Schedule the next batch of tasks to be processed.N) rrrrHbatch_completedrrn_completed_tasksprint_progress_original_iterator dispatch_next)rethis_batch_durations r%rz%BatchCompletionCallBack._dispatch_newCs#iikD,C,CC ..t@ST]]  . MM + +t > + MM ( ( *}}//; ++-  . . .s (A4C%%C.c |jjj|}tt|}|j||dtk7S#t $r"}d|_t|t}Yd}~Cd}~wwxYw)zFetch and register the outcome of a task. Return True if the task succeeded, False otherwise. This function is only called by backends that support retrieving the task result in the callback thread. )rrNrr) rrHretrieve_result_callbackrrr __traceback__rr)reoutrrr#s r%rz(BatchCompletionCallBack._retrieve_resultQsr 8]]++DDSIF)F;G w'x J..  8"AO!J7G 8s6A BA;;Bc|jj5|jtdfvr dddy|d|_ddd|d|_d|_|jt k(r"d|j_d|j_|jjry|jj5|jjj|dddy#1swYxYw#1swYyxYw)ztRegister the outcome of a task. This method can be called only once, future calls will be ignored. NrrT) rrrrrrr _exceptionrreturn_ordered_jobsappend)rers r%rz)BatchCompletionCallBack._register_outcomegs]]  ,{{<"66 , ,"(+DK , x(  ;;* $'+DMM $&*DMM # == ' '  ]]  - MM   & &t , - -) , ,( - -sC* C*;&C6*C36C?N) rQrrrrjrrrrrrrrrtr;r%rrs6 "'0"'H0!B ./,-r;rc |t|<|r|ayy)aRegister a new Parallel backend factory. The new backend can then be selected by passing its name as the backend argument to the :class:`~Parallel` class. Moreover, the default backend can be overwritten globally by setting make_default=True. The factory can be any callable that takes no argument and return an instance of ``ParallelBackendBase``. Warning: this function is experimental and subject to change in a future version of joblib. .. versionadded:: 0.10 N)rLrM)namefactory make_defaults r%r!r!sHTNr;cT|dk(ryt\}}||}|j|S)aeDetermine the number of jobs that can actually run in parallel n_jobs is the number of workers requested by the callers. Passing n_jobs=-1 means requesting all available workers for instance matching the number of CPU cores on the worker host(s). This method should return a guesstimate of the number of workers that can actually perform work concurrently with the currently enabled default backend. The primary use case is to make it possible for the caller to know in how many chunks to slice the work. In general working on larger data chunks is more efficient (less scheduling overhead and better use of CPU cache prefetching heuristics) as long as all the workers have enough work to do. Warning: this function is experimental and subject to change in a future version of joblib. .. versionadded:: 0.10 r )r+)r@effective_n_jobs)r+r*backend_n_jobss r%rrs9*{02G^ ~  # #6 # 22r;c eZdZdZededdedddded ed ed ed ed f fd ZdZdZdZdZ dZ dZ dZ dZ dZdZdZdZdZdZdZdZdZd Zd!Zd"Zd#Zd$Zd%Zd&ZxZS)'Parallela/Helper class for readable parallel mapping. Read more in the :ref:`User Guide `. Parameters ---------- n_jobs: int, default=None The maximum number of concurrently running jobs, such as the number of Python worker processes when ``backend="loky"`` or the size of the thread-pool when ``backend="threading"``. This argument is converted to an integer, rounded below for float. If -1 is given, `joblib` tries to use all CPUs. The number of CPUs ``n_cpus`` is obtained with :func:`~cpu_count`. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. For instance, using ``n_jobs=-2`` will result in all CPUs but one being used. This argument can also go above ``n_cpus``, which will cause oversubscription. In some cases, slight oversubscription can be beneficial, e.g., for tasks with large I/O operations. If 1 is given, no parallel computing code is used at all, and the behavior amounts to a simple python `for` loop. This mode is not compatible with ``timeout``. None is a marker for 'unset' that will be interpreted as n_jobs=1 unless the call is performed under a :func:`~parallel_config` context manager that sets another value for ``n_jobs``. If n_jobs = 0 then a ValueError is raised. backend: str, ParallelBackendBase instance or None, default='loky' Specify the parallelization backend implementation. Supported backends are: - "loky" used by default, can induce some communication and memory overhead when exchanging input and output data with the worker Python processes. On some rare systems (such as Pyiodide), the loky backend may not be available. - "multiprocessing" previous process-based backend based on `multiprocessing.Pool`. Less robust than `loky`. - "threading" is a very low-overhead backend but it suffers from the Python Global Interpreter Lock if the called function relies a lot on Python objects. "threading" is mostly useful when the execution bottleneck is a compiled extension that explicitly releases the GIL (for instance a Cython loop wrapped in a "with nogil" block or an expensive call to a library such as NumPy). - finally, you can register backends by calling :func:`~register_parallel_backend`. This will allow you to implement a backend of your liking. It is not recommended to hard-code the backend name in a call to :class:`~Parallel` in a library. Instead it is recommended to set soft hints (prefer) or hard constraints (require) so as to make it possible for library users to change the backend from the outside using the :func:`~parallel_config` context manager. return_as: str in {'list', 'generator', 'generator_unordered'}, default='list' If 'list', calls to this instance will return a list, only when all results have been processed and retrieved. If 'generator', it will return a generator that yields the results as soon as they are available, in the order the tasks have been submitted with. If 'generator_unordered', the generator will immediately yield available results independently of the submission order. The output order is not deterministic in this case because it depends on the concurrency of the workers. prefer: str in {'processes', 'threads'} or None, default=None Soft hint to choose the default backend if no specific backend was selected with the :func:`~parallel_config` context manager. The default process-based backend is 'loky' and the default thread-based backend is 'threading'. Ignored if the ``backend`` parameter is specified. require: 'sharedmem' or None, default=None Hard constraint to select the backend. If set to 'sharedmem', the selected backend will be single-host and thread-based even if the user asked for a non-thread based backend with :func:`~joblib.parallel_config`. verbose: int, default=0 The verbosity level: if non zero, progress messages are printed. Above 50, the output is sent to stdout. The frequency of the messages increases with the verbosity level. If it more than 10, all iterations are reported. timeout: float or None, default=None Timeout limit for each task to complete. If any task takes longer a TimeOutError will be raised. Only applied when n_jobs != 1 pre_dispatch: {'all', integer, or expression, as in '3*n_jobs'}, default='2*n_jobs' The number of batches (of tasks) to be pre-dispatched. Default is '2*n_jobs'. When batch_size="auto" this is reasonable default and the workers should never starve. Note that only basic arithmetic are allowed here and no modules can be used in this expression. batch_size: int or 'auto', default='auto' The number of atomic tasks to dispatch at once to each worker. When individual evaluations are very fast, dispatching calls to workers can be slower than sequential computation because of the overhead. Batching fast computations together can mitigate this. The ``'auto'`` strategy keeps track of the time it takes for a batch to complete, and dynamically adjusts the batch size to keep the time on the order of half a second, using a heuristic. The initial batch size is 1. ``batch_size="auto"`` with ``backend="threading"`` will dispatch batches of a single task at a time as the threading backend has very little overhead and using larger batch size has not proved to bring any gain in that case. temp_folder: str or None, default=None Folder to be used by the pool for memmapping large arrays for sharing memory with worker processes. If None, this will try in order: - a folder pointed by the JOBLIB_TEMP_FOLDER environment variable, - /dev/shm if the folder exists and is writable: this is a RAM disk filesystem available by default on modern Linux distributions, - the default system temporary folder that can be overridden with TMP, TMPDIR or TEMP environment variables, typically /tmp under Unix operating systems. Only active when ``backend="loky"`` or ``"multiprocessing"``. max_nbytes int, str, or None, optional, default='1M' Threshold on the size of arrays passed to the workers that triggers automated memory mapping in temp_folder. Can be an int in Bytes, or a human-readable string, e.g., '1M' for 1 megabyte. Use None to disable memmapping of large arrays. Only active when ``backend="loky"`` or ``"multiprocessing"``. mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, default='r' Memmapping mode for numpy arrays passed to workers. None will disable memmapping, other modes defined in the numpy.memmap doc: https://numpy.org/doc/stable/reference/generated/numpy.memmap.html Also, see 'max_nbytes' parameter documentation for more details. backend_kwargs: dict, optional Additional parameters to pass to the backend `configure` method. Notes ----- This object uses workers to compute in parallel the application of a function to many different arguments. The main functionality it brings in addition to using the raw multiprocessing or concurrent.futures API are (see examples for details): * More readable code, in particular since it avoids constructing list of arguments. * Easier debugging: - informative tracebacks even when the error happens on the client side - using 'n_jobs=1' enables to turn off parallel computing for debugging without changing the codepath - early capture of pickling errors * An optional progress meter. * Interruption of multiprocesses jobs with 'Ctrl-C' * Flexible pickling control for the communication to and from the worker processes. * Ability to use shared memory efficiently with worker processes for large numpy-based datastructures. Note that the intended usage is to run one call at a time. Multiple calls to the same Parallel object will result in a ``RuntimeError`` Examples -------- A simple example: >>> from math import sqrt >>> from joblib import Parallel, delayed >>> Parallel(n_jobs=1)(delayed(sqrt)(i**2) for i in range(10)) [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] Reshaping the output when the function has several return values: >>> from math import modf >>> from joblib import Parallel, delayed >>> r = Parallel(n_jobs=1)(delayed(modf)(i/2.) for i in range(10)) >>> res, i = zip(*r) >>> res (0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5) >>> i (0.0, 0.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0) The progress meter: the higher the value of `verbose`, the more messages: >>> from time import sleep >>> from joblib import Parallel, delayed >>> r = Parallel(n_jobs=2, verbose=10)( ... delayed(sleep)(.2) for _ in range(10)) #doctest: +SKIP [Parallel(n_jobs=2)]: Done 1 tasks | elapsed: 0.6s [Parallel(n_jobs=2)]: Done 4 tasks | elapsed: 0.8s [Parallel(n_jobs=2)]: Done 10 out of 10 | elapsed: 1.4s finished Traceback example, note how the line of the error is indicated as well as the values of the parameter passed to the function that triggered the exception, even though the traceback happens in the child process: >>> from heapq import nlargest >>> from joblib import Parallel, delayed >>> Parallel(n_jobs=2)( ... delayed(nlargest)(2, n) for n in (range(4), 'abcde', 3)) ... # doctest: +SKIP ----------------------------------------------------------------------- Sub-process traceback: ----------------------------------------------------------------------- TypeError Mon Nov 12 11:37:46 2012 PID: 12934 Python 2.7.3: /usr/bin/python ........................................................................ /usr/lib/python2.7/heapq.pyc in nlargest(n=2, iterable=3, key=None) 419 if n >= size: 420 return sorted(iterable, key=key, reverse=True)[:n] 421 422 # When key is none, use simpler decoration 423 if key is None: --> 424 it = izip(iterable, count(0,-1)) # decorate 425 result = _nlargest(n, it) 426 return map(itemgetter(0), result) # undecorate 427 428 # General case, slowest method TypeError: izip argument #1 must support iteration _______________________________________________________________________ Using pre_dispatch in a producer/consumer situation, where the data is generated on the fly. Note how the producer is first called 3 times before the parallel loop is initiated, and then called to generate new data on the fly: >>> from math import sqrt >>> from joblib import Parallel, delayed >>> def producer(): ... for i in range(6): ... print('Produced %s' % i) ... yield i >>> out = Parallel(n_jobs=2, verbose=100, pre_dispatch='1.5*n_jobs')( ... delayed(sqrt)(i) for i in producer()) #doctest: +SKIP Produced 0 Produced 1 Produced 2 [Parallel(n_jobs=2)]: Done 1 jobs | elapsed: 0.0s Produced 3 [Parallel(n_jobs=2)]: Done 2 jobs | elapsed: 0.0s Produced 4 [Parallel(n_jobs=2)]: Done 3 jobs | elapsed: 0.0s Produced 5 [Parallel(n_jobs=2)]: Done 4 jobs | elapsed: 0.0s [Parallel(n_jobs=2)]: Done 6 out of 6 | elapsed: 0.0s remaining: 0.0s [Parallel(n_jobs=2)]: Done 6 out of 6 | elapsed: 0.0s finished r+r*rr,Nz 2 * n_jobsautor-r.r/r0r1c *t|| td}t| | |\}}|j}t ||d|_||_||_|dvrtd|d||_ |dk7|_ |dk7|_ i| | d f|d f| d f| d f| d f|dffDcic]\}}|t |||c}}|_ t|jd tr%t!|jd |jd <t#d|jddz |jd<t$t$|jd<n1t't(dr!t)j*|jd<|tdus||}nt|t,r|j||_nt'|dr(t'|dr||jd<t/|}nr|t0vrW|t2vrOt5j6d|dt8dt:dt0t8t0|<t1t8|}n t0|}||}t ||d}| |jB} tE|}||_#| dk(rtI|dd std!|z|d"k(st|tJr |dkDr||_&ntd#|zt|tNs|jr'|jPstd$jS||tUjV|_,t[j\|_/ta|_1te|_3tijj|_6d|_7||_8d |_9d |_:twjx|_=d|_>ycc}}w#t<$r2}td|dt?t0jA|d}~wwxYw#t$r tdwxYw)%Nr+)r0r1r,r,>r generatorgenerator_unorderedzlExpected `return_as` parameter to be a string equal to "list","generator" or "generator_unordered", but got z instead.rrr.r-r/r0r1r2contextrr*PoolLockrBrlrmrnrorprrrsz$n_jobs could not be converted to intr4rEFz)Backend %s does not support shared memoryr z8batch_size must be 'auto' or a positive integer, got: %rz(Backend {} does not support return_as={})?rrjr6r>rCr:r,r pre_dispatchrJ return_asreturn_generatorr_backend_kwargsrcrvrmaxDEFAULT_MP_CONTEXThasattrr rrrrLrxryrzrMr{KeyErrorr|r}default_n_jobsrr+rGr rrsupports_return_generatorformatrRLockr collectionsdequerset _jobs_setr_pending_outputsqueueQueue_ready_batchesrrH_running_managed_backendr hex_id _call_ref)rer+r*rr,rrrr-r.r/r0r1backend_kwargsactive_backendr8rCr7rhbackend_factoryr#rPs r%rjzParallel.__init__sC"  >,X6F)<7G* &'44 (.)L  ( H HBBKM  # )V 3'+@@   . -0 ,X&i(i( ! E1$UNA>>   d**<8# >1@$$\22D  .+.a1E1Ei1PSU1U*VY'  ).@D  + R '.0nn.>D  + -i8 8GO$G !4 5$$,(5% Wf %''6*B/6D  +,=IG H $4L)L MM"7),00?/@C   !) 9HW /mLG "*7"3 &MBG"6>8D >++F E[F k !'';OQV*WH7RS S  :j(#C UV(DOJZW '#45$$W-N-N >EE#*DJ$**,DJ UDN$(FD !"'++-D %)D "   %7;;M j  x}} 79  ECD D Es* N9 N?. O=? O:-O55O:=PcBd|_d|_|j|S)NTF)r(_calling_initialize_backendrs r%rzParallel.__enter__Ts" $    " r;cd|_|jr|jr|j|j y)NF)r(rr0_abort_terminate_and_reset)reexc_type exc_valuers r%rzParallel.__exit__Zs. %  T]] KKM !!#r;c |jjd|j|d|j}|jc|jj sMt jdj|jjj|j|S#t$r,}|j|_|j}Yd}~|Sd}~wwxYw)z?Build a process or thread pool and return the number of workers)r+rNzThe backend class {!r} does not support timeout. You have set 'timeout={}' in Parallel but the 'timeout' parameter will not be used.rt)rH configurer+rrsupports_timeoutryrzrrPrQrr*r1)rer+r#s r%r1zParallel._initialize_backend`s 0,T]],,{{T595I5IF||' 0N0N @@F //88$,,A ! 0IIDM--/F  0sB"B&& C/!CCcf|jr%|jj|jSy)Nr )rHrr+rs r%_effective_n_jobszParallel._effective_n_jobsvs% ====11$++> >r;ct|jdr&|jr|jjd|_|js|jj yy)N stop_callF)rrHr0r=r( terminaters r%r4zParallel._terminate_and_reset{sK 4==+ .4== MM # # % $$ MM # # %%r;cH|jryt|}|xj|z c_|xjdz c_t j}t |||}|j ||jj||}|j|y)zQueue the batch for computing, with or without multiprocessing WARNING: this method is not thread-safe: it should be only called indirectly via dispatch_one_batch. Nr )callback) rrun_dispatched_tasksn_dispatched_batchesrr_register_new_jobrHsubmitr)rebatchrr batch_trackerrs r% _dispatchzParallel._dispatchs >> Z  :- !!Q&!!YY[/0BJPTU  }-mm""5="A""3'r;c|jr|jj|y|jj |yr)rrrr"add)rerFs r%rCzParallel._register_new_jobs/    JJ  m , NN  } -r;cX|j|jsd|_d|_yy)aDispatch more data for parallel processing This method is meant to be called concurrently by the multiprocessing callback. We rely on the thread-safety of dispatch_one_batch to protect against concurrent consumption of the unprotected iterator. FN)dispatch_one_batchr _iteratingrs r%rzParallel.dispatch_nexts-&&t'>'>?#DO&*D #@r;c |jry|j}|j5 |jj d}t)|dk(r dddy|j=| dddy#t j $r|j}||z} ttj||}n#t$r|}t|jt j rd|_td||}|j!||j#t%|t&Yd}~Ydddyd}~wwxYwt)|dk(r Ydddy||j*ur*t)||krt-dt)|d|zz} nt-dt)||z} t/dt)|| D]]} t1|| | | z|j2j5|j6|j8}|jj;|_|jj d}YwxYw#1swYyxYw) aTPrefetch the tasks for the next batch and dispatch them. The effective size of the batch is computed here. If there are no more jobs to dispatch, return False, else return True. The iterator consumption and dispatching is protected by the same lock so calling this function should be thread safe. F)blockNrrTr rF)r_get_batch_sizerr&getr$Empty_cached_effective_n_jobsr itertoolsislice Exceptionrc __context__ __cause__rrCrrrrurrrangerrHget_nested_backendrrputrG) reiteratorrtasksr+big_batch_sizerTr#rFfinal_batch_sizeis r%rKzParallel.dispatch_one_batchs@ >>))+ ZZD 7 =++//e/<n5zQCD D Fu%ID D ;;5 =66!+f!4 !)"2"28^"LMF  "!--= '+ $;Az4$PM**=9!33D*4UVGD D * v;!# MD D P 7 77CK.   $ $ 0 !:!:DLLI$%6|%D$EFH**E||' E5'+8DLL% 3J!H:VS^e3c'lBC eE5'#373%zJK**E11Kz%u,q043L3LL(DLL8A= $qyK7 6I#5*S]:''%/N KKugQY'x UG19/EF/ =>l$^457 r;cd|_|j}|js*t|dr|j}|j |d|_y)NTabort_everything) ensure_ready)rrH_abortedrr(r~)rer*rs r%r3zParallel._abort`sJ --}}2D!E 00L  $ $, $ ? r;cd|_|j|r|jdu|_|j|r |j|r|dk(rd|_yy)NFall)rLrKr)rer[rs r%_startzParallel._startqsd   " "8 ,"55TADO%%h/ %%h/ 5 $DO !r;c#^ Ktj}d} |j||d|jj 5|j Ed{ddd|jrgn |j}tj|_ t|_d|_|s|j% t/|d kDrF|j1}|j3|j4}|D]}|t/|d kDrEyy7#1swYxYw#t $rd|_|tjk7rtjdd}| G fddtj}|djY|jrgn |j}tj|_ t|_d|_|s|j%yy|j'|j(r|j+t,$rd|_|j'wxYw#|jrgn |j}tj|_ t|_d|_|s|j%wwxYww) z?Iterator returning the tasks' output as soon as they are ready.FNTaA generator produced by joblib.Parallel has been gc'ed in an unexpected thread. This behavior should not cause major -issues but to make sure, please report this warning and your use case at https://github.com/joblib/joblib/issues so it can be investigated.ceZdZfdZy)3Parallel._get_outputs.._GeneratorExitThreadc~jjrjjyr)r3r_warn_exit_earlyr4)re _parallels r%runz7Parallel._get_outputs.._GeneratorExitThread.runs0!((*$55%668!668r;N)rQrrr)rsr%_GeneratorExitThreadrs9r;rGeneratorExitThread)rr)r get_identrrHretrieval_context _retrieve GeneratorExitrryrzThreadstartrrr r!r"r'r4r3rrrrupopleftrr) rer[rdispatch_thread_iddetach_generator_exitr_remaining_outputsbatched_resultsrrs @r% _get_outputszParallel._get_outputssL&002 %C , KK, / 002 ,>>+++ ,n(,DJJ $**,DJ UDN!DM())+$%)088:O-88FO)   $%){, , ,* #DO"Y%8%8%:: ')-% 99+;+;9%*?@FFH$(,DJJ $**,DJ UDN!DM())+)% KKM$$%%'  "DO KKM   (,DJJ $**,DJ UDN!DM())+)soJ-0D+ DD D$D+,B.J-J-DD($D++A2I I AJ-;AI  I AJ**J-c|jry|j|jkry|jjst |j dkDryy)z9Return True if we need to continue retrieving some tasks.TrF)rLrrArHrrurrs r%_wait_retrievalzParallel._wait_retrievalsL ??  ! !D$;$; ;}}774::"r;c#nKd}|jr|jr|jyt|j}|j rK|dk(s0|jdj |jtk(r{tjd|dk(rU|tt|jd}||j |jtjd| d|_d}|j5|jj!}|j s|jj#|dddj%|j}|D]}|xj&dz c_||jryy#1swYXxYww)Nrrg{Gz?r )rr_raise_error_fastrurrrrrrsleepnextiterr"rrrremover _nb_consumed)retimeout_control_jobnb_jobsrrs r%rzParallel._retrieves"""$ ~~&&($**oG""qLJJqM,,T\\,BlRJJt$A'.*.tDNN/CT*J''2'224<<2H 4 $0 CG#?&*#  ;"&**"4"4"6**NN))/: ; .88FO) !!Q&!  A""$$r ; ;s&DF5AF)AF5'F5)F2.F5c|j5td|jDd}ddd|j|jyy#1swY(xYw)z3If we are aborting, raise if a job caused an error.c3HK|]}|jtk(s|ywr)rr).0rs r% z-Parallel._raise_error_fast..<sGcjjJ.FGs""N)rrrrr)re error_jobs r%rzParallel._raise_error_fast6sWZZ G GI     . !  s AAc|j|jz }|j}d}|r||dz }|s|dz }|s||j|jz dz }|r|dz }t j |yy)z?Warn the user if the generator is gc'ed before being consumned.rz5 tasks have been successfully executed but not used.z Additionally, zK tasks which were still being processed by the workers have been cancelled.z` You could benefit from adjusting the input task iterator to limit unnecessary computation time.N)rrrlrAryrz)re ready_outputs is_completedr$s r%rzParallel._warn_exit_earlyEs..1B1BB ))+    /!VW C (( **T-C-CCDE C  B C MM#  r;c#K d|_||_|jdk7r$t|tfdd}d|D}d|D]v\}}}|xjdz c_|xj dz c_||i|}|xj dz c_|j||xjdz c_x d|_ d|_d|_|jy#t$rd|_ d|_ d|_ wxYw#d|_ d|_d|_|jwxYww)zSeparate loop for sequential output. This simplifies the traceback in case of errors and reduces the overhead of calling sequential tasks with `joblib`. Tr cBttjSr)rrSrT)ritsr%z1Parallel._get_sequential_output..nsE)"2"22z"BCr;rtc3.K|] }|D]}|ywrrt)rrEtasks r%rz2Parallel._get_sequential_output..psQU5Q4DQDQsNF)rLrrOrrBrArrrrrrrr') reiterableiterable_batchedrrrresrrs @@r%_get_sequential_outputzParallel._get_sequential_output`sK " ""DO&.D #--/JQ(^#'CR$ R.>QJ'/ '"dF))Q.)''1,'D+F+&&!+&##% !!Q&! '"DM#DO&*D #    ! "DO!DN DM    "DM#DO&*D #    !s)ECC3 &E3 DD'D==Ec t|dt5|jr d}|jdur|dz }t |d|_dddd|_d|_d|_d|_d|_ d|_ d|_ y#1swY;xYw)z9Reset the counters and flags used to track the execution.rz+This Parallel instance is already running !Tz Before submitting new tasks, you must wait for the completion of all the previous tasks, or clean all references to the output generator.NrF) rGrr'r RuntimeErrorrBrArrrrr)rer$s r%_reset_run_trackingzParallel._reset_run_trackings T7KM 2 !}}C((D0>C #3'' DM !%&!"#!"   A ! !s 4BB c(jt|dr t|nd_t j_j sj}nj}|dk(r5j|}t|jr|St|Sj5tj_ddd|_t%j&t(r fd}|_|_j&j,j.}|dk(rt1d|zj3d|d|d tj&d rj&j5d _t9|}j:}|d k(rd_d_ni|_t|d r$tA|jCdtE|}tG|x_}tIjJ|j>}tM_'jQ||}tSjT|_+t|jr|St|S#1swYxYw)z)Main function to dispatch parallel tasks.rNr cxjjjjjyr)rH_workers_temp_folder_managerset_current_contextr*rsr%_batched_calls_reducer_callbackz:Parallel.__call__.._batched_calls_reducer_callbacks* &&;;OOHHr;rz%s has no active worker.zUsing backend z with z concurrent workers. start_callTrendswithr+),rrrurqrrrr(r1r;rrrrrr r)rrRrcrHrrrPrQrrjrr0rrrrsrreplacervrrSrTrrrweakrefrefr+)rerr+outputr backend_namer[rs` r%rzParallel.__call__s2   "(/)(Ds8}$ 99;$$--/F++-F Q;00:F L!226 DV DZZ (!GKKDM ( )/% dmm[ 1 &ED ")/%}}..77 Q;9LHI I n\N&@TUV 4==, / MM $ $ & >(( 5 &*D #()D %&.D #|Z0()=)=hF )TU 7:<7H HD % !''$2K2KLH "V""8\: V, V ..v@DL@_ ( (s <JJcN|jjd|jdS)Nz(n_jobs=))rPrQr+rs r%__repr__zParallel.__repr__s"&.."9"94;;GGr;)rQrrrr6rjrrr1r;r4rGrCrrKrOrjrlrr3rrrrrrrrrrrrs@r%r r s{~'x0' 2' 2!+M:*<8)+6&x0' 2Vp $ , &(<. +Tl# % =~"$*M^6DL /6("T%NgARHr;r )F)r)Qr __future__rrrrSosr$rerrryr contextlibrmathrrrrrnumbersr uuidr _multiprocessing_helpersr _parallel_backendsr rrrrrr_utilsrrdiskrloggerrrrLrMrNrSrx externalsrlocalrHr&rwr6rIrKr:r@r>r\rrrenvironrPstriprrobjectrrrrrrrrr!rr rtr;r%rs3   "##(()!-"# $%-v6>"8H "HVO$ 9??  &" Nt,d+q)40$/-d+t, 5/( #8 , #I . #I . #8 , #I . #I .O#dq>q>hh)h)` 2} ZZ^^12 6 < < > F$F +R^^6:!6!J    C0)& V-fV-t*3>]Hv]Hr;