
    Pi"                         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mZ d dl	Z	d dl
mZ d dlmZmZ d dlmZ d dlmZmZmZ  ee	j                  j        j        Z G d d	e          ZdS )
    N)Path)Optional)record)get_args_parserrun)
Subcommand)Configget_all_recipesRecipec                        e Zd ZdZ fdZddZedej        de	fd            Z
dej        de	fd	Zdej        fd
Zdedee         fdZdedefdZdedee         dee         fdZdej        fdZ xZS )Runz2Holds all the logic for the `tune run` subcommand.c           
      *   t                                                       |                    dddddt          j        d          t
          j                  | _        |                                  | j        	                    | j
                   d S )Nr   ztune runzLRun a recipe. For distributed recipes, this supports all torchrun arguments.zGtune run [TORCHRUN-OPTIONS] <recipe> --config <config> [RECIPE-OPTIONS]as                  examples:

                    # Run a finetuning recipe on a single device w/ default values
                    $ tune run lora_finetune_single_device --config llama2/7B_lora_single_device

                    # Run a finetuning recipe in a distributed fashion using torchrun w/ default values
                    $ tune run --nproc_per_node 4 full_finetune_distributed --config llama2/7B_full_finetune_distributed

                    # Override a parameter in the config file and specify a number of GPUs for torchrun
                    $ tune run --nproc_per_node 2                         lora_finetune_single_device                         --config llama2/7B_lora_single_device                         model.lora_rank=16 
                Remember, you can use `tune cp` to copy a default recipe/config to your local dir and modify the values.
                )proghelpdescriptionusageepilogformatter_class)func)super__init__
add_parsertextwrapdedentargparseRawTextHelpFormatter_parser_add_argumentsset_defaults_run_cmd)self
subparsers	__class__s     f/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/torchtune/_cli/run.pyr   zRun.__init__   s    !,,_f[? & %93 - 
 
6 	!!t}!55555    returnNc                     t                      }|j        D ]\}|j        dk    rd|_        d|_        n&|j        dk    rd|_        d|_        n|j        dk    rB| j                            |           ]dS )	a  Add arguments to the parser.

        This is a bit hacky since we need to add the torchrun arguments to our parser.
        This grabs the argparser from torchrun, iterates over it's actions, and adds them
        to our parser. We rename the training_script and training_script_args to recipe and recipe_args
        respectively. In addition, we leave out the help argument since we add it manually to ours.
        training_scriptrecipezjName or path to recipe to be launched followed by args.
For a list of all possible recipes, run `tune ls`.training_script_argsrecipe_argsz Args to be passed to the recipe.r   N)get_torchrun_args_parser_actionsdestr   r   _add_action)r!   torchrun_argparseractions      r$   r   zRun._add_arguments=   s     677(1 
	- 
	-F{///&6 666+@&&L$$V,,,,
	- 
	-r%   args
is_builtinc                     t          d           |j        |_        |j        |_        |j        sd|_        | |_        t          |           dS )zRun a recipe with torchrun.zRunning with torchrun...TN)	printr)   r(   r+   r*   rdzv_endpoint
standalonemoduler   r!   r2   r3   s      r$   _run_distributedzRun._run_distributedR   sV    
 	()))#{$($4! ! 	#"DO
 %nD					r%   c                     t          |j                  g|j        z   t          _        |r*t          j        t          |j                  d           dS t          j        t          |j                  d           dS )z Run a recipe on a single device.__main__)run_nameN)strr)   r+   sysargvrunpyrun_path
run_moduler9   s      r$   _run_single_devicezRun._run_single_deviceg   st    $$%(88 	DN3t{++jAAAAAA S--
CCCCCCr%   c                 t    t          t          j                  dz
  }t          |j                  dz   }||k    S )z8Check if the user is trying to run a distributed recipe.      )lenr?   r@   r+   )r!   r2   totalscript_argss       r$   _is_distributed_argszRun._is_distributed_argsq   s4    CH!$*++a/{""r%   
recipe_strc                 F    t                      D ]}|j        |k    r|c S dS )zGet a recipe from the name or path.

        Args:
            recipe_str (str): The name or path of the recipe.

        Returns:
            The recipe if it's found in built-in recipes, otherwise None.
        N)r
   name)r!   rL   r)   s      r$   _get_recipezRun._get_recipew   s>     &'' 	 	F{j(( )	 	r%   recipe_pathc                 r    t           j                            |          \  }}|                    dd          S )zConvert a custom recipe path to a dot path that can be run as a module.

        Args:
            recipe_path (str): The path of the recipe.

        Returns:
            The dot path of the recipe.
        /.)ospathsplitextreplace)r!   rP   filepath_s       r$   _convert_to_dotpathzRun._convert_to_dotpath   s3     g&&{33!S)))r%   
config_strspecific_recipec                     ||j         D ]}|j        |k    r|c S t                      D ]}|j         D ]}|j        |k    r|c c S dS )a,  Get a config from the name or path.

        Args:
            config_str (str): The name or path of the config.
            specific_recipe (Optional[Recipe]): The specific recipe to search through.

        Returns:
            The config if it's found in built-in configs, otherwise None.
        N)configsrN   r
   )r!   r[   r\   configr)   s        r$   _get_configzRun._get_config   s     &)1 " ";*,,!MMM - &'' 	" 	"F . " ";*,,!MMMMM -"	" 	"r%   c                 R   d}d\  }}	 |j                             d          dz   }|j         |         }n*# t          $ r | j                            d           Y nw xY w|                     |j                  }||                     |j                  }d}n(t          t          dz  |j
        z            }|j        }d}|                     ||          }	|	|}n"t          t          dz  d	z  |	j
        z            }||_        ||j         |<   t          j                            t!          j                               |                     |          r>|s#| j                            d
|j         d           |                     ||           dS |                     ||           dS )zRun a recipe.T)NNz--configrG   z$The '--config' argument is required.NFrecipesr^   zRecipe zL does not support distributed training.Please run without torchrun commands.)r3   )r+   index
ValueErrorr   errorrO   r)   rZ   r>   ROOT	file_pathsupports_distributedr`   r?   rU   appendrT   getcwdrK   rN   r:   rD   )
r!   r2   rh   rP   config_path
config_idxr[   r)   r3   r_   s
             r$   r    zRun._run_cmd   s     $#- [	G)//
;;a?J)*5JJ 	G 	G 	GLEFFFFF	G !!$+..>224;??KJJdY.1AABBK#)#> J !!*f55>$KKdY.:V=MMNNK "'2$ 		$$$ $$T** 	A' ""<fk < < <   !!$:!>>>>>##DZ#@@@@@s   *4 $AA)r&   N)__name__
__module____qualname____doc__r   r   r   r   	Namespaceboolr:   rD   rK   r>   r   r   rO   rZ   r	   r`   r    __classcell__)r#   s   @r$   r   r      ss       <<6 6 6 6 6@- - - -* X%7 T    V(Dx'9 Dt D D D D#); # # # #c hv.>    
*s 
*s 
* 
* 
* 
*""080@"	&	" " " "0.AX/ .A .A .A .A .A .A .A .Ar%   r   )r   rT   rA   r?   r   pathlibr   typingr   	torchtune0torch.distributed.elastic.multiprocessing.errorsr   torch.distributed.runr   r,   r   torchtune._cli.subcommandr   torchtune._recipe_registryr	   r
   r   __file__parentrf   r    r%   r$   <module>r~      s    				  



                  C C C C C C R R R R R R R R 0 0 0 0 0 0 F F F F F F F F F FtI&-|A |A |A |A |A* |A |A |A |A |Ar%   