a
    dR                     @   s  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 d dlZd dlm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 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)m*Z* edZ+e+r6d dl,Z,d dl-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3 e2e e3dd ne4e5 d< e4e5 d< G dd dej6j7j8Z8ee8fZ9eee8f Z:eee ee8 f Z;eeee< e
e<ef e1f  Z=e	egef Z>e	egeee8f f Z?G dd de/Z@G dd deZAG dd dZBee<dddZCd+eeee1e
e<ef f  e
e<ef dd d!ZDee	e1ge
e<ef f dd"d#ZEeeeed$f f e
e<ef ed%d&d'ZFe4ee< d(d)d*ZGdS ),    N)partialupdate_wrapper)
MethodType)
AnyCallableDictIterableListOptionalSetTupleTypeUnion)RequirementCache)_warn)	Optimizer)get_filesystem)_TORCH_LRSCHEDULER)CallbackLightningDataModuleLightningModuleseed_everythingTrainer)MisconfigurationException)is_overridden)rank_zero_deprecationrank_zero_warnz jsonargparse[signatures]>=4.17.0)ActionConfigFileArgumentParserclass_from_function	Namespace"register_unresolvable_import_pathsset_config_read_modeT)Zfsspec_enabledr   r    c                       s*   e Zd Zeeeedd fddZ  ZS )ReduceLROnPlateauN)	optimizermonitorargskwargsreturnc                    s$   t  j|g|R i | || _d S N)super__init__r%   )selfr$   r%   r&   r'   	__class__ ^/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/pytorch_lightning/cli.pyr+   6   s    zReduceLROnPlateau.__init__)__name__
__module____qualname__r   strr   r+   __classcell__r/   r/   r-   r0   r#   5   s   r#   c                	       s   e Zd ZdZddddeeeeedd fdd	Zdee	dee
eeef f ee
 ee ee ee f eeeee dddZefddfeee eee df f eeddddZeddfeeeedf f eeddddZ  ZS )LightningArgumentParserzAExtension of jsonargparse's ArgumentParser for pytorch-lightning.z+pytorch-lightning trainer command line toolZPLFdescription
env_prefixdefault_envN)r&   r8   r9   r:   r'   r(   c                   sB   t stt  d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.
        z2. Try `pip install -U 'jsonargparse[signatures]'`.r7   N)"_JSONARGPARSE_SIGNATURES_AVAILABLEModuleNotFoundErrorr*   r+   callback_keys_optimizers_lr_schedulers)r,   r8   r9   r:   r&   r'   r-   r/   r0   r+   J   s    z LightningArgumentParser.__init__T.)lightning_class
nested_keysubclass_moderequiredr(   c                 C   s   t |rt|tst|}t|tr~t|ttttfr~t|trL| j	
| |rb| j||d|dS | j||dt|t ddS td| ddS )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_untypedrC   T)rD   instantiatesub_configszCannot add arguments from: zt. You should provide either a callable or a subclass of: Trainer, LightningModule, LightningDataModule, or Callback.N)callable
isinstancetyper   
issubclassr   r   r   r   r=   appendadd_subclass_argumentsadd_class_argumentsr   )r,   r@   rA   rB   rC   r/   r/   r0   add_lightning_class_argsf   s&    


z0LightningArgumentParser.add_lightning_class_argsr$   	AUTOMATIC)optimizer_classrA   link_tor(   c                 C   s   t |tr"tdd |D s0J nt|ts0J dddhd}t |tr^| j||fi | n| j||fddi| ||f| j|< dS )	ac  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   s   | ]}t |tV  qd S r)   )rJ   r   .0or/   r/   r0   	<genexpr>       z=LightningArgumentParser.add_optimizer_args.<locals>.<genexpr>FparamsrE   rD   skiprF   TN)rH   tupleallrJ   r   rL   rM   r>   )r,   rP   rA   rQ   r'   r/   r/   r0   add_optimizer_args   s    

z*LightningArgumentParser.add_optimizer_argslr_scheduler)lr_scheduler_classrA   rQ   r(   c                 C   s   t |tr"tdd |D s0J nt|ts0J dddhd}t |tr^| j||fi | n| j||fddi| ||f| j|< dS )	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   s   | ]}t |tV  qd S r)   )rJ   LRSchedulerTypeTuplerR   r/   r/   r0   rU      rV   z@LightningArgumentParser.add_lr_scheduler_args.<locals>.<genexpr>Fr$   rX   rF   TN)rH   rZ   r[   rJ   r_   rL   rM   r?   )r,   r^   rA   rQ   r'   r/   r/   r0   add_lr_scheduler_args   s    

z-LightningArgumentParser.add_lr_scheduler_args)FT)r1   r2   r3   __doc__r   r4   boolr+   r   r   r   r   r   r   r   r	   rN   r   r   r\   r_   LRSchedulerTyper`   r5   r/   r/   r-   r0   r6   G   s\   &  0r6   c                   @   s>   e Zd ZdZdeeeeeddddZe	e
eddd	d
ZdS )SaveConfigCallbacka!  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.

    Raises:
        RuntimeError: If the config file already exists in the directory to avoid overwriting a previous run
    config.yamlFN)parserconfigconfig_filename	overwrite	multifiler(   c                 C   s(   || _ || _|| _|| _|| _d| _d S )NF)rf   rg   rh   ri   rj   already_saved)r,   rf   rg   rh   ri   rj   r/   r/   r0   r+      s    zSaveConfigCallback.__init__)trainer	pl_modulestager(   c                 C   s   | j r
d S |j}|d usJ tj|| j}t|}| jsv|jrJ|	|nd}|j
|}|rvt| jj d| d|jr|j|dd | jj| j|d| j| jd 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_overwrite=True)` to overwrite the config file.T)exist_ok)Z	skip_noneri   rj   )rk   log_dirospathjoinrh   r   ri   Zis_global_zeroisfileZstrategy	broadcastRuntimeErrorr.   r1   makedirsrf   saverg   rj   )r,   rl   rm   rn   rp   Zconfig_pathfsZfile_existsr/   r/   r0   setup   s(    zSaveConfigCallback.setup)re   FF)r1   r2   r3   ra   r6   r    r4   rb   r+   r   r   rz   r/   r/   r/   r0   rd      s      rd   c                   @   s  e Zd ZdZddededdddddddfeeee	 e
de	f f  eeee e
def f  eee  eeeef  eee e
def f eeeef  eeef eeeeef eeeeef f f  eeeeeeddddZedd	d
dZeeef eeeef eeef f dddZeed	ddZeeeef eeef ddddZeddddZeddddZeddddZeddddZeeeee f dddZ eedd d!d"Z!eeeed#d$d%Z"eeddd&d'Z#eedd(d)d*Z$ddd+d,Z%ddd-d.Z&eed	d/d0Z'eeef e(e) ed1d2d3Z*ee ed4d5d6Z+edEe	e,ee- ed7d8d9Z.ee dd4d:d;Z/dFe0eee ed<d=d>Z1edd4d?d@Z2eeeef d4dAdBZ3dddCdDZ4dS )G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'   r(   c                 K   s   || _ |pi | _|| _|pi | _|| _|p,i | _|| _| | || _|pLt	| _
|du pZ|	| _|| _|pjt| _|du px|
| _| | j\}}| ||| | | j| |r| jd nd| _|   |   |   | jdur| | j dS )a9  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>`.

        .. warning:: ``LightningCLI`` is in beta and subject to change.

        Args:
            model_class: An optional :class:`~pytorch_lightning.core.module.LightningModule` class to train on or a
                callable which returns a :class:`~pytorch_lightning.core.module.LightningModule` instance when
                called. If ``None``, you can pass a registered model with ``--model=MyModel``.
            datamodule_class: An optional :class:`~pytorch_lightning.core.datamodule.LightningDataModule` class or a
                callable which returns a :class:`~pytorch_lightning.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:`~pytorch_lightning.trainer.trainer.Trainer` class or a
                callable which returns a :class:`~pytorch_lightning.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:`~pytorch_lightning.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   _handle_deprecated_paramsr|   r   _model_classr   r}   r   _datamodule_classr   _setup_parser_kwargssetup_parserparse_argumentsrf   rg   r   	_set_seedbefore_instantiate_classesinstantiate_classes_run_subcommand)r,   r|   r}   r~   r   r   r   r   r   r   r   r&   r   r   r'   main_kwargssubparser_kwargsr/   r/   r0   r+     s.    ;






zLightningCLI.__init__)r'   r(   c                 C   s   |  g d@ D ]B}||}|dddd}|| j|< td|d| d q|  g d	@ D ]:}||}|d
d}|| j|< td|d| d qd|rtd| d S )N)Zsave_config_filenameZsave_config_overwriteZsave_config_multifileZsave_config_ filenamerh   zLightningCLI's za init parameter is deprecated from v1.8 and will be removed in v2.0.0. Use `save_config_kwargs={'z': ...}` instead.)r8   r9   	env_parser   r:   zZ init parameter is deprecated from v1.9 and will be removed in v2.0. Use `parser_kwargs={'zUnexpected keyword parameters: )keyspopreplacer   r   r   
ValueError)r,   r'   namevaluekeyr/   r/   r0   r   h  s(    



z&LightningCLI._handle_deprecated_params)r   r(   c                    s@   |      fdd| D } fdd| D }||fS )Nc                    s   i | ]\}}| vr||qS r/   r/   rS   kvZsubcommand_namesr/   r0   
<dictcomp>  rV   z5LightningCLI._setup_parser_kwargs.<locals>.<dictcomp>c                    s   i | ]\}}| v r||qS r/   r/   r   r   r/   r0   r     rV   )subcommandsr   items)r,   r   r   r   r/   r   r0   r   ~  s    z!LightningCLI._setup_parser_kwargsc                 K   s:   | ddtj g tf i |}|jddtdd |S )z-Method that instantiates the argument parser.Zdump_headerzpytorch_lightning==z-cz--configz4Path to a configuration file in json or yaml format.)actionhelp)
setdefaultpl__version__r6   add_argumentr   )r,   r'   rf   r/   r/   r0   init_parser  s    zLightningCLI.init_parser)add_subcommandsr   r   r(   c                 C   sB   | j f i || _|r2i | _| j| jfi | n| | j dS )z<Initialize and setup the parser, subcommands, and arguments.N)r   rf   _subcommand_method_arguments_add_subcommands_add_arguments)r,   r   r   r   r/   r/   r0   r     s
    zLightningCLI.setup_parser)rf   r(   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.)rI   defaultr   N)r   r   rb   intr   r,   rf   r/   r/   r0   add_default_arguments_to_parser  s    
z,LightningCLI.add_default_arguments_to_parserc                 C   sz   | | jd dd | j D }|| |j | jd| jd | jdur`|j | jd| j	d n|j | jd| j	dd	 dS )
z3Adds arguments from the core classes to the parser.rl   c                 S   s"   i | ]\}}|d krd| |qS )	callbacksztrainer.r/   r   r/   r/   r0   r     rV   z=LightningCLI.add_core_arguments_to_parser.<locals>.<dictcomp>model)rB   NdataF)rB   rC   )
rN   r   r   r   set_defaultsr   r   r}   r   r   )r,   rf   r   r/   r/   r0   add_core_arguments_to_parser  s    

z)LightningCLI.add_core_arguments_to_parserc                 C   sT   |  | | | | | | jrF|js6|tf |jsF|t	 | 
| d S r)   )r   r   add_arguments_to_parserr   r>   r\   r   r?   r`   r_   !link_optimizers_and_lr_schedulersr   r/   r/   r0   r     s    



zLightningCLI._add_argumentsc                 C   s   dS )zImplement to add extra arguments to the parser or link arguments.

        Args:
            parser: The parser object to which arguments can be added
        Nr/   r   r/   r/   r0   r     s    z$LightningCLI.add_arguments_to_parser)r(   c                   C   s$   h dh dh dh dh ddS )zDDefines the list of available subcommands and the arguments to skip.>   
datamoduleZval_dataloadersr   Ztrain_dataloaders>   r   r   Zdataloaders)ZfitvalidatetestZpredictZtuner/   r/   r/   r/   r0   r     s    zLightningCLI.subcommands)rf   r'   r(   c           
      K   s   i | _ | }t| jtr | jnt| j}|  D ]\}t||}t|}|	|i }|
d| | j||fi |}	|	| j |< |j||	|d q2dS )z%Adds subcommands to the input parser.r8   )r   N)_subcommand_parsersr   rH   r   rI   r   r   getattr_get_short_descriptiongetr   _prepare_subcommand_parserZadd_subcommand)
r,   rf   r'   Zparser_subcommandsr   r   fnr8   r   Zsubcommand_parserr/   r/   r0   r     s    

zLightningCLI._add_subcommands)klassr   r'   r(   c                 K   sH   | j f i |}| | t|  | }|j|||d}|| j|< |S )N)rY   )r   r   setr   Zadd_method_argumentsr   )r,   r   r   r'   rf   rY   addedr/   r/   r0   r     s    

z'LightningCLI._prepare_subcommand_parserc                 C   sd   i | j | j}| D ]F\}\}}|dkr.qt|trF| || qt|}| j|||d qdS )z`Creates argument links for optimizers and learning rate schedulers that specified a ``link_to``.rO   )Z
compute_fnN)r>   r?   r   rH   rZ   Zlink_arguments_add_class_path_generator)rf   Zoptimizers_and_lr_schedulersr   
class_typerQ   add_class_pathr/   r/   r0   r     s    
z.LightningCLI.link_optimizers_and_lr_schedulers)rf   r&   r(   c                 C   sb   |dur6t tjdkr6tdtjdd  d| dt|ttfrR||| _n|	|| _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 allowed to provide both args and command line arguments, got: sys.argv[1:]=z, args=.)
lensysargvr   rH   dictr    parse_objectrg   
parse_args)r,   rf   r&   r/   r/   r0   r     s    zLightningCLI.parse_argumentsc                 C   s   dS )z<Implement to run some code before instantiating the classes.Nr/   r,   r/   r/   r0   r   
  s    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)rf   r   rg   config_init_getr   r   )_add_configure_optimizers_method_to_modelr   instantiate_trainerrl   r   r/   r/   r0   r     s
    z LightningCLI.instantiate_classesc                    sB    fdd   jjD }i  j jdi d|} ||S )zcInstantiates the trainer.

        Args:
            kwargs: Any custom trainer arguments.
        c                    s   g | ]}   j|qS r/   )r   r   rS   cr   r/   r0   
<listcomp>  rV   z4LightningCLI.instantiate_trainer.<locals>.<listcomp>rl   )r   )_parserr   r=   r   r   _instantiate_trainer)r,   r'   Zextra_callbacksZtrainer_configr/   r   r0   r     s    z LightningCLI.instantiate_trainer)rg   r   r(   c                 C   s   d}||v r|| d u r"g ||< nt || ts>|| g||< || | || jv r| j| }||  t |trv|n|g7  < | jr|dds| j| | j| jt	| j| jfi | j
}|| | ntd| jj d| d | jf i |S )Nr   Zfast_dev_runFzThe `z` class does not expose the `z(` argument so they will not be included.)rH   listextendr   r~   r   r   r   rg   r4   r   rK   r   r   r3   )r,   rg   r   r   r   Zconfig_callbackr/   r/   r0   r     s,    


 
z!LightningCLI._instantiate_trainer)r   r(   c                 C   s   |d u r| j S | j| S r)   )rf   r   r,   r   r/   r/   r0   r   8  s    zLightningCLI._parser)lightning_moduler$   r]   r(   c                 C   s4   |du r|S t |tr(|||jddS |g|gfS )a,  Override to customize the :meth:`~pytorch_lightning.core.module.LightningModule.configure_optimizers`
        method.

        Args:
            lightning_module: A reference to the model.
            optimizer: The optimizer.
            lr_scheduler: The learning rate scheduler (if used).
        N)Z	schedulerr%   r$   r]   )rH   r#   r%   )r   r$   r]   r/   r/   r0   configure_optimizers>  s    

z!LightningCLI.configure_optimizersc              	   C   s  | j s
dS | |}ttttdf f tttttttdf f tf f tt ddd}|t|j	}|t
|j}t|dkrdS t|dkst|dkrtd| jj d	||  d
|j	|d  d }| | j|d }t|tst||}|sdS d}|r<|j|d  d }	| | j|d }t|	ts<t|	|}td| jrjt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:`~pytorch_lightning.core.module.LightningModule.configure_optimizers` method
        if a single optimizer and optionally a scheduler argument groups are added to the parser as 'AUTOMATIC'.N.)r   registerr(   c                    sV   g }|  D ]D\}\}}t|ts(|f}|dkrt fdd|D r|| q|S )NrO   c                 3   s   | ]}t | V  qd S r)   )rJ   r   r   r/   r0   rU   b  rV   z`LightningCLI._add_configure_optimizers_method_to_model.<locals>.get_automatic.<locals>.<genexpr>)r   rH   rZ   anyrK   )r   r   Z	automaticr   Z
base_classrQ   r/   r   r0   get_automatic[  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://pytorch-lightning.readthedocs.io/en/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   r4   r	   r   r>   r_   r?   r   r   r.   r1   r   r   rH   rZ   _global_add_class_pathr   r   r   instantiate_class
parametersr   r   r   r   )r,   r   rf   r   Z
optimizersZlr_schedulersrP   Zoptimizer_initZlr_scheduler_initr^   r$   r]   r   r/   r/   r0   r   S  sN    
4


z6LightningCLI._add_configure_optimizers_method_to_model)rg   r   r   r(   c                 C   s   | t| j| ||S )zAUtility to get a config value which might be inside a subcommand.)r   r4   r   )r,   rg   r   r   r/   r/   r0   r     s    zLightningCLI._getc                 C   st   t | d| d}t|r |  t | j|}t | ||}| |}|f i | t | d| d}t|rp|  dS )zRun the chosen subcommand.Zbefore_NZafter_)r   rG   rl   _prepare_subcommand_kwargs)r,   r   Z	before_fnr   r   	fn_kwargsZafter_fnr/   r/   r0   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 r/   )r   r   r   r/   r0   r     s   z;LightningCLI._prepare_subcommand_kwargs.<locals>.<dictcomp>r   Nr   )r   r   r   r   )r,   r   r   r/   r   r0   r     s    


z'LightningCLI._prepare_subcommand_kwargsc                 C   sH   |  | jd}|du rdS |du r.tdd}nt|dd}|| jd< dS )zSets the seed.r   FNT)workers)r   rg   r   )r,   Zconfig_seedr/   r/   r0   r     s    zLightningCLI._set_seed)N)N)5r1   r2   r3   ra   rd   r   r
   r   r   r   r   r   r   r4   r   rb   r   ArgsTyper+   r   r   r   r   r6   r   r   r   r   r   r   staticmethodr   r   r   r   r   r   r   r   r   r	   r   r   r   r   LRSchedulerTypeUnionr   r   r    r   r   r   r   r/   r/   r/   r0   r{     s   

&]0



 
>
r{   )r   r(   c                 C   s   | j d | j S )Nr   )r2   r1   r   r/   r/   r0   _class_path_from_class  s    r   )r   	init_argsr(   c                 C   s$   t |tr| }t| |pi dS )N)
class_pathr   )rH   r    Zas_dictr   )r   r   r/   r/   r0   r     s    
r   c                    s    t tttf d fdd}|S )N)r   r(   c                    s
   t  | S r)   )r   )r   r   r/   r0   r     s    z1_add_class_path_generator.<locals>.add_class_path)r    r   r4   r   )r   r   r/   r   r0   r     s    r   .)r&   initr(   c                 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   rH   rZ   rsplit
__import__r   )r&   r   r'   Zclass_module
class_namemoduleZ
args_classr/   r/   r0   r     s    


r   )	componentr(   c              
   C   sf   | j d u rd S zt| j }|jW S  ttjfy` } z td|  d|  W Y d }~n
d }~0 0 d S )NzFailed parsing docstring for z: )ra   docstring_parserparseZshort_descriptionr   
ParseErrorr   )r   	docstringexr/   r/   r0   r     s    
r   )N)Hrq   r   	functoolsr   r   typesr   typingr   r   r   r   r	   r
   r   r   r   r   ZtorchZ lightning_utilities.core.importsr   Z"lightning_utilities.core.rank_zeror   Ztorch.optimr   Zpytorch_lightningr   Z#lightning_fabric.utilities.cloud_ior   Z lightning_fabric.utilities.typesr   r   r   r   r   r   Z&pytorch_lightning.utilities.exceptionsr   Z)pytorch_lightning.utilities.model_helpersr   Z%pytorch_lightning.utilities.rank_zeror   r   r;   r   Zjsonargparser   r   r   r    r!   r"   objectlocalsZoptimr]   r#   r_   r   rc   r4   r   ZOptimizerCallableZLRSchedulerCallabler6   rd   r{   r   r   r   r   r   r/   r/   r/   r0   <module>   sZ   0 	

B   6 
"*