o
    9wi0                  
   @   s(  d dl 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	m
Z
mZmZmZmZmZmZmZmZmZ d dlZd dl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 d dl m!Z" d d
l#m$Z$ d dl m%Z%m&Z&m'Z'm(Z(m)Z) d dl*m+Z+ d dl,m-Z- d dl.m/Z/ d dl0m1Z1 edZ2e2rd dl3Z3d dl4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z: e9e e:dd n
e;e< d< e;e< d< edZ=G dd dej>j?j@Z@ee@fZAeee@f ZBeee ee@ f ZCeeeeD eeDe	f e7f  ZEe
egef ZFe
egeee@f f ZGG dd de6ZHG dd de%ZIG dd dZJded eDfd!d"ZK	d8ded#eee7eeDe	f f  d eeDe	f fd$d%ZLded e
e7geeDe	f f fd&d'ZMd(ee	ee	d)f f d*eeDe	f d e	fd+d,ZNd-e;d eeD fd.d/ZOd0ee
ePf d ePfd1d2ZQG d3d4 d4ZRdee= d5eeDe	f d e=fd6d7ZSdS )9    N)partialupdate_wrapper)
MethodType)AnyCallableDictIterableListOptionalSetTupleTypeTypeVarUnion)RequirementCache)_warn)	Optimizer)LRScheduler)override)get_filesystem)CallbackLightningDataModuleLightningModuleTrainerseed_everything)_given_hyperparameters_context)MisconfigurationException)is_overridden)rank_zero_warnz jsonargparse[signatures]>=4.27.7)ActionConfigFileArgumentParser	Namespaceclass_from_function"register_unresolvable_import_pathsset_config_read_modeT)fsspec_enabledr    r!   
ModuleTypec                
       s2   e Zd Zdededededdf
 fddZ  ZS )	ReduceLROnPlateau	optimizermonitorargskwargsreturnNc                    s$   t  j|g|R i | || _d S N)super__init__r)   )selfr(   r)   r*   r+   	__class__ R/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/lightning/pytorch/cli.pyr/   <   s   
zReduceLROnPlateau.__init__)__name__
__module____qualname__r   strr   r/   __classcell__r3   r3   r1   r4   r'   ;   s    *r'   c                       s  e Zd ZdZdddddededed	ed
eddf fddZ		d!dee	dee
eeef f ee
 ee ee ee f dedededee f
ddZefddfdeee eee df f dededdfddZeddfdeeeedf f dededdfdd Z  ZS )"LightningArgumentParserzAExtension of jsonargparse's ArgumentParser for pytorch-lightning.z#Lightning Trainer command line toolPLFdescription
env_prefixdefault_envr*   r=   r>   r?   r+   r,   Nc                   s>   t stt  t j||||d| g | _i | _i | _dS )a  Initialize argument parser that supports configuration file input.

        For full details of accepted arguments see `ArgumentParser.__init__
        <https://jsonargparse.readthedocs.io/en/stable/#jsonargparse.ArgumentParser.__init__>`_.

        Args:
            description: Description of the tool shown when running ``--help``.
            env_prefix: Prefix for environment variables. Set ``default_env=True`` to enable env parsing.
            default_env: Whether to parse environment variables.

        r<   N)"_JSONARGPARSE_SIGNATURES_AVAILABLEModuleNotFoundErrorr.   r/   callback_keys_optimizers_lr_schedulers)r0   r=   r>   r?   r*   r+   r1   r3   r4   r/   P   s   

z LightningArgumentParser.__init__Tlightning_class.
nested_keysubclass_moderequiredc                 C   s   t |rt|tst|}t|tr?t|ttttfr?t|tr&| j	
| |r1| j||d|dS | j||dt|t ddS td| d)a  Adds arguments from a lightning class to a nested key of the parser.

        Args:
            lightning_class: A callable or any subclass of {Trainer, LightningModule, LightningDataModule, Callback}.
            nested_key: Name of the nested namespace to store arguments.
            subclass_mode: Whether allow any subclass of the given class.
            required: Whether the argument group is required.

        Returns:
            A list with the names of the class arguments added.

        F)fail_untypedrH   T)rI   instantiatesub_configszCannot add arguments from: zt. You should provide either a callable or a subclass of: Trainer, LightningModule, LightningDataModule, or Callback.)callable
isinstancetyper"   
issubclassr   r   r   r   rB   appendadd_subclass_argumentsadd_class_argumentsr   )r0   rE   rF   rG   rH   r3   r3   r4   add_lightning_class_argsk   s&   


z0LightningArgumentParser.add_lightning_class_argsr(   	AUTOMATICoptimizer_classlink_toc                 C      t |trtdd |D sJ nt|tsJ dddhd}t |tr/| j||fi | n| j||fddi| ||f| j|< dS )	ad  Adds arguments from an optimizer class to a nested key of the parser.

        Args:
            optimizer_class: Any subclass of :class:`torch.optim.Optimizer`. Use tuple to allow subclasses.
            nested_key: Name of the nested namespace to store arguments.
            link_to: Dot notation of a parser key to set arguments or AUTOMATIC.

        c                 s       | ]}t |tV  qd S r-   )rO   r   .0or3   r3   r4   	<genexpr>       z=LightningArgumentParser.add_optimizer_args.<locals>.<genexpr>FparamsrJ   rI   skiprK   TN)rM   tupleallrO   r   rQ   rR   rC   )r0   rU   rF   rV   r+   r3   r3   r4   add_optimizer_args   s   

z*LightningArgumentParser.add_optimizer_argslr_schedulerlr_scheduler_classc                 C   rW   )	a  Adds arguments from a learning rate scheduler class to a nested key of the parser.

        Args:
            lr_scheduler_class: Any subclass of ``torch.optim.lr_scheduler.{_LRScheduler, ReduceLROnPlateau}``. Use
                tuple to allow subclasses.
            nested_key: Name of the nested namespace to store arguments.
            link_to: Dot notation of a parser key to set arguments or AUTOMATIC.

        c                 s   rX   r-   )rO   LRSchedulerTypeTuplerY   r3   r3   r4   r\      r]   z@LightningArgumentParser.add_lr_scheduler_args.<locals>.<genexpr>Fr(   r_   rK   TN)rM   ra   rb   rO   rf   rQ   rR   rD   )r0   re   rF   rV   r+   r3   r3   r4   add_lr_scheduler_args   s   

z-LightningArgumentParser.add_lr_scheduler_args)FT)r5   r6   r7   __doc__r   r8   boolr/   r   r   r   r   r   r   r   r	   rS   r   r   rc   rf   LRSchedulerTyperg   r9   r3   r3   r1   r4   r:   M   s|    %	

1
r:   c                   @   sx   e Zd ZdZ				ddedededed	ed
eddfddZe	de
dededdfddZde
dededdfddZdS )SaveConfigCallbackaf  Saves a LightningCLI config to the log_dir when training starts.

    Args:
        parser: The parser object used to parse the configuration.
        config: The parsed configuration that will be saved.
        config_filename: Filename for the config file.
        overwrite: Whether to overwrite an existing config file.
        multifile: When input is multiple config files, saved config preserves this structure.
        save_to_log_dir: Whether to save the config to the log_dir.

    Raises:
        RuntimeError: If the config file already exists in the directory to avoid overwriting a previous run

    config.yamlFTparserconfigconfig_filename	overwrite	multifilesave_to_log_dirr,   Nc                 C   sJ   || _ || _|| _|| _|| _|| _d| _|s!td| ts#t	dd S d S )NFsave_configz`save_to_log_dir=False` only makes sense when subclassing SaveConfigCallback to implement `save_config` and it is desired to disable the standard behavior of saving to log_dir.)
rm   rn   ro   rp   rq   rr   already_savedr   rk   
ValueError)r0   rm   rn   ro   rp   rq   rr   r3   r3   r4   r/      s   	zSaveConfigCallback.__init__trainer	pl_modulestagec                 C   s   | j rd S | jrV|j}|d usJ tj|| j}t|}| js>|j	r(|
|nd}|j|}|r>t| jj d| d|j	rV|j|dd | jj| j|d| j| jd |j	rc| ||| d| _ |j| j | _ d S )NFz
 expected a   to NOT exist. Aborting to avoid overwriting results of a previous run. You can delete the previous config file, set `LightningCLI(save_config_callback=None)` to disable config saving, or set `LightningCLI(save_config_kwargs={"overwrite": True})` to overwrite the config file.T)exist_ok)	skip_nonerp   rq   )rt   rr   log_dirospathjoinro   r   rp   is_global_zeroisfilestrategy	broadcastRuntimeErrorr2   r5   makedirsrm   savern   rq   rs   )r0   rv   rw   rx   r{   config_pathfsfile_existsr3   r3   r4   setup   s.   zSaveConfigCallback.setupc                 C      dS )a   Implement to save the config in some other place additional to the standard log_dir.

        Example:
            def save_config(self, trainer, pl_module, stage):
                if isinstance(trainer.logger, Logger):
                    config = self.parser.dump(self.config, skip_none=False)  # Required for proper reproducibility
                    trainer.logger.log_hyperparams({"config": config})

        Note:
            This method is only called on rank zero. This allows to implement a custom save config without having to
            worry about ranks or race conditions. Since it only runs on rank zero, any collective call will make the
            process hang waiting for a broadcast. If you need to make collective calls, implement the setup method
            instead.

        Nr3   )r0   rv   rw   rx   r3   r3   r4   rs         zSaveConfigCallback.save_config)rl   FFT)r5   r6   r7   rh   r:   r!   r8   ri   r/   r   r   r   r   rs   r3   r3   r3   r4   rk      s0    
'rk   c                   @   s(  e Zd ZdZddededdddddddfdeeee	 e
de	f f  deeee e
def f  deee  d	eeeef  d
eee e
def f deeeef  deeef deeeeef eeeeef f f  dedededededdfddZdeeef deeeef eeef f fddZdedefddZdedeeef deeef ddfddZd eddfd!d"Zd eddfd#d$Zd eddfd%d&Zd eddfd'd(Zedeeee f fd)d*Zd ededdfd+d,Zd-ed.ededefd/d0Z ed eddfd1d2Z!d ededdfd3d4Z"dTd5d6Z#dTd7d8Z$dTd9d:Z%dedefd;d<Z&d=eeef d>e'e( defd?d@Z)d.ee defdAdBZ*e	dUdCe	dDe+dEee, defdFdGZ-d.ee ddfdHdIZ.dUd=e/dJedKee defdLdMZ0d.eddfdNdOZ1d.edeeef fdPdQZ2dTdRdSZ3dS )VLightningCLIzIImplementation of a configurable command line tool for pytorch-lightning.NTFmodel_class.datamodule_classsave_config_callbacksave_config_kwargstrainer_classtrainer_defaultsseed_everything_defaultparser_kwargssubclass_mode_modelsubclass_mode_datar*   runauto_configure_optimizersr,   c                 C   s   || _ |pi | _|| _|pi | _|| _|pi | _|| _|| _|p!t| _	|du p(|	| _
|| _|p0t| _|du p7|
| _| | j\}}| ||| | | j| |rV| jd nd| _|   |   |   |   | jdurv| | j dS dS )a  Receives as input pytorch-lightning classes (or callables which return pytorch-lightning classes), which are
        called / instantiated using a parsed configuration file and / or command line args.

        Parsing of configuration from environment variables can be enabled by setting ``parser_kwargs={"default_env":
        True}``. A full configuration yaml would be parsed from ``PL_CONFIG`` if set. Individual settings are so parsed
        from variables named for example ``PL_TRAINER__MAX_EPOCHS``.

        For more info, read :ref:`the CLI docs <lightning-cli>`.

        Args:
            model_class: An optional :class:`~lightning.pytorch.core.LightningModule` class to train on or a
                callable which returns a :class:`~lightning.pytorch.core.LightningModule` instance when
                called. If ``None``, you can pass a registered model with ``--model=MyModel``.
            datamodule_class: An optional :class:`~lightning.pytorch.core.datamodule.LightningDataModule` class or a
                callable which returns a :class:`~lightning.pytorch.core.datamodule.LightningDataModule` instance when
                called. If ``None``, you can pass a registered datamodule with ``--data=MyDataModule``.
            save_config_callback: A callback class to save the config.
            save_config_kwargs: Parameters that will be used to instantiate the save_config_callback.
            trainer_class: An optional subclass of the :class:`~lightning.pytorch.trainer.trainer.Trainer` class or a
                callable which returns a :class:`~lightning.pytorch.trainer.trainer.Trainer` instance when called.
            trainer_defaults: Set to override Trainer defaults or add persistent callbacks. The callbacks added through
                this argument will not be configurable from a configuration file and will always be present for
                this particular CLI. Alternatively, configurable callbacks can be added as explained in
                :ref:`the CLI docs <lightning-cli>`.
            seed_everything_default: Number for the :func:`~lightning.fabric.utilities.seed.seed_everything`
                seed value. Set to True to automatically choose a seed value.
                Setting it to False will avoid calling ``seed_everything``.
            parser_kwargs: Additional arguments to instantiate each ``LightningArgumentParser``.
            subclass_mode_model: Whether model can be any `subclass
                <https://jsonargparse.readthedocs.io/en/stable/#class-type-and-sub-classes>`_
                of the given class.
            subclass_mode_data: Whether datamodule can be any `subclass
                <https://jsonargparse.readthedocs.io/en/stable/#class-type-and-sub-classes>`_
                of the given class.
            args: Arguments to parse. If ``None`` the arguments are taken from ``sys.argv``. Command line style
                arguments can be given in a ``list``. Alternatively, structured config options can be given in a
                ``dict`` or ``jsonargparse.Namespace``.
            run: Whether subcommands should be added to run a :class:`~lightning.pytorch.trainer.trainer.Trainer`
                method. If set to ``False``, the trainer and model classes will be instantiated only.

        N
subcommand)r   r   r   r   r   r   r   r   r   _model_classr   r   r   _datamodule_classr   _setup_parser_kwargssetup_parserparse_argumentsrm   rn   r   	_set_seed_add_instantiatorsbefore_instantiate_classesinstantiate_classes_run_subcommand)r0   r   r   r   r   r   r   r   r   r   r   r*   r   r   main_kwargssubparser_kwargsr3   r3   r4   r/   2  s0   9





zLightningCLI.__init__c                    s@   |      fdd| D } fdd| D }||fS )Nc                    s   i | ]\}}| vr||qS r3   r3   rZ   kvsubcommand_namesr3   r4   
<dictcomp>      z5LightningCLI._setup_parser_kwargs.<locals>.<dictcomp>c                    s   i | ]\}}| v r||qS r3   r3   r   r   r3   r4   r     r   )subcommandskeysitems)r0   r   r   r   r3   r   r4   r     s   z!LightningCLI._setup_parser_kwargsr+   c                 K   s:   | ddtj g tdi |}|jddtdd |S )	z-Method that instantiates the argument parser.dump_headerzlightning.pytorch==z-cz--configz4Path to a configuration file in json or yaml format.)actionhelpNr3   )
setdefaultpl__version__r:   add_argumentr   )r0   r+   rm   r3   r3   r4   init_parser  s   zLightningCLI.init_parseradd_subcommandsr   r   c                 C   sD   | j di || _|ri | _| j| jfi | dS | | j dS )z<Initialize and setup the parser, subcommands, and arguments.Nr3   )r   rm   _subcommand_method_arguments_add_subcommands_add_arguments)r0   r   r   r   r3   r3   r4   r     s
   zLightningCLI.setup_parserrm   c                 C   s    |j dtttf | jdd dS )z%Adds default arguments to the parser.z--seed_everythingzsSet to an int to run seed_everything with this value before classes instantiation.Set to True to use a random seed.)rN   defaultr   N)r   r   ri   intr   r0   rm   r3   r3   r4   add_default_arguments_to_parser  s   

z,LightningCLI.add_default_arguments_to_parserc                 C   s|   | | jd dd | j D }|| |j | jd| jd | jdur1|j | jd| j	d dS |j | jd| j	dd	 dS )
z3Adds arguments from the core classes to the parser.rv   c                 S   s"   i | ]\}}|d krd| |qS )	callbacksztrainer.r3   r   r3   r3   r4   r     s   " z=LightningCLI.add_core_arguments_to_parser.<locals>.<dictcomp>model)rG   NdataF)rG   rH   )
rS   r   r   r   set_defaultsr   r   r   r   r   )r0   rm   r   r3   r3   r4   add_core_arguments_to_parser  s   


z)LightningCLI.add_core_arguments_to_parserc                 C   sT   |  | | | | | | jr#|js|tf |js#|t	 | 
| d S r-   )r   r   add_arguments_to_parserr   rC   rc   r   rD   rg   rf   !link_optimizers_and_lr_schedulersr   r3   r3   r4   r     s   



zLightningCLI._add_argumentsc                 C   r   )zImplement to add extra arguments to the parser or link arguments.

        Args:
            parser: The parser object to which arguments can be added

        Nr3   r   r3   r3   r4   r     r   z$LightningCLI.add_arguments_to_parserc                   C   s   h dh dh dh ddS )zDDefines the list of available subcommands and the arguments to skip.>   r   
datamoduleval_dataloaderstrain_dataloaders>   r   r   dataloaders)fitvalidatetestpredictr3   r3   r3   r3   r4   r     s
   zLightningCLI.subcommandsc           
      K   s   i | _ | }t| jtr| jnt| j}|  D ].}t||}t|}|	|i }|
d| | j||fi |}	|	| j |< |j||	|d qdS )z%Adds subcommands to the input parser.r=   )r   N)_subcommand_parsersr   rM   r   rN   r"   r   getattr_get_short_descriptiongetr   _prepare_subcommand_parseradd_subcommand)
r0   rm   r+   parser_subcommandsr   r   fnr=   r   subcommand_parserr3   r3   r4   r     s   

zLightningCLI._add_subcommandsklassr   c                 K   sH   | j di |}| | t|  | }|j|||d}|| j|< |S )N)r`   r3   )r   r   setr   add_method_argumentsr   )r0   r   r   r+   rm   r`   addedr3   r3   r4   r     s   

z'LightningCLI._prepare_subcommand_parserc                 C   sd   i | j | j}| D ]#\}\}}|dkrqt|tr#| || qt|}| j|||d qdS )z`Creates argument links for optimizers and learning rate schedulers that specified a ``link_to``.rT   )
compute_fnN)rC   rD   r   rM   ra   link_arguments_add_class_path_generator)rm   optimizers_and_lr_schedulerskey
class_typerV   add_class_pathr3   r3   r4   r     s   
z.LightningCLI.link_optimizers_and_lr_schedulersc                 C   sd   |durt tjdkrtdtjdd  d| d t|ttfr*||| _dS |	|| _dS )z?Parses command line arguments and stores it in ``self.config``.N   zLightningCLI's args parameter is intended to run from within Python like if it were from the command line. To prevent mistakes it is not recommended to provide both args and command line arguments, got: sys.argv[1:]=z, args=.)
lensysargvr   rM   dictr!   parse_objectrn   
parse_args)r0   rm   r*   r3   r3   r4   r     s   zLightningCLI.parse_argumentsc                 C   s~   t | jj| jddd| _d| jv r| j| jj | _| jjt| ddt	| j
| jd | jjt| ddt	| j| jd d S )NF)skip_link_targetsrz   r   r   clir   )
subclassesr   )yaml	safe_loadrm   dumprn   config_dumpr   add_instantiator_InstantiatorFn_get_module_typer   r   r   r   r0   r3   r3   r4   r     s   



zLightningCLI._add_instantiatorsc                 C   r   )z<Implement to run some code before instantiating the classes.Nr3   r   r3   r3   r4   r   (  r   z'LightningCLI.before_instantiate_classesc                 C   sJ   | j | j| _| | jd| _| | jd| _| | j | 	 | _
dS )z3Instantiates the classes and sets their attributes.r   r   N)rm   r   rn   config_init_getr   r   )_add_configure_optimizers_method_to_modelr   instantiate_trainerrv   r   r3   r3   r4   r   +  s
   z LightningCLI.instantiate_classesc                    sB    fdd   jjD }i  j jdi d|} ||S )zdInstantiates the trainer.

        Args:
            kwargs: Any custom trainer arguments.

        c                    s   g | ]	}   j|qS r3   )r   r   rZ   cr   r3   r4   
<listcomp>:  s    z4LightningCLI.instantiate_trainer.<locals>.<listcomp>rv   )r   )_parserr   rB   r   r   _instantiate_trainer)r0   r+   extra_callbackstrainer_configr3   r   r4   r   3  s   z LightningCLI.instantiate_trainerrn   r   c                 C   s   d}||v ri|| d u rg ||< nt || ts|| g||< || | || jv r@| j| }||  t |tr;|n|g7  < | jrh|ddsh| j| | j| jt	| j| jfi | j
}|| | ntd| jj d| d | jdi |S )Nr   fast_dev_runFzThe `z` class does not expose the `z(` argument so they will not be included.r3   )rM   listextendr   r   r   r   r   rn   r8   r   rP   r   r   r7   )r0   rn   r   r   valueconfig_callbackr3   r3   r4   r   >  s.   


 
z!LightningCLI._instantiate_trainerc                 C   s   |d u r| j S | j| S r-   )rm   r   r0   r   r3   r3   r4   r   W  s   
zLightningCLI._parserlightning_moduler(   rd   c                 C   s4   |du r|S t |tr|||jddS |g|gfS )a  Override to customize the :meth:`~lightning.pytorch.core.LightningModule.configure_optimizers` method.

        Args:
            lightning_module: A reference to the model.
            optimizer: The optimizer.
            lr_scheduler: The learning rate scheduler (if used).

        N)	schedulerr)   r(   rd   )rM   r'   r)   )r  r(   rd   r3   r3   r4   configure_optimizers]  s   

z!LightningCLI.configure_optimizersc                 C   s  | j sdS | |}dttttdf f dtttttttdf f tf f dtt fdd}|t|j	}|t
|j}t|dkrCdS t|d	ksOt|d	kr^td
| jj d||  d|j	|d  d }| | j|d }t|tszt||}|s~dS d}|r|j|d  d }	| | j|d }t|	tst|	|}td| jrtd
| jjj d| jj d t| j |}
|rt|
|nd}t| j|
|d}t|| j t|| j| j_dS )zOverrides the model's :meth:`~lightning.pytorch.core.LightningModule.configure_optimizers` method if a
        single optimizer and optionally a scheduler argument groups are added to the parser as 'AUTOMATIC'.Nr   .registerr,   c                    sV   g }|  D ]"\}\}}t|ts|f}|dkr(t fdd|D r(|| q|S )NrT   c                 3   s    | ]}t | V  qd S r-   )rO   r   r   r3   r4   r\     r]   z`LightningCLI._add_configure_optimizers_method_to_model.<locals>.get_automatic.<locals>.<genexpr>)r   rM   ra   anyrP   )r   r  	automaticr   
base_classrV   r3   r  r4   get_automaticz  s   

zMLightningCLI._add_configure_optimizers_method_to_model.<locals>.get_automaticr   r   `z{.add_configure_optimizers_method_to_model` expects at most one optimizer and one lr_scheduler to be 'AUTOMATIC', but found z. In this case the user is expected to link the argument groups and implement `configure_optimizers`, see https://lightning.ai/docs/pytorch/stable/common/lightning_cli.html#optimizers-and-learning-rate-schedulersr  z..configure_optimizers` will be overridden by `z.configure_optimizers`.r
  )r   r   r   r   r   r   r8   r	   r   rC   rf   rD   r   r   r2   r5   r   r   rM   ra   _global_add_class_pathr   r   r   instantiate_class
parametersr   r  r   r   )r0   r   rm   r  
optimizerslr_schedulersrU   optimizer_initlr_scheduler_initre   r(   rd   r   r3   r3   r4   r   r  sV   
"




z6LightningCLI._add_configure_optimizers_method_to_modelr   r   c                 C   s   | t| j| ||S )zAUtility to get a config value which might be inside a subcommand.)r   r8   r   )r0   rn   r   r   r3   r3   r4   r     s   zLightningCLI._getc                 C   sx   t | d| d}t|r|  t | j|}t | ||}| |}|di | t | d| d}t|r:|  dS dS )zRun the chosen subcommand.before_Nafter_r3   )r   rL   rv   _prepare_subcommand_kwargs)r0   r   	before_fnr   r   	fn_kwargsafter_fnr3   r3   r4   r     s   

zLightningCLI._run_subcommandc                    s@    fdd j   D } j|d<  jdur j|d< |S )z@Prepares the keyword arguments to pass to the subcommand to run.c                    s$   i | ]\}}| j  v r||qS r3   )r   r   r  r3   r4   r     s    z;LightningCLI._prepare_subcommand_kwargs.<locals>.<dictcomp>r   Nr   )r   r   r   r   )r0   r   r  r3   r  r4   r    s   


z'LightningCLI._prepare_subcommand_kwargsc                 C   sb   |  | jd}|du rdS |du rtdd}nt|dd}| jr*|| j| j d< dS || jd< dS )zSets the seed.r   FNT)workers)r   rn   r   r   )r0   config_seedr3   r3   r4   r     s   zLightningCLI._set_seed)r,   Nr-   )4r5   r6   r7   rh   rk   r   r
   r   r   r   r   r   r   r8   r   ri   r   ArgsTyper/   r   r   r:   r   r   r   r   r   r   staticmethodr   r   r   r   r   r   r   r   r   r   r	   r   r   r   r   LRSchedulerTypeUnionr  r   r!   r   r   r  r   r3   r3   r3   r4   r   /  s    

&	

2Z	


	



" >
r   r   r,   c                 C   s   | j d | j S )Nr   )r6   r5   r  r3   r3   r4   _class_path_from_class  s   r%  	init_argsc                 C   s$   t |tr	| }t| |pi dS )N)
class_pathr&  )rM   r!   as_dictr%  )r   r&  r3   r3   r4   r    s   
r  c                    s"   dt dtttf f fdd}|S )Nr&  r,   c                    s
   t  | S r-   )r  )r&  r  r3   r4   r     s   
z1_add_class_path_generator.<locals>.add_class_path)r!   r   r8   r   )r   r   r3   r  r4   r     s   r   r*   .initc                 C   sV   | di }t| ts| f} |d dd\}}t||gd}t||}|| i |S )zInstantiates a class with the given args and init.

    Args:
        args: Positional arguments required for instantiation.
        init: Dict of the form {"class_path":...,"init_args":...}.

    Returns:
        The instantiated class object.

    r&  r'  r   r   )fromlist)r   rM   ra   rsplit
__import__r   )r*   r)  r+   class_module
class_namemodule
args_classr3   r3   r4   r    s   

r  	componentc              
   C   sd   | j d u rd S z
t| j }|jW S  ttjfy1 } ztd|  d|  W Y d }~d S d }~ww )NzFailed parsing docstring for z: )rh   docstring_parserparseshort_descriptionru   
ParseErrorr   )r1  	docstringexr3   r3   r4   r     s   
"r   r  c                 C   s"   t | rt| tst| jS | S r-   )rL   rM   rN   inspect	signaturereturn_annotation)r  r3   r3   r4   r     s   r   c                   @   s@   e Zd ZdededdfddZdee ded	edefd
dZ	dS )r   r   r   r,   Nc                 C   s   || _ || _d S r-   r   )r0   r   r   r3   r3   r4   r/     s   
z_InstantiatorFn.__init__r   r*   r+   c                 O   s|   | j j| ji }d|v rd|d i|di |di }t|dd ||i |W  d    S 1 s7w   Y  d S )Nr'  _class_pathr&  dict_kwargsz(lightning.pytorch.cli.instantiate_module)hparamsinstantiator)r   r   r   r   r   )r0   r   r*   r+   r=  r3   r3   r4   __call__  s   

$z_InstantiatorFn.__call__)
r5   r6   r7   r   r8   r/   r   r&   r   r?  r3   r3   r3   r4   r     s    "r   rn   c                 C   sn   t dd}d|v r |j| ddd |d dd | D d}n|j| ddd |d|i}||}|jS )	NF)exit_on_errorr;  r/  )rI   c                 S   s   i | ]\}}|d kr||qS )r;  r3   r   r3   r3   r4   r   1  r   z&instantiate_module.<locals>.<dictcomp>)r'  r<  )r    rQ   r   rR   r   r   r/  )r   rn   rm   cfgr)  r3   r3   r4   instantiate_module+  s   

rB  r-   )Tr8  r|   r   	functoolsr   r   typesr   typingr   r   r   r   r	   r
   r   r   r   r   r   torchr    lightning_utilities.core.importsr   "lightning_utilities.core.rank_zeror   torch.optimr   torch.optim.lr_schedulerr   typing_extensionsr   lightning.pytorchpytorchr   #lightning.fabric.utilities.cloud_ior   r   r   r   r   r   +lightning.pytorch.core.mixins.hparams_mixinr   &lightning.pytorch.utilities.exceptionsr   )lightning.pytorch.utilities.model_helpersr   %lightning.pytorch.utilities.rank_zeror   r@   r2  jsonargparser   r    r!   r"   r#   r$   objectlocalsr&   optimrd   r'   rf   r$  rj   r8   r"  OptimizerCallableLRSchedulerCallabler:   rk   r   r%  r  r   r  r   rN   r   r   rB  r3   r3   r3   r4   <module>   st   4 	

 a   1

$.
&