o
    h2                     @   s  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
mZmZ d dlmZ ddlmZ dZe eZg dZG dd	 d	eZG d
d deZG dd deZdd ZG dd dZG dd deZ					dddZdddZdS )    N)as_completedThreadPoolExecutor)Optional   )_prctl_pr_set_pdeathsigTORCH_MP_PARALLEL_START)ProcessContextProcessExceptionProcessExitedExceptionProcessRaisedExceptionspawnSpawnContextstart_processesc                       s:   e Zd ZddgZdededef fddZdd Z  ZS )	r	   error_index	error_pidmsgpidc                    s"   t  | || _|| _|| _d S N)super__init__r   r   r   )selfr   r   r   	__class__ o/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/torch/multiprocessing/spawn.pyr   $   s   
zProcessException.__init__c                 C   s   t | | j| j| jffS r   )typer   r   r   r   r   r   r   
__reduce__*   s   zProcessException.__reduce__)	__name__
__module____qualname__	__slots__strintr   r   __classcell__r   r   r   r   r	   !   s    r	   c                       s.   e Zd ZdZdededef fddZ  ZS )r   zNException raised when a process failed due to an exception raised by the code.r   r   r   c                    s   t  ||| d S r   )r   r   )r   r   r   r   r   r   r   r   1   s   zProcessRaisedException.__init__)r   r   r    __doc__r"   r#   r   r$   r   r   r   r   r   .   s    r   c                       sL   e Zd ZdZdgZ	ddededededee f
 fdd	Zd
d Z	  Z
S )r
   zTException raised when a process failed due to signal or exited with a specific code.	exit_codeNr   r   r   signal_namec                    s    t  ||| || _|| _d S r   )r   r   r&   r'   )r   r   r   r   r&   r'   r   r   r   r   ?   s   
zProcessExitedException.__init__c                 C   s    t | | j| j| j| j| jffS r   )r   r   r   r   r&   r'   r   r   r   r   r   K   s   z!ProcessExitedException.__reduce__r   )r   r   r    r%   r!   r"   r#   r   r   r   r$   r   r   r   r   r
   :   s     r
   c                 C   s   t tj z| |g|R   W d S  ty   Y d S  tyI   dd l}t|d}t|	 | W d    n1 s<w   Y  t
d Y d S w )Nr   wbr   )r   signalSIGINTKeyboardInterrupt	Exception	tracebackopenpickledump
format_excsysexit)fniargs
error_filer-   fhr   r   r   _wrapR   s   
r9   c                   @   sH   e Zd Zdd Zdd ZdefddZ	ddee d	ee fd
dZdS )r   c                 C   s$   || _ || _dd t|D | _d S )Nc                 S   s   i | ]\}}|j |qS r   )sentinel).0indexprocessr   r   r   
<dictcomp>j   s    z+ProcessContext.__init__.<locals>.<dictcomp>)error_files	processes	enumerate	sentinelsr   r@   r?   r   r   r   r   g   s
   zProcessContext.__init__c                 C   s   dd | j D S )Nc                 S   s   g | ]}t |jqS r   )r#   r   )r;   r=   r   r   r   
<listcomp>o   s    z'ProcessContext.pids.<locals>.<listcomp>)r@   r   r   r   r   pidsn   s   zProcessContext.pidstimeoutc                 C   s8   t  | }| jD ]}td|t   }|| q	dS )z4Attempt to join all processes with a shared timeout.r   N)time	monotonicr@   maxjoin)r   rF   endr=   time_to_waitr   r   r   _join_procs_with_timeoutq   s
   
z'ProcessContext._join_procs_with_timeoutNgrace_periodc                 C   s  t | jdkr	dS tjj| j |d}d}|D ]}| j|}| j| }|  |j	dkr2|} nq|du r>t | jdkS |durG| 
| | jD ]}| r[td|j |  qJ| 
|du rddn| | jD ]}| r{td|j |  |  qj| j| }t| j| tjs| j| j	}	|	dk rz	t|	 j}
W n ty   d|	  d	}
Y nw td
|dd|
 ||j|	|
dtd
|dd|	d||j|	dt| j| d}t|}W d   n1 sw   Y  d|dd}||7 }t|||j)aL  Join one or more processes within spawn context.

        Attempt to join one or more processes in this spawn context.
        If one of them exited with a non-zero exit status, this function
        kills the remaining processes (optionally with a grace period)
        and raises an exception with the cause of the first process exiting.

        Returns ``True`` if all processes have been joined successfully,
        ``False`` if there are more processes that need to be joined.

        Args:
            timeout (float): Wait this long (in seconds) before giving up on waiting.
            grace_period (float): When any processes fail, wait this long (in seconds)
                for others to shutdown gracefully before terminating them. If they
                still don't exit, wait another grace period before killing them.
        r   T)rF   Nz)Terminating process %s via signal SIGTERM   zJUnable to shutdown process %s via SIGTERM , forcefully exiting via SIGKILLz<Unknown signal >zprocess dz terminated with signal )r   r   r&   r'   z terminated with exit code )r   r   r&   rbz

-- Process z& terminated with the following error:
)lenrB   multiprocessing
connectionwaitkeyspopr@   rJ   exitcoderM   is_alivelogwarningr   	terminatekillosaccessr?   R_OKr)   Signalsname
ValueErrorr
   r.   r/   loadr   )r   rF   rN   readyr   r:   r<   r=   failed_processrY   rc   r8   original_tracer   r   r   r   rJ   x   sz   






zProcessContext.join)NN)	r   r   r    r   rE   floatrM   r   rJ   r   r   r   r   r   f   s    r   c                       s   e Zd Z fddZ  ZS )r   c                    s   t d t || d S )Nz<SpawnContext is renamed to ProcessContext since 1.4 release.)warningswarnr   r   rC   r   r   r   r      s   
zSpawnContext.__init__)r   r   r    r   r$   r   r   r   r   r      s    r   r   TFr   c                    s*  |dkrt jtddkrtd d}nd}t|d g| }d g| } fdd|sHt|D ]}	|	\}
}}|||
< |||
< q5n7t	|d	*fd
dt|D }t
|D ]}| \}
}}|||
< |||
< q^W d    n1 szw   Y  t||}|s|S | s	 | rd S d S )N
forkserver01zStarting processes in parallel.TFc                    sR   t jdddd}|  t|j jt|  |jfd}|  | ||jfS )Nzpytorch-errorfile-z.pickleF)prefixsuffixdelete)targetr6   daemon)	tempfileNamedTemporaryFilecloser_   unlinkrc   Processr9   start)r5   tfr=   )r6   rs   r4   mpr   r   start_process  s   z&start_processes.<locals>.start_process)max_workersc                    s   g | ]}  |qS r   )submit)r;   r5   )executorr|   r   r   rD     s    z#start_processes.<locals>.<listcomp>)r_   environgetENV_VAR_PARALLEL_STARTr[   inforT   get_contextranger   r   resultr   rJ   )r4   r6   nprocsrJ   rs   start_methodstart_parallelr?   r@   r5   idxr=   tf_namefuturesfutcontextr   )r6   rs   r   r4   r{   r|   r   r      s:   






r   c                 C   s8   |dkrd| d}t j|tdd t| ||||ddS )a  Spawns ``nprocs`` processes that run ``fn`` with ``args``.

    If one of the processes exits with a non-zero exit status, the
    remaining processes are killed and an exception is raised with the
    cause of termination. In the case an exception was caught in the
    child process, it is forwarded and its traceback is included in
    the exception raised in the parent process.

    Args:
        fn (function): Function is called as the entrypoint of the
            spawned process. This function must be defined at the top
            level of a module so it can be pickled and spawned. This
            is a requirement imposed by multiprocessing.

            The function is called as ``fn(i, *args)``, where ``i`` is
            the process index and ``args`` is the passed through tuple
            of arguments.

        args (tuple): Arguments passed to ``fn``.
        nprocs (int): Number of processes to spawn.
        join (bool): Perform a blocking join on all processes.
        daemon (bool): The spawned processes' daemon flag. If set to True,
                       daemonic processes will be created.
        start_method (str): (deprecated) this method will always use ``spawn``
                               as the start method. To use a different start method
                               use ``start_processes()``.

    Returns:
        None if ``join`` is ``True``,
        :class:`~ProcessContext` if ``join`` is ``False``

    r   z3This method only supports start_method=spawn (got: zU).
To use a different start_method use:
		 torch.multiprocessing.start_processes(...)   )
stacklevel)r   )rj   rk   FutureWarningr   )r4   r6   r   rJ   rs   r   r   r   r   r   r   ,  s
   !
)r   r   TFr   )loggingrT   multiprocessing.connectionr_   r/   r)   r2   rt   rG   rj   concurrent.futuresr   r   typingr    r   r   	getLoggerr   r[   __all__r,   r	   r   r
   r9   r   r   r   r   r   r   r   r   <module>   s:   
t
D