
    Pi!                        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
 d dlmZmZ d dlmZ d dlmZmZ ded	ed
dfdZde
eeef         ef         d
efdZded
efdZdede	e         d
efdZdeeef         ded
dfdZdS )    )	Namespace)import_module)
ModuleType)AnyDictListUnion)
DictConfig	OmegaConf)InstantiationError)
get_loggerlog_rank_zerorecipe_namecfgreturnNc                     t          d          }t          j        |dd          }t          |d|  d|            dS )z
    Logs the resolved config (merged YAML file and CLI overrides) to rank zero.

    Args:
        recipe_name (str): name of the recipe to display
        cfg (DictConfig): parsed config object
    DEBUGT)resolve	sort_keyszRunning z with resolved config:

)loggermsgN)r   r   to_yamlr   )r   r   r   cfg_strs       k/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/torchtune/config/_utils.py
log_configr      s_       FTTBBBGVkVVWVV         nodec                 \    t          j        |           st          | t                    od| v S )N_component_)r   is_dict
isinstancedict)r   s    r   _has_componentr#   !   s-    d##=z$'='=X=TXCXXr   pathc                    | dk    rt          d          d |                     d          D             }|D ]'}t          |          st          d|  ddz             (|d         }	 t          |          }n<# t          $ r/}t          d|  d	t          |           d
| dz             |d}~ww xY wt          dt          |                    D ]1}||         }	 t          ||          }# t          $ r}d
                    |d|                   }t          |t                    rd
                    |d|dz                      }		 t          |	          }Y d}~# t          $ r2}t          d|  d	t          |           d| d| dz             |d}~wt          $ r(}t          d|  d	t          |                     |d}~ww xY wt          d|  d	t          |           d| d| dz             |d}~ww xY w|S )aY  
    Return an object by name or dotted path, importing as necessary.
    The base functionality relies on ``getattr()`` and handles all
    possible exceptions accordingly.

    Based on Hydra's `_locate` from Facebook Research:
    https://github.com/facebookresearch/hydra/blob/main/hydra/_internal/utils.py#L614

    Args:
        path (str): Dotted path of the object

    Returns:
        Any: The object

    Raises:
        InstantiationError: If there is an exception loading the
            object from the provided path
        ValueError: If a relative or invalid dotpath is passed in
     z
Empty pathc                     g | ]}|S  r(   ).0parts     r   
<listcomp>z,_get_component_from_path.<locals>.<listcomp><   s    ...dT...r   .zError loading 'z': invalid dotstring.z$
Relative imports are not supported.r   z':
z
Are you sure that module 'z' is installed?N   z
Are you sure that 'z' is importable from module 'z'?z' is an attribute of ')
ValueErrorsplitlenr   ImportErrorr   reprrangegetattrAttributeErrorjoinr!   r   ModuleNotFoundError	Exception)
r$   partsr*   part0obj
exc_importmexc_attrparent_dotpathmods
             r   _get_component_from_pathrA   %   s   ( rzz&&&..djjoo...E  4yy 	=$===9:  	 !HEE""    :d::Z(8(8::CUCCCD
 
 	 1c%jj!!  Qx	#t$$CC  	 	 	 XXeBQBi00N#z** &hhuWq1uW~..&',,CHHHH* & & &,F$FFD4D4DFFg$ggUcgggh  && ! & & &,F$FFD4D4DFF %&&
 %<$<<DNN<<X$XXnXXXY  '	. Js[   (A8 8
B1*B,,B1C..H9AG<E  
G*-FG$#GG0G<<H	yaml_argscli_argsc                    t          |           }g }|D ]}|                    d          ru|dd                             d          d         }d|v rt          d|           	 t	          ||           n)# t
          t          f$ r t          d| d	          dw xY w	 |                    d          \  }}n!# t          $ r t          d
|           dw xY w||v rt          ||                   r|dz  }|dk    rd}d|v rd|z   }|                    | d|            t          j	        |          }t          j
        |          }	t          j        |	|          S )a  
    Takes the direct output of argparse's parse_known_args which returns known
    args as a Namespace and unknown args as a dotlist (in our case, yaml args and
    cli args, respectively) and merges them into a single OmegaConf DictConfig.

    If a cli arg overrides a yaml arg with a _component_ field, the cli arg can
    be specified with the parent field directly, e.g., model=torchtune.models.lora_llama2_7b
    instead of model._component_=torchtune.models.lora_llama2_7b. Nested fields within the
    component should be specified with dot notation, e.g., model.lora_rank=16.

    Example:
        >>> config.yaml:
        >>>     a: 1
        >>>     b:
        >>>       _component_: torchtune.models.my_model
        >>>       c: 3

        >>> tune full_finetune --config config.yaml b=torchtune.models.other_model b.c=4
        >>> yaml_args, cli_args = parser.parse_known_args()
        >>> conf = _merge_yaml_and_cli_args(yaml_args, cli_args)
        >>> print(conf)
        >>> {"a": 1, "b": {"_component_": "torchtune.models.other_model", "c": 4}}

    Args:
        yaml_args (Namespace): Namespace containing args from yaml file, components
            should have _component_ fields
        cli_args (List[str]): List of key=value strings

    Returns:
        DictConfig: OmegaConf DictConfig containing merged args

    Raises:
        ValueError: If a cli override is not in the form of key=value
    ~r-   N=r   r   0Removing components from CLI is not supported: ~zCould not find key z in yaml config to removez=Command-line overrides must be in the form of key=value, got z._component_Nonez!!nullmax_filenamez!!str )vars
startswithr/   r.   _remove_key_by_dotpathKeyErrorr#   appendr   from_dotlistcreatemerge)
rB   rC   yaml_kwargscli_dotlistargdotpathkvcli_conf	yaml_confs
             r   _merge_yaml_and_cli_argsrZ   p   s   H y//KK $' $'>># 	!""gmmC((+G'' PwPP  &{G<<<<j)    L'LLL  	99S>>DAqq 	 	 	UPSUU 	 {1~ > >A ;;A
 Q1Aa::!::&&&& %k22H --I ?9h///s   &A77&B"B;;Cnested_dictrU   c                                         d          }dt          t          t          f         dt          ddffddt          t          t          f         dt          t                   ddffd | |           dS )	z
    Removes a key specified by dotpath from a nested dict. Errors should handled by
    the calling function.

    Args:
        nested_dict (Dict[str, Any]): Dict to remove key from
        dotpath (str): dotpath of key to remove, e.g., "a.b.c"
    r,   dkeyr   Nc                 \    t          | |                   rt          d           | |= d S )NrG   )r#   r.   )r]   r^   rU   s     r   delete_non_componentz4_remove_key_by_dotpath.<locals>.delete_non_component   sA    !C&!! 	L7LL   cFFFr   r$   c                     t          |          dk    r | |d                    d S  | |d                  |dd                     | |d                  s | |d                    d S d S )Nr-   r   )r0   )r]   r$   r`   recurse_and_deletes     r   rb   z2_remove_key_by_dotpath.<locals>.recurse_and_delete   s    t99>>  DG,,,,,qaz48444T!W: 1$$QQ000001 1r   )r/   r   strr   r   )r[   rU   r$   r`   rb   s    ` @@r   rL   rL      s     ==DS#X S T      1d38n 1DI 1$ 1 1 1 1 1 1 1 {D)))))r   )argparser   	importlibr   typesr   typingr   r   r   r	   	omegaconfr
   r   torchtune.config._errorsr   torchtune.utils._loggingr   r   rc   r   boolr#   rA   rZ   rL   r(   r   r   <module>rl      s         # # # # # #       ) ) ) ) ) ) ) ) ) ) ) ) + + + + + + + + 7 7 7 7 7 7 > > > > > > > >C j T    YtCH~z9: Yt Y Y Y YH3 H3 H H H HVQ0	 Q0T#Y Q0: Q0 Q0 Q0 Q0h*S#X * * * * * * * *r   