
    gu                     4   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 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 dlmZ d dlmZ d dlmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z, d d	l-m.Z.m/Z/  e!            r*d d
l0m1Z1 d dl2m3Z3 dZ4 ej5        e4d e3            g            ej6        e7          Z8dddddddZ9d Z: G d de j;                  Z<d%dZ=d Z>d Z?d Z@d ZAd ZBdefd ZCd! ZDd" ZEd# ZFe7d$k    r eF             dS dS )&    N)Path)default_config_fileload_config_from_file)SageMakerConfig)DYNAMO_BACKENDS)CustomArgumentParser)get_int_from_env)ComputeEnvironmentDistributedTypePrepareForLaunch_filter_argscheck_cuda_p2p_ib_supportconvert_dict_to_env_variablesis_bf16_availableis_deepspeed_availableis_mlu_availableis_musa_availableis_npu_availableis_rich_availableis_sagemaker_availableis_torch_versionis_torch_xla_availableis_xpu_availablepatch_environmentprepare_deepspeed_cmd_envprepare_multi_gpu_envprepare_sagemager_args_inputsprepare_simple_launcher_cmd_envprepare_tpustr_to_bool)DEEPSPEED_MULTINODE_LAUNCHERSTORCH_DYNAMO_MODES)get_console)RichHandlerz%(message)sz[%X])formatdatefmthandlersDistributed GPUsTPUDeepSpeed ArgumentsFSDP ArgumentsMegatron-LM ArgumentsFP8 Arguments)	multi_gputpuuse_deepspeeduse_fsdpuse_megatron_lmfp8_backendc                 x    d| v rd} |                      d          r| dd                             dd          S dS )zIFinds all cases of - after the first two characters and changes them to _r3   --fp8_backendz--   N-_)
startswithreplace)options    V/var/www/html/ai-engine/env/lib/python3.11/site-packages/accelerate/commands/launch.pyclean_optionr=   R   sP      ,abbz!!#s+++, ,    c                   F     e Zd ZdZ fdZdej        f fdZ fdZ xZ	S )CustomHelpFormattera  
    This is a custom help formatter that will hide all arguments that are not used in the command line when the help is
    called. This is useful for the case where the user is using a specific platform and only wants to see the arguments
    for that platform.
    c                 L     t                      j        |i | g d| _        d S )N)Hardware Selection ArgumentsResource Selection ArgumentsTraining Paradigm Argumentszpositional argumentszoptional arguments)super__init__titles)selfargskwargs	__class__s      r<   rF   zCustomHelpFormatter.__init__a   s6    $)&)))
 
 
r>   actionc                    dt           j        d         v r+dt           j        dd          v rt           j        dd          }nt           j        dd          }t          |          dk    r-t          t	          t
          |                    }d |D             }d |D             }|j        j        | j        |z   vrt          j
        |_        n|j        j        dk    rVt          |j                                      t          |                    rt          j
        |_        nu|j        d	z   |_        ne|j        j        d
k    rUt          |j                                      t          |                    rt          j
        |_        n|j        d	z   |_        d |j        D             |_        t                                          |           d S )N
accelerater   launch   r6   c                 H    g | ]}|t                                           v | S  )options_to_groupkeys).0args     r<   
<listcomp>z4CustomHelpFormatter.add_argument.<locals>.<listcomp>s   s/    TTTcS<L<Q<Q<S<S5S5Sc5S5S5Sr>   c                 (    g | ]}t           |         S rR   )rS   )rU   os     r<   rW   z4CustomHelpFormatter.add_argument.<locals>.<listcomp>t   s    GGG1+A.GGGr>   rB   z (currently selected)rD   c                 *    g | ]}d |dd         v|S )r7   r6   NrR   )rU   ss     r<   rW   z4CustomHelpFormatter.add_argument.<locals>.<listcomp>   s/     V V VqSPQRSRTRTPUEUEUEUEUEUr>   )sysargvlenlistmapr=   	containertitlerG   argparseSUPPRESShelpsetoption_strings
isdisjointrE   add_argument)rH   rL   rI   used_platformsused_titlesrK   s        r<   ri   z CustomHelpFormatter.add_argumentk   s   38A;&&8sx|+C+C8ABB<DD8ABB<Dt99q==L$//00DTTTTTTNGGGGGK%T[;-FFF&/!'+IIIv,--88TCC H"*"3FKK"(+0G"GFKK!'+HHHv,--88TCC H"*"3FKK"(+0G"GFK V VF,A V V VV$$$$$r>   c                     t          | j        j                  dk     rg | j        _        d| j        _        t	                                                       d S )Nr6    )r^   _current_sectionitemsheadingrE   end_section)rH   rK   s    r<   rq   zCustomHelpFormatter.end_section   sN    t$*++a//*,D!',.D!)r>   )
__name__
__module____qualname____doc__rF   rc   Actionri   rq   __classcell__)rK   s   @r<   r@   r@   Z   s         
 
 
 
 
%8? % % % % % %4        r>   r@   c                 D   d}|  |                      d|ddt                    }nt          d|ddt                    }|                    dddd	
           |                    dd d           |                    dddd
           |                    dd          }|                    dddd           |                    dddd           |                    dddd           |                    dddd           |                    dd          }|                    dt
          g d d!"           |                    d#t          d d$%           |                    d&t          d d'%           |                    d(t          d d)%           |                    d*ddd+           |                    d,t
          d-gd. t          D             z   d/"           |                    d0t
          d1t          d23           |                    d4ddd5           |                    d6ddd7           |                    d8d9          }|                    d:ddd;           |                    d<ddd=           |                    d>ddd?           |                    d@dddA           |                    dBdC          }|                    dDd dE           |                    dFdddG           |                    dHt          d dI%           |                    dJt
          d dK%           |                    dLt          d dM%           |                    dNdOdPt
          dQR           |                    dSt
          d dT%           |                    dUt
          d1dV%           |                    dWt
          dXdY%           |                    dZt
          d[d\%           |                    d]t          d^d_%           |                    d`t          dadb%           |                    dcdddde
           |                    dfddg
           |                    dhdi          }|                    djddkdlm           |                    dndodkdpm           |                    dqddr
           |                    dst
          dtduv           |                    dwt
          dtdxv           |                    dyt
          d dz%           |                    d{dd|
           |                    d}d~          }|                    dd t
          dR           |                    dd t          dR           |                    dd t
          dR           |                    dd t
          dR           |                    dd t
          dR           |                    dd t
          dR           |                    dd t          dR           |                    dd t          dR           |                    dd t
          dR           |                    dd t
          dR           |                    dd t
          dR           |                    dd t
          dR           |                    dd t
          dR           |                    dd t
          dR           |                    dd t
          dR           |                    dd          }	|	                    ddt
          dR           |	                    dt          dd%           |	                    dt
          dd%           |	                    dt
          d d%           |	                    dd t
          dR           |	                    dd t
          dR           |	                    dd t
          dR           |	                    ddt
          dR           |	                    ddt
          dR           |	                    ddt
          dR           |	                    ddt
          dR           |	                    ddt
          dR           |                    dd          }
|
                    dt          dd%           |
                    dt          dd%           |
                    dt          d dì%           |
                    dd t
          dŬR           |
                    dd t
          dǬR           |
                    dd t
          dɬR           |
                    ddt          d̬R           |                    ddΦ          }|                    dt
          ddgdҬ"           |                    ddddԬ           |                    dt          d^d֬%           |                    dt          ddج%           |                    dt
          dddgdܬ3           |                    dt          dd߬%           |                    dt
          dddgd3           |                    dd dd%           |                    dt
          dddgd3           |                    dd          }|                    dt
          d d%           |                    dt
          d d%           |                    ddd
           |                    dt
          d           |                    dd          }|                    dt
          d d%           |                    dt          dd%           |                    dt          j        d           | |                    t                      |S (  NzLaunch a python script in a distributed scenario. Arguments can be passed in with either hyphens (`--num-processes=2`) or underscores (`--num_processes=2`)rO   F)descriptionadd_helpallow_abbrevformatter_classzAccelerate launch commandz-hz--helpre   z Show this help message and exit.)rL   re   z--config_filezFThe config file to use for the default values in the launching script.)defaultre   z--quietz-q
store_truezSilence subprocess errors from the launch stack trace and only show the relevant tracebacks. (Only applicable to DeepSpeed and single-process configurations)rB   z0Arguments for selecting the hardware to be used.z--cpuz0Whether or not to force the training on the CPU.)r}   rL   re   z--multi_gpuz=Whether or not this should launch a distributed GPU training.--tpuz1Whether or not this should launch a TPU training.z--ipexzLWhether or not this should launch a Intel PyTorch Extension (IPEX) training.rC   z@Arguments for fine-tuning how available hardware should be used.--mixed_precision)nofp16bf16fp8zWhether or not to use mixed precision training. Choose between FP16 and BF16 (bfloat16) training. BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.)typechoicesre   --num_processesz9The total number of processes to be launched in parallel.)r   r}   re   --num_machinesz3The total number of machines used in this training.z--num_cpu_threads_per_processzLThe number of CPU threads per process. Can be tuned for optimal performance.z--enable_cpu_affinityziWhether or not CPU affinity and balancing should be enabled. Currently only supported on NVIDIA hardware.--dynamo_backendr   c                 6    g | ]}|                                 S rR   )lower)rU   bs     r<   rW   z)launch_command_parser.<locals>.<listcomp>   s     ===!''))===r>   zkChoose a backend to optimize your training with dynamo, see more at https://github.com/pytorch/torchdynamo.z--dynamo_moder}   z4Choose a mode to optimize your training with dynamo.)r   r}   r   re   z--dynamo_use_fullgraphz[Whether to use full graph mode for dynamo or it is ok to break model into several subgraphsz--dynamo_use_dynamicz(Whether to enable dynamic shape tracing.rD   z;Arguments for selecting which training paradigm to be used.z--use_deepspeedzWhether to use deepspeed.z
--use_fsdpzWhether to use fsdp.z--use_megatron_lmzWhether to use Megatron-LM.z	--use_xpuzDWhether to use IPEX plugin to speed up training on XPU specifically.r(   z.Arguments related to distributed GPU training.z	--gpu_idszWWhat GPUs (by id) should be used for training on this machine as a comma-seperated listz--same_networkzQWhether all machines used for multinode training exist on the same local network.z--machine_rankz9The rank of the machine on which this script is launched.z--main_process_ipz(The IP address of the machine of rank 0.z--main_process_portz:The port to use to communicate with the machine of rank 0.z-tz--tee0z4Tee std streams into a log file and also to console.)r}   r   re   z	--log_dirzBase directory to use for log files when using torchrun/torch.distributed.run as launcher. Use with --tee to redirect std streams info log files.z--rolez"User-defined role for the workers.z--rdzv_backendstaticzFThe rendezvous method to use, such as 'static' (the default) or 'c10d'z--rdzv_confrm   zJAdditional rendezvous configuration (<key1>=<value1>,<key2>=<value2>,...).z--max_restartsr   z7Maximum number of worker group restarts before failing.z--monitor_intervalg?z6Interval, in seconds, to monitor the state of workers.z-mz--modulezwChange each process to interpret the launch script as a Python module, executing with the same behavior as 'python -m'.z--no_pythonz|Skip prepending the training script with 'python' - just execute it directly. Useful when the script is not a Python script.r)   zArguments related to TPU.z--tpu_clustertpu_use_clusterz*Whether to use a GCP TPU pod for training.)rL   destre   --no_tpu_clusterstore_falsez?Should not be passed explicitly, this is for internal use only.z--tpu_use_sudozGWhether to use `sudo` when running the TPU training script in each pod.z--vmappendzkList of single Compute VM instance names. If not provided we assume usage of instance groups. For TPU pods.)r   rL   re   z--envzOList of environment variables to set on the Compute VM instances. For TPU pods.--main_training_functionzTThe name of the main function to be executed in your script (only for TPU training).z--downcast_bf16zWhether when using bf16 precision on TPUs if both float and double tensors are cast to bfloat16 or if double tensors remain as float32.r*   zArguments related to DeepSpeed.z--deepspeed_config_filezDeepSpeed config file.z--zero_stagez{DeepSpeed's ZeRO optimization stage (useful only when `use_deepspeed` flag is passed). If unspecified, will default to `2`.z--offload_optimizer_devicezDecides where (none|cpu|nvme) to offload optimizer states (useful only when `use_deepspeed` flag is passed). If unspecified, will default to 'none'.z--offload_param_devicezDecides where (none|cpu|nvme) to offload parameters (useful only when `use_deepspeed` flag is passed). If unspecified, will default to 'none'.z--offload_optimizer_nvme_pathzDecides Nvme Path to offload optimizer states (useful only when `use_deepspeed` flag is passed). If unspecified, will default to 'none'.z--offload_param_nvme_pathzDecides Nvme Path to offload parameters (useful only when `use_deepspeed` flag is passed). If unspecified, will default to 'none'.z--gradient_accumulation_stepszNo of gradient_accumulation_steps used in your training script (useful only when `use_deepspeed` flag is passed). If unspecified, will default to `1`.z--gradient_clippingzgradient clipping value used in your training script (useful only when `use_deepspeed` flag is passed). If unspecified, will default to `1.0`.z--zero3_init_flagzDecides Whether (true|false) to enable `deepspeed.zero.Init` for constructing massive models. Only applicable with DeepSpeed ZeRO Stage-3. If unspecified, will default to `true`.z--zero3_save_16bit_modelzDecides Whether (true|false) to save 16-bit model weights when using ZeRO Stage-3. Only applicable with DeepSpeed ZeRO Stage-3. If unspecified, will default to `false`.z--deepspeed_hostfilez@DeepSpeed hostfile for configuring multi-node compute resources.z--deepspeed_exclusion_filterz>DeepSpeed exclusion filter string when using mutli-node setup.z--deepspeed_inclusion_filterz>DeepSpeed inclusion filter string when using mutli-node setup.z--deepspeed_multinode_launcherzMDeepSpeed multi-node launcher to use. If unspecified, will default to `pdsh`.z--deepspeed_moe_layer_cls_nameszcomma-separated list of transformer MoE layer class names (case-sensitive) to wrap ,e.g, `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` ... (useful only when `use_deepspeed` flag is passed).r+   z3Arguments related to Fully Shared Data Parallelism.z--fsdp_offload_paramsfalsezvDecides Whether (true|false) to offload parameters and gradients to CPU. (useful only when `use_fsdp` flag is passed).z--fsdp_min_num_paramsg    חAzlFSDP's minimum number of parameters for Default Auto Wrapping. (useful only when `use_fsdp` flag is passed).z--fsdp_sharding_strategy
FULL_SHARDzGFSDP's Sharding Strategy. (useful only when `use_fsdp` flag is passed).z--fsdp_auto_wrap_policyzFFSDP's auto wrap policy. (useful only when `use_fsdp` flag is passed).z$--fsdp_transformer_layer_cls_to_wrapzTransformer layer class name (case-sensitive) to wrap ,e.g, `BertLayer`, `GPTJBlock`, `T5Block` .... (useful only when `use_fsdp` flag is passed).z--fsdp_backward_prefetchzNFSDP's backward prefetch policy. (useful only when `use_fsdp` flag is passed).z--fsdp_state_dict_typezEFSDP's state dict type. (useful only when `use_fsdp` flag is passed).z--fsdp_forward_prefetchzIf True, then FSDP explicitly prefetches the next upcoming all-gather while executing in the forward pass (useful only when `use_fsdp` flag is passed).z--fsdp_use_orig_paramstruezIf True, allows non-uniform `requires_grad` during init, which means support for interspersed frozen and trainable paramteres. (useful only when `use_fsdp` flag is passed).z --fsdp_cpu_ram_efficient_loadingu  If True, only the first process loads the pretrained model checkoint while all other processes have empty weights. Only applicable for 🤗 Transformers. When using this, `--fsdp_sync_module_states` needs to True. (useful only when `use_fsdp` flag is passed).z--fsdp_sync_module_stateszIf True, each individually wrapped FSDP unit will broadcast module parameters from rank 0. (useful only when `use_fsdp` flag is passed).z--fsdp_activation_checkpointingzDecides Whether (true|false) intermediate activations are freed during the forward pass, and a checkpoint is left as a placeholder. (useful only when `use_fsdp` flag is passed).r,   z!Arguments related to Megatron-LM.z--megatron_lm_tp_degreerP   zbMegatron-LM's Tensor Parallelism (TP) degree. (useful only when `use_megatron_lm` flag is passed).z--megatron_lm_pp_degreezdMegatron-LM's Pipeline Parallelism (PP) degree. (useful only when `use_megatron_lm` flag is passed).z--megatron_lm_num_micro_batchesznMegatron-LM's number of micro batches when PP degree > 1. (useful only when `use_megatron_lm` flag is passed).z"--megatron_lm_sequence_parallelismzDecides Whether (true|false) to enable Sequence Parallelism when TP degree > 1. (useful only when `use_megatron_lm` flag is passed).z#--megatron_lm_recompute_activationszDecides Whether (true|false) to enable Selective Activation Recomputation. (useful only when `use_megatron_lm` flag is passed).z'--megatron_lm_use_distributed_optimizerzDecides Whether (true|false) to use distributed optimizer which shards optimizer state and gradients across Data Pralellel (DP) ranks. (useful only when `use_megatron_lm` flag is passed).z--megatron_lm_gradient_clippingg      ?zMegatron-LM's gradient clipping value based on global L2 Norm (0 to disable). (useful only when `use_megatron_lm` flag is passed).r-   zDArguments related to FP8 training (requires `--mixed_precision=fp8`)r5   temsampzIChoose a backend to train with FP8 (te: TransformerEngine, msamp: MS-AMP)z--fp8_use_autocast_during_evalzWhether to use FP8 autocast during eval mode (useful only when `--fp8_backend=te` is passed). Generally better metrics are found when this is not passed.z--fp8_marginz[The margin to use for the gradient scaling (useful only when `--fp8_backend=te` is passed).z--fp8_intervalzsThe interval to use for how often the scaling factor is recomputed (useful only when `--fp8_backend=te` is passed).z--fp8_formatE4M3HYBRIDzUThe format to use for the FP8 recipe (useful only when `--fp8_backend=te` is passed).z--fp8_amax_history_leni   ztThe length of the history to use for the scaling factor computation (useful only when `--fp8_backend=te` is passed).z--fp8_amax_compute_algomost_recentmaxziThe algorithm to use for the scaling factor computation. (useful only when `--fp8_backend=te` is passed).z--fp8_override_linear_precisionc                 l    t          t          t          |                     d                              S )N,)tupler`   r    split)xs    r<   <lambda>z'launch_command_parser.<locals>.<lambda>  s"    uSaggcll;;<< r>   )FFFzWhether or not to execute `fprop`, `dgrad`, and `wgrad` GEMMS in higher precision. Should be passed in a comma-seperated string of booleans (useful only when `--fp8_backend=te` is passed).z--fp8_opt_levelO2O1z{What level of 8-bit collective communication should be used with MS-AMP (useful only when `--fp8_backend=msamp` is passed).zAWS ArgumentszArguments related to AWS.z--aws_access_key_idzFThe AWS_ACCESS_KEY_ID used to launch the Amazon SageMaker training jobz--aws_secret_access_keyzKThe AWS_SECRET_ACCESS_KEY used to launch the Amazon SageMaker training job.z--debugzLWhether to print out the torch.distributed stack trace when something fails.training_scriptznThe full path to the script to be launched in parallel, followed by all the arguments for the training script.)r   re   zMPI Argumentsz)Arguments related to mpirun for Multi-CPUz--mpirun_hostfilezLocation for a hostfile for using Accelerate to launch a multi-CPU training job with mpirun. This will get passed to the MPI --hostfile or -f parameter, depending on which MPI program is installed.z--mpirun_cclzcThe number of oneCCL worker threads when using Accelerate to launch multi-CPU training with mpirun.training_script_argsz!Arguments of the training script.)nargsre   )func)
add_parserr@   r   ri   add_argument_groupstrintr   r"   floatrc   	REMAINDERset_defaultslaunch_command)
subparsersry   parserhardware_argsresource_argsparadigm_argsdistributed_argstpu_argsdeepspeed_args	fsdp_argsmegatron_lm_argsfp8_argsaws_argsmpirun_argss                 r<   launch_command_parserr      s?    pK&&+Ecv ' 
 
 &'#/
 
 
 hv<^___
U    
  m	     --&(Z M |:l     L	     |:m     [	     --&(j M ---[	     T8s     sD7l     '[	     x	     ==_====2	     "C      j	     7	     --%'d M (	     #	     *	     S	     001CEuvv!!f "   
 !!`	 "    !!sD7r "    !!#t:d "    !!I	 "    !!C "    !!E "    !!1	 "    !!U	 "    !!Y	 "    !!F	 "    !!E	 "     G	      L     ((0KLLH9	     N	     V    
 P     ^	     "c	      W     ../DFghhN!%	      /	      $2	       2	      '2	      #2	      '/	      1	      _	      "`	      O	      &M	      &M	      (\	      )>	      ))*:<qrrI F	     {	     "V	     !U	     .8	     "]	      T	     !g	      9	     *8	     #9	     ) A	     001HJmnn!!!q	 "    !!!s	 "    !!)}	 "    !!,?	 "    !!-?	 "    !!1?	 "    !!)?	 "    ((_ H wX	     ( i	     j	      C	     "d       D	     !&x     )<<% L	     t K     ((:UVVHU	     !Z	     [    
 	     ++O=hiiKi	     r	     .h6HOrsss000Mr>   c                    t          |           \  }}t          j        ||          }|                                 |j        dk    r8| j        st          j        |j        |          t          j        d           d S d S )Nenvr   
returncodecmdrP   )	r   
subprocessPopenwaitr   quietCalledProcessErrorr\   exit)rI   r   current_envprocesss       r<   simple_launcherr     s    6t<<Cs444GLLNNNQz 	/7;MSVWWWWHQKKKKK	 r>   c                 ~   dd l mc m} t          |           }t	                      s6d}d}d|vrd|d<   d}d|vrd|d<   d}|rt
                              |           t          | dd          }t          | |	                                d	| j
        d
| j        g          } t          di |5  	 |                    |            nb# t          $ rU t                      rC|rAt                      }|                    d           |                    t$          gd           n Y nw xY wd d d            d S # 1 swxY w Y   d S )Nr   {Using RTX 4000 series which doesn't support faster communication speedups. Ensuring P2P and IB communications are disabled.FNCCL_P2P_DISABLE1TNCCL_IB_DISABLEdebug--training_script--training_script_argsE
[bold red]Using --debug, `torch.distributed` Stack Trace:[/bold red]suppressshow_localsrR   )torch.distributed.rundistributedrunr   r   loggerwarninggetattrr   get_args_parserr   r   r   	Exceptionr   r#   printprint_exception__file__)rI   distrib_runr   messagewarnr   consoles          r<   multi_gpu_launcherr      s   /////////'--K$&& 
$ P[00.1K*+DK//-0K)*D 	$NN7###D'5))E##%%	d24LdNgh D 
	)	)[	)	) 	 		OOD!!!! 	 	 	 "" u %--fggg''('OOOO PO			 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s7   +D2-CD2AD"D2!D""D22D69D6c                    dd l mc m} t                      st	          d          ddlm} t          |           \  }}t                      s6d}d}d|vrd|d<   d}d	|vrd|d	<   d}|rt          
                    |           | j        d
k    r| j        t          d
         k    rt          |d          5 }t          |          }t!          |          d
k    r|                    |           d d d            n# 1 swxY w Y   t%          j        ||          }	|	                                 |	j        dk    r8| j        st%          j        |	j        |          t1          j        d
           d S d S t5          | dd          }
t7          | |                                d| j        d| j        g          } t?          di |5  	 |                    |            nb# t@          $ rU tC                      rC|
rAtE                      }|#                    d           |$                    tJ          gd           n Y nw xY wd d d            d S # 1 swxY w Y   d S )Nr   zSDeepSpeed is not installed => run `pip3 install deepspeed` or build it from source.)DEEPSPEED_ENVIRONMENT_NAMEr   Fr   r   Tr   rP   ar   r   r   r   r   r   r   rR   )&r   r   r   r   ImportErrordeepspeed.launcher.runnerr   r   r   r   r   num_machinesdeepspeed_multinode_launcherr!   openr   r^   
writelinesr   r   r   r   r   r   r\   r   r   r   r   r   r   r   r   r   r#   r   r   r   )rI   r   r   r   r   r   r   fvalid_env_itemsr   r   r   s               r<   deepspeed_launcherr   #  sB   /////////!## IopppHHHHHH066C$&& 
$ P[00.1K*+DK//-0K)*D 	$NN7###1!BFcdeFf!f!f,c22 	.a;KHHO?##a''_---	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	.
 "3K888"":  3w?QWZ[[[[	 #" gu--'')) $"68PRVRkl
 

 ---- 		 		%%%%   $&& 5 )mmGMM"jkkk++hZU+SSSS TS			 		 		 		 		 		 		 		 		 		 		 		 		 		 		 		 		 		sI   48C88C<?C< IGIAH74I6H77IIIc                    dd l mc m} | j        rt	          d          t          | i           \  } }| j        r| j        }n^t          | j                  }t          j
                            t          |j                                                             |j        }t!          j        |          }t%          || j                  st	          d| j         d          |j        g| j        z   t          _        t/          || j                  }t1          di |5  |                    t5          |          d| j                   d d d            d S # 1 swxY w Y   d S )Nr   z,--no_python cannot be used with TPU launcherz2Your training script should have a function named zE, or you should pass a different value to `--main_training_function`.rR   )rI   nprocs))torch_xla.distributed.xla_multiprocessingr   xla_multiprocessing	no_python
ValueErrorr   moduler   r   r\   pathr   r   parentresolvestem	importlibimport_modulehasattrmain_training_functionr   r   r]   r   r   spawnr   num_processes)rI   xmpr   mod_namescript_pathmodmain_functions          r<   tpu_launcherr  X  s   ;;;;;;;;;~ IGHHH#D"--D+{ $' 4/00K.668899:::#

!(
+
+C3344 
=A\ = = =
 
 	
 ~ 99CHC!<==M		)	)[	)	) W W		"=114CU	VVVW W W W W W W W W W W W W W W W W Ws   +EEEc                    ddl m} i }t          | |d          \  } }t          | dd          }| j        }| j        }t          | |                                d| j        ddd	g          }| j	        rd
g}ng }|ddddddddddt          | j                  dt          | j                  |g|z   z  }||_        d}t          |          D ]:}	|	                    d          r#t          ||	          }
|
dk    r|
||	 d|
 dz  };|dk    rt!          d|           d |                                D             |_        |j                            d           	 |                    |           d S # t*          $ rU t-                      rE|rCt/                      }|                    d           |                    t4          gd           Y d S  w xY w)Nr   )xla_distTr   Fr   z--positionalrm   z--restart-tpuvm-pod-serversudozaccelerate-launchr   r   r   r   r   r   r   r   docker_z="z"
zgDocker containers are not supported for TPU pod launcher currently, please remove the following flags:
c                 "    g | ]\  }}| d | S )=rR   )rU   kvs      r<   rW   z$tpu_pod_launcher.<locals>.<listcomp>  s&    ???41aqJJ1JJ???r>   zACCELERATE_IN_TPU_POD=1zF
[bold red]Using --debug, `torch_xla.xla_dist` Stack Trace:[/bold red]r   )torch_xla.distributedr  r   r   r   r   r   r   tpu_nametpu_use_sudor   r  r  
positionalvarsr9   r   ro   r   r   resolve_and_executer   r   r#   r   r   r   )rI   r  r   r   r   r   new_argsnew_cmd	bad_flagsrV   valuer   s               r<   tpu_pod_launcherr   w  sh   ......K#D+t<<D+D'5))E*O4h&&((7DM>SUWs*t H  (D"D'(( 	 G" "HIH~~ 2 2>>)$$ 	2Hc**E{{u011u1111	B C  xA  C  C
 
 	
 @?;+<+<+>+>???HLL1222$$X.....    	5 	!mmGMMcddd##hZU#KKKKKKs   E0 0AGGsagemaker_configc                    t                      st          d          |j        s|j        rt	          d          ddlm} t          | |          \  }} |di |}|                    |           t          d|j
                    d S )NzsPlease install sagemaker to be able to launch training on Amazon SageMaker with `pip install accelerate[sagemaker]`z`SageMaker requires a python training script file and cannot be used with --module or --no_pythonr   )HuggingFace)inputsz!You can find your model data at: rR   )r   r   r   r   r   sagemaker.huggingfacer#  r   fitr   
model_data)r!  rI   r#  sagemaker_inputshuggingface_estimators        r<   sagemaker_launcherr*    s    !## 
 B
 
 	
 { 
dn 
n
 
 	
 211111:;KTRRD
'K//$//%5666	
P.C.N
P
PQQQQQr>   c           	      :   t          | j        | j        | j        | j        | j        g          dk    rt          d          | j        r!| j        | j        dk     rt          d          d }g }d}| j        -t          j
                            t                    r| j        st          | j                  }| j        s| j        s| j        s| j        s| j        s| j        s|j        t"          j        k    | _        |j        t"          j        t"          j        t"          j        t"          j        t"          j        fv rdnd| _        |j        t"          j        k    | _        |j        t"          j        k    | _        |j        t"          j        k    | _        | j        r|j        nd| _        | j        |j        |j        | _        nd| _        | j        r| j        |j        | _        t;          | j                            d                    dk     r,| j        dk    r!| j        r| j        dk    rt          d	          |j        t@          j!        k    rM|j"        #                                D ]2\  }}tI          |tJ                    r|j&        D ]}tO          | ||j&        |                    |j(        D ])}|}d
|vrd|z   }tO          | ||j(        |                    *|j)        D ]}tO          | ||j)        |                    |j*        D ]}tO          | ||j*        |                    |j+        D ]}tO          | ||j+        |                    |j,        D ]}tO          | ||j,        |                    |dvr"t[          | |d           tO          | ||           4| j.        s|j.        | _.        | j/        s|j/        d| _/        n|j/        | _/        d}n| j0        s%| j1        r/td          j3        4                                rtk          dd          }ntm          d          }| j/        dk    r(|s&| j        rto          d          st          d          | j8        d| _8        | j        dk    rt          d          n| j        | j1        r2ts                      r$td          j3        :                                | _        ntw                      r$td          j<        :                                | _        nt{                      r$td          j>        :                                | _        nUt                      r$td          j@        :                                | _        n#td          jA        :                                | _        |B                    d| j         d           | j.        d| _.        | j        s| j        dk    r| j1        r0ts                      r"td          j3        :                                dk    stw                      r"td          j<        :                                dk    st{                      r"td          j>        :                                dk    sRt                      r"td          j@        :                                dk    s"td          jA        :                                dk    r|B                    d           d| _        | j        |B                    d           d| _        | j/        |B                    d           d| _/        t          | d          s| j        | _0        | j8        |B                    d           d| _8        | j.        rt          .                    d           |d u p|d uo|j        t@          jE        k    }	|	r| jF        t          dgd          | _F        | j0        r| j        dk    rt          dgd          dk    rt          g dt          t          | j        | j        z            d                    }
t          t          jK        d           |
z            }|dk    r%|| _F        |B                    d!| jF         d"           t          |          r9d#}|d$M                    |          z  }|d%z  }t          N                    |           | ||fS )&NrP   zcYou can only use one of `--cpu`, `--multi_gpu`, `--tpu`, `--use_deepspeed`, `--use_fsdp` at a time.r6   z:You need to use at least 2 processes to use `--multi_gpu`.FTallr   zLess than two GPU ids were configured and tried to run on on multiple GPUs. Please ensure at least two are specified for `--gpu_ids`, or use `--gpu_ids='all'`.fsdpfsdp_)compute_environmentmixed_precisiondistributed_typer   z>=z1.10r   )check_is_tpuzEbf16 mixed precision requires PyTorch >= 1.10 and a supported device.zFYou need to manually pass in `--num_processes` using this config yaml.z*	`--num_processes` was set to a value of ``zx		More than one GPU was found, enabling multi-GPU training.
		If this was unintended please pass in `--num_processes=1`.z+	`--num_machines` was set to a value of `1`z1	`--mixed_precision` was set to a value of `'no'`use_cpuz0	`--dynamo_backend` was set to a value of `'no'`zRRunning script in debug mode, expect distributed operations to be slightly slower.OMP_NUM_THREADSr   )MPI_LOCALNRANKSOMPI_COMM_WORLD_LOCAL_SIZEMV2_COMM_WORLD_LOCAL_SIZE)logicalz-	`--num_cpu_threads_per_process` was set to `z9` to improve out-of-box performance when training on CPUsz[The following values were not passed to `accelerate launch` and had defaults used instead:

zh
To avoid this warning pass in values for each of the problematic parameters or run `accelerate config`.)Osumr.   cpur/   r0   r1   r   r  config_fileosr   isfiler   r   r   r2   r1  r   	DEEPSPEED	MULTI_GPU	MULTI_NPU	MULTI_MLU
MULTI_MUSA	MULTI_XPUXLAFSDPMEGATRON_LMgpu_idsr   r^   r   r/  r
   LOCAL_MACHINE__dict__ro   
isinstancedictdeepspeed_configsetattrfsdp_configmegatron_lm_configdynamo_configipex_configmpirun_configr   r   r0  r5  use_xputorchxpuis_availabler   r   r   dynamo_backendr   device_countr   mlur   musar   npucudar   r  r   AMAZON_SAGEMAKERnum_cpu_threads_per_processr	   r   r   psutil	cpu_countanyjoinr   )rI   defaultswarnedmp_from_config_flagnameattrr  
arg_to_set
native_ampis_aws_env_disabled
local_sizethreads_per_processr   s                r<   _validate_launch_commandrp    s4	   
DNDHdh0BDMRSSVWWWq
 
 	
 ~ W4-9@RUV@V@VUVVVHF#rw~~6I'J'J#SWS[#()9::	SH	S (	S &		S
 M	S (	S "*!:o>W!WD ,#-#-#-#.#-    N  0O4GGDH$59MMDM#+#<@[#[D ?Cx#R8#;#;UD <+'/$> 	6d/7 ( 5Dt|!!#&&''!++1F1FDN1F_c_ptu_u_uf   '+=+KKK&/5577 . .
ddD)) %6 G Ga)B1)EFFFF%1 K K%&
!33)0:)=Jj(2Fq2IJJJJ%8 I Ia)DQ)GHHHH%3 D Da)?)BCCCC%1 B Ba)=a)@AAAA%3 D Da)?)BCCCC  ^^^dD119D$---z 	(!DJ# 	j'/'+$$'/'?$&*##| 5 51G1G1I1I 5-dF;;

.t44
$.." / /&<$&O&O&O / !!hiii &"&D##efff $ %| 	? 0 2 2 	?%*Y%;%;%=%=""!## ?%*Y%;%;%=%="""$$ ?%*Z%<%<%>%>""!## ?%*Y%;%;%=%=""%*Z%<%<%>%>"MM]HZ]]]^^^:DJ	""Q&& '"2"4"4 '9>9O9O9Q9QTU9U9U$&& :V+09+A+A+C+Ca+G+G%'' ,H,1J,C,C,E,E,I,I$&& -J+09+A+A+C+Ca+G+GJ++--11 MMQ   "DN$MMHIII !D'MMNOOO#'D tY'' 	$8DL&MMMNNN"&Dz kijjj"d* d!=ASAd!d   t?G+;=N<OQR+S+S(< 
	D.!338HJ[I\^_8`8`de8e8e)^^^C*T->>??CC J #&f&6u&E&E&E
&R"S"S"Q&&3F0 aTEe  a  a  a   6{{  p499V$$$w	
 	w...r>   c                    t          |           \  } }}| j        r| j        s{|r&t          |j                                                  ng | _        |r| j                            d           d                    | j                  | _        t          |            d S | j
        r| j        st          |            d S | j        r| j        st          |            d S | j        r| j        st          |            d S | j        r0| j        s)| j        rt!          |            d S t#          |            d S |'|j        t&          j        k    rt+          ||            d S t-          |            d S )Nr0  r   )rp  r0   r=  r_   rO  rT   'deepspeed_fields_from_accelerate_configr   re  r   r1   r   r2   r.   r/   r   r   r  r/  r
   r`  r*  r   )rI   rf  rh  s      r<   r   r   y  s   *B4*H*H'D(' $( ai7qtH<U<Z<Z<\<\7]7]7]oq4 	S8??@QRRR7:xx@l7m7m44     	 tx 4     		 dh 4     	 
 
4     	 $(  	T"""""		(">BTBe"e"e8T*****r>   c                  h    t                      } |                                 }t          |           d S N)r   
parse_argsr   )r   rI   s     r<   mainrv    s2    "$$FD4r>   __main__rt  )Grc   r  loggingr?  r   r\   pathlibr   rb  rW  accelerate.commands.configr   r   &accelerate.commands.config.config_argsr   'accelerate.commands.config.config_utilsr   accelerate.commands.utilsr   accelerate.stater	   accelerate.utilsr
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    accelerate.utils.constantsr!   r"   richr#   rich.loggingr$   FORMATbasicConfig	getLoggerrr   r   rS   r=   HelpFormatterr@   r   r   r   r   r  r   r*  rp  r   rv  rR   r>   r<   <module>r     s  "       				     



         Q Q Q Q Q Q Q Q B B B B B B C C C C C C : : : : : : - - - - - -                                                 2 Y X X X X X X X  Q      ((((((FGvvPPPP 
	8	$	$ $* ."  , , ,/ / / / /(0 / / /de	 e	 e	 e	P	 	 	     F2 2 2jW W W>8 8 8vR R R R R(p/ p/ p/f  4   zDFFFFF r>   