U
    0-eu(                     @   sh   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m	Z	m
Z
mZ dd ZdddZdddZdS )    N   )AcceleratorStatePartialState)PrecisionTypePrepareForLaunchis_mps_availablepatch_environmentc                  C   s
   t  } dS )z+Verify a `PartialState` can be initialized.N)r   )_ r
   U/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/accelerate/launchers.pytest_launch   s    r   r
   no29500	127.0.0.1c                 C   s&  d}d}	t dd tj D r&d}	n dtjkrFdttjd  k}zt|	 }W n4 t
k
r   t
d|j	  dt  d	Y nX |s|	rtjd
ddk	rddlm  m}
 ttjdkrt
d|dkrd}t| dd}td| d |
j|||dd n|r@tj r,td ntd | |  n|dkrRt
d||krdt
d|dkrddlm} ddlm} ttjdkrt
dt|||| |||d  tjdd	 d krRttd!d}z||d"|dd W n^ |k
rP } z>d#}d$|j d kr,t!| d%|nt!| d&| |W 5 d}~X Y nX t| d!d}td'| d( z||||dd W nP |k
r } z0d$|j d krt!d)|nt!d*| |W 5 d}~X Y nX W 5 Q R X nBt" rd+tjd,< td- ntj rtd ntd. | |  dS )/a  
    Launches a training function, using several processes or multiple nodes if it's possible in the current environment
    (TPU with multiple cores for instance).

    <Tip warning={true}>

    To use this function absolutely zero calls to a CUDA device must be made in the notebook session before calling. If
    any have been made, you will need to restart the notebook and make sure no cells use any CUDA capability.

    Setting `ACCELERATE_DEBUG_MODE="1"` in your environment will run a test before truly launching to ensure that none
    of those calls have been made.

    </Tip>

    Args:
        function (`Callable`):
            The training function to execute. If it accepts arguments, the first argument should be the index of the
            process run.
        args (`Tuple`):
            Tuple of arguments to pass to the function (it will receive `*args`).
        num_processes (`int`, *optional*):
            The number of processes to use for training. Will default to 8 in Colab/Kaggle if a TPU is available, to
            the number of GPUs available otherwise.
        mixed_precision (`str`, *optional*, defaults to `"no"`):
            If `fp16` or `bf16`, will use mixed precision training on multi-GPU.
        use_port (`str`, *optional*, defaults to `"29500"`):
            The port to use to communicate between processes when launching a multi-GPU training.
        master_addr (`str`, *optional*, defaults to `"127.0.0.1"`):
            The address to use for communication between processes.
        node_rank (`int`, *optional*, defaults to 0):
            The rank of the current node.
        num_nodes (`int`, *optional*, defaults to 1):
            The number of nodes to use for training.

    Example:

    ```python
    # Assume this is defined in a Jupyter Notebook on an instance with two GPUs
    from accelerate import notebook_launcher


    def train(*args):
        # Your training function here
        ...


    notebook_launcher(train, args=(arg1, arg2), num_processes=2, mixed_precision="fp16")
    ```
    Fc                 s   s   | ]}| d V  qdS )ZKAGGLEN)
startswith).0keyr
   r
   r   	<genexpr>\   s     z$notebook_launcher.<locals>.<genexpr>TZIPythonzgoogle.colabzUnknown mixed_precision mode: z. Choose between .ZTPU_NAMENr   zTo train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside your training function. Restart your notebook and make sure no cells initializes an `Accelerator`.   ZTPU)Zdistributed_typezLaunching a training on z TPU cores.forkargsZnprocsZstart_methodzLaunching training on one GPU.zLaunching training on one CPU.zcYou have to specify the number of GPUs you would like to use, add `num_processes=...` to your call.z4The node_rank must be less than the number of nodes.r   start_processes)ProcessRaisedExceptionzTo launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized inside your training function. Restart your notebook and make sure no cells initializes an `Accelerator`.)Znproc	node_rank
world_sizemaster_addrmaster_portmixed_precisionZACCELERATE_DEBUG_MODEfalsetrueZ	MULTI_GPUr
   zQAn issue was found when verifying a stable environment for the notebook launcher.z.Cannot re-initialize CUDA in forked subprocesszThis likely stems from an outside import causing issues once the `notebook_launcher()` is called. Please review your imports and test them when running the `notebook_launcher()` to identify which one is problematic and causing CUDA to be initialized.z! The following error was raised: zLaunching training on z GPUs.aU  CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. This likely stems from an outside import causing issues once the `notebook_launcher()` is called. Please review your imports and test them when running the `notebook_launcher()` to identify which one is problematic and causing CUDA to be initialized.z0An issue was found when launching the training: 1ZPYTORCH_ENABLE_MPS_FALLBACKzLaunching training on MPS.zLaunching training on CPU.)#anyosenvironkeyssysmodulesstrget_ipythonr   lower
ValueErrorr    listgetZ)torch_xla.distributed.xla_multiprocessingdistributedZxla_multiprocessinglenr   Z_shared_stater   printspawntorchcudaZis_availabletorch.multiprocessingr   Ztorch.multiprocessing.spawnr   r   r   r   RuntimeErrorr   )functionr   num_processesr    Zuse_portr   r   Z	num_nodesZin_colabZ	in_kaggleZxmplauncherr   r   eerrr
   r
   r   notebook_launcher   s    <






	&.


r=      c              
   C   sb   ddl m} t D}t|ddd|jdd" t| dd	}||||d
d W 5 Q R X W 5 Q R X dS )aC  
    Launches a training function using several processes on CPU for debugging purposes.

    <Tip warning={true}>

    This function is provided for internal testing and debugging, but it's not intended for real trainings. It will
    only use the CPU.

    </Tip>

    Args:
        function (`Callable`):
            The training function to execute.
        args (`Tuple`):
            Tuple of arguments to pass to the function (it will receive `*args`).
        num_processes (`int`, *optional*, defaults to 2):
            The number of processes to use for training.
    r   r   z127.0.01r   r   yes)r   r   r   Zaccelerate_mixed_precisionZaccelerate_debug_rdv_fileZaccelerate_use_cpuT)debugr   r   N)r6   r   tempfileNamedTemporaryFiler   namer   )r8   r   r9   r   Ztmp_filer:   r
   r
   r   debug_launcher   s    
rD   )r
   Nr   r   r   r   r   )r
   r>   )r%   r(   rA   r4   stater   r   utilsr   r   r   r   r   r=   rD   r
   r
   r
   r   <module>   s           
 *