
    g5                         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mZmZmZmZ ddlmZ d Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZdS )    N   )AcceleratorStatePartialState)PrecisionTypePrepareForLaunchare_libraries_initializedcheck_cuda_p2p_ib_supportget_gpu_infois_mps_availableis_torch_versionpatch_environment)0ELASTIC_LOG_LINE_PREFIX_TEMPLATE_PYTORCH_VERSIONc                  "    t                      } dS )z+Verify a `PartialState` can be initialized.N)r   )_s    P/var/www/html/ai-engine/env/lib/python3.11/site-packages/accelerate/launchers.pytest_launchr   #   s    AAA     no29500	127.0.0.1static none皙?c                 	   d}d}t          d t          j                                        D                       rd}nAdt          j        v r3dt          t          j        d                                                   v }	 t          |	                                          }nL# t          $ r? t          d|j        	                                 dt          j                     d          w xY w|s|rt          j                            d	d
          xdd
lmc m} t#          t$          j                  dk    rt          d          |d}t)          | d          }t+          d| d           |                    |||d           d
S |r\t/                      d         dk     rDt0          j                                        rt+          d           nt+          d            | |  d
S |t          d          ||k    rt          d          |dk    rBddlm}m} ddlm} ddl m!} t#          t$          j                  dk    rt          d          tE          d          }t#          |          dk    rd}|D ]}|d | d!z  }tG          |          tI          ||||z  |||"          }tK                      s
d#|d$<   d#|d%<   tM          d*i |5  t          j                            d&d'          	                                d(k    rmt)          tN          d)          }	  ||d*|d           nF# |$ r>}d+}d,|j(        d         v rtG          | d-          |tG          | d.|           |d
}~ww xY wt)          | d)          }t+          d/| d0           	 |
i }
|d1k    r||
d2<   |	s| d3| }	tI          |||||	||
||d4
  
        }tS          d5tT                    r||d6<     | |d*i || 7          |  n?# |$ r7}d,|j(        d         v rtG          d8          |tG          d9|           |d
}~ww xY w	 d
d
d
           d
S # 1 swxY w Y   d
S tW                      rd#t          j        d:<   t+          d;           n=t0          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.
        rdzv_backend (`str`, *optional*, defaults to `"static"`):
            The rendezvous method to use, such as 'static' (the default) or 'c10d'
        rdzv_endpoint (`str`, *optional*, defaults to `""`):
            The endpoint of the rdzv sync. storage.
        rdzv_conf (`Dict`, *optional*, defaults to `None`):
            Additional rendezvous configuration.
        rdzv_id (`str`, *optional*, defaults to `"none"`):
            The unique run id of the job.
        max_restarts (`int`, *optional*, defaults to 0):
            The maximum amount of restarts that elastic agent will conduct on workers before failure.
        monitor_interval (`float`, *optional*, defaults to 0.1):
            The interval in seconds that is used by the elastic_agent as a period of monitoring workers.
        log_line_prefix_template (`str`, *optional*, defaults to `None`):
            The prefix template for elastic launch logging. Available from PyTorch 2.2.0.

    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              3   @   K   | ]}|                     d           V  dS )KAGGLEN)
startswith).0keys     r   	<genexpr>z$notebook_launcher.<locals>.<genexpr>{   s.      
A
A3>>(##
A
A
A
A
A
Ar   TIPythonzgoogle.colabzUnknown mixed_precision mode: z. Choose between .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`.   XLA)distributed_typezLaunching a training on z TPU cores.forkargsnprocsstart_methodr      z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.)LaunchConfigelastic_launch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`.bitsandbyteszCould not start distributed process. Libraries known to initialize CUDA upon import have been imported already. Please keep these imports inside your training function to try and help with this:z
	* ``)nproc	node_rank
world_sizemaster_addrmaster_portmixed_precision1nccl_p2p_disablenccl_ib_disableACCELERATE_DEBUG_MODEfalsetrue	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.r   rank:)
	min_nodes	max_nodesnproc_per_noderun_idrdzv_endpointrdzv_backendrdzv_configsmax_restartsmonitor_intervalr-   z>=log_line_prefix_template)config
entrypointaU  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: 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get)torch_xla.distributed.xla_multiprocessingdistributedxla_multiprocessinglenr   _shared_stater   printspawnr
   torchcudais_availabletorch.distributed.launcher.apir/   r0   torch.multiprocessingr2   torch.multiprocessing.spawnr3   r   RuntimeErrordictr	   r   r   r+   r   r   r   )functionr+   num_processesr;   use_portr9   r7   	num_nodesrJ   rI   	rdzv_confrdzv_idrL   rM   rN   in_colab	in_kagglexmplauncherr/   r0   r2   r3   problematic_importserrlib_namepatched_envelaunch_config_kwargss                                r   notebook_launcherr}   (   s   b HI

A
Arz/@/@
A
A
AAA O			ck	!	!!SY)?)K)K)M)M%N%NN
'(=(=(?(?@@ 
 
 
sT-A-G-G-I-Iss\i\n\p\psss
 
 	


 	 CI CBJNN:t$D$D$P?????????-..22!  
  M#HuEEECCCCDDD		(m&	QQQQQ	 slnnQ'!++:""$$ 	4233332333$ u   	!!STTT1SSSSSSSS======JJJJJJ#122Q66 %   #<N"K"K&''!++{  !4 1 1H0X0000CC"3'''##$}4'$ /  K -.. 525./14-. #11[11 3j 3j:>>"97CCIIKKvUU/kZZZHd'r-^deeeee1 
d 
d 
dqKqvVWyXX".#& !_ !_ !_# #
 $%% #/#/[/[XY/[/["\"\bcc
d ,H{SSSD}DDDEEEj ($&	#x//,5	&), H/:,G,GX,G,GM+/"+"+'4&&3%1%.%1)9%+, , ,( (.^__ dKc,-GHdNN,,*N*N9M*N*N[cdddfjkkk- 	j 	j 	jG16RS9TT*[ 
  !! ++a^_+a+abbhii	j lS3j 3j 3j 3j 3j 3j 3j 3j 3j 3j 3j 3j 3j 3j 3j 3j 3j 3jn  !! 4<?
8923333((** 4677772333HdOOOOsi   ?!B! !A	C*AQ	L/.Q	/M249M--M22'Q	A!O<;Q	<P82P33P88Q		QQr.   c           	         ddl m} t          j                    5 }t	          |ddd|j        d          5  t          | d	          } ||||d
           ddd           n# 1 swxY w Y   ddd           dS # 1 swxY w Y   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   r1   r   r   r   yes)r8   r9   r:   accelerate_mixed_precisionaccelerate_debug_rdv_fileaccelerate_use_cpuT)debugr)   r*   N)ri   r2   tempfileNamedTemporaryFiler   namer   )rm   r+   rn   r2   tmp_filerv   s         r   debug_launcherr     sX   & 655555		$	&	& \( $#'+&.m$
 
 
 		\ 		\ (===HOH4TZ[[[[		\ 		\ 		\ 		\ 		\ 		\ 		\ 		\ 		\ 		\ 		\ 		\ 		\ 		\ 		\\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \s4   A:!A"A:"A&	&A:)A&	*A::A>A>)r   Nr   r   r   r   r   r   r   Nr   r   r   N)r   r.   )rS   rV   r   re   stater   r   utilsr   r   r   r	   r
   r   r   r   utils.constantsr   r   r}   r   r   r   r   <module>r      s4   
			 



   1 1 1 1 1 1 1 1	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 N M M M M M   
!b b b bJ!\ !\ !\ !\ !\ !\r   