a
    d                      @   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 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 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#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l.m/Z/m0Z0m1Z1 d dl2m3Z3m4Z4m5Z5m6Z6m7Z7 d dl8m9Z9m:Z: d dl;m<Z< d dl=m>Z>m?Z? d dl@mAZAmBZBmCZCmDZD d dlEmFZF d dlGmHZH d dlImJZJ d dlKmLZLmMZMmNZN G dd dZOePdddZQe
dddd ZRdS )!    N)contextmanagernullcontext)partial)Path)AnyCallablecastDict	GeneratorListMappingOptionaloverloadSequenceTupleUnion)apply_to_collection)is_overridden)rank_zero_warn)Tensor)	Optimizer)BatchSampler
DataLoaderDistributedSamplerRandomSamplerSequentialSampler)Logger)	Precision)Accelerator)
_Connector_PLUGIN_INPUT_PRECISION_INPUT)DeepSpeedStrategyFSDPStrategySingleDeviceStrategyStrategyXLAStrategy)_Sharded
TBroadcast)move_data_to_device)convert_tensors_to_scalarsconvert_to_tensors)_auto_add_worker_init_fn_replace_dunder_methods_update_dataloaderhas_iterable_dataset)DistributedSamplerWrapperseed_everything)PossibleUserWarning)_FabricDataLoader_FabricModule_FabricOptimizerc                   @   s  e Zd ZdZdeeeef  eeeef  eee	e
 ee
f  e
eeeee	e f  eee	e ef  eeee	e f  dd	ddZeedd	d
ZeedddZeejdddZee
dddZee
dddZee
dddZee
dddZeedddZee	e dddZeedddZeeedddZd d!eje eed"d#d$Z!dejee"d%d&d'Z#e ee$e%e$d(f f d)d*d+Z&d d d,e'eeee'e	e' f d-d.d/Z(de'eee'd0d1d2Z)dd3e*eee" edd4d5d6Z+e,e-d7 dd8d9Z.e/ejejd:d;d<Z0e/e*e*d:d=d<Z0e/eed:d>d<Z0eeje*ef eeje*ef d:d?d<Z0eeddd@dAZ1dee ddBdCdDZ2dee*e3e	e%f ee eee*e3e	e%f dFdGdHZ4de5e
e5dJdKdLZ6e,de"ee-dMdNdOZ7e,e-ddPdQZ8e3eef eee9f ddRdSdTZ:eee9f edUdVdWZ;dee<d gef  eeedXdYdZZ=eeedd[d\d]Z>deeee
 dd^d_d`Z?de@eef ee
 ddadbdcZAeBdee
 ee e
dddedfZCe<eeedgdhdiZDe<eeedjdkdlZEeje	e  ejdmdndoZFe'edpdqdrZGeBe'eeHdsdtduZIdddvdwZJejeKe  ddxdydzZLejdd{d|d}ZMeKe  dd)d~dZNeBeKe' ddddZOdS )Fabrica  Fabric accelerates your PyTorch training or inference code with minimal changes required.

    - Automatic placement of models and data onto the device.
    - Automatic support for mixed and double precision (smaller memory footprint).
    - Seamless switching between hardware (CPU, GPU, TPU) and distributed training strategies
      (data-parallel training, sharded training, etc.).
    - Automated spawning of processes, no launch utilities required.
    - Multi-node support.

    Args:
        accelerator: The hardware to run on. Possible choices are:
            ``"cpu"``, ``"cuda"``, ``"mps"``, ``"gpu"``, ``"tpu"``, ``"auto"``.
        strategy: Strategy for how to run across multiple devices. Possible choices are:
            ``"dp"``, ``"ddp"``, ``"ddp_spawn"``, ``"deepspeed"``, ``"fsdp"``.
        devices: Number of devices to train on (``int``), which GPUs to train on (``list`` or ``str``), or ``"auto"``.
            The value applies per node.
        num_nodes: Number of GPU nodes for distributed training.
        precision: Double precision (``64``), full precision (``32``), half precision (``16``),
            or bfloat16 precision (``"bf16"``).
        plugins: One or several custom plugins
        callbacks: A single callback or a list of callbacks. A callback can contain any arbitrary methods that
            can be invoked through :meth:`~lightning_fabric.fabric.Fabric.call` by the user.
        loggers: A single logger or a list of loggers. See :meth:`~lightning_fabric.fabric.Fabric.log` for more
            information.
    N       )	acceleratorstrategydevices	num_nodes	precisionplugins	callbacksloggersreturnc	           	      C   s   t ||||||d| _| jj| _| jj| _| jj| _|d ur@|ng }t|t	rR|n|g| _
|d urf|ng }t|t	rx|n|g| _d| _|   t r| j  d S )N)r:   r;   r<   r=   r>   r?   r   )r   Z
_connectorr;   	_strategyr:   _acceleratorr>   
_precision
isinstancelist
_callbacks_loggers_models_setup_prepare_run_method_is_using_clisetup_environment)	selfr:   r;   r<   r=   r>   r?   r@   rA    rO   `/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/lightning_fabric/fabric.py__init__N   s&    


zFabric.__init__rB   c                 C   s   | j S N)rD   rN   rO   rO   rP   r:   p   s    zFabric.acceleratorc                 C   s   | j S rS   )rC   rT   rO   rO   rP   r;   t   s    zFabric.strategyc                 C   s   | j jS )zwThe current device this process runs on.

        Use this to create tensors directly on the device if needed.
        )rC   Zroot_devicerT   rO   rO   rP   devicex   s    zFabric.devicec                 C   s   t | jddS )zEThe global index of the current process across all devices and nodes.global_rankr   getattrrC   rT   rO   rO   rP   rV      s    zFabric.global_rankc                 C   s   t | jddS )zOThe index of the current process among the processes running on the local node.
local_rankr   rW   rT   rO   rO   rP   rY      s    zFabric.local_rankc                 C   s   t | jddS )zThe index of the current node.	node_rankr   rW   rT   rO   rO   rP   rZ      s    zFabric.node_rankc                 C   s   t | jddS )zCThe total number of processes running across all devices and nodes.
world_sizer8   rW   rT   rO   rO   rP   r[      s    zFabric.world_sizec                 C   s   | j jS )zWhether this rank is rank zero.)rC   is_global_zerorT   rO   rO   rP   r\      s    zFabric.is_global_zeroc                 C   s   | j S )z%Returns all loggers passed to Fabric.rI   rT   rO   rO   rP   rA      s    zFabric.loggersc                 C   s
   | j d S )z[Returns the first logger in the list passed to Fabric, which is considered the main logger.r   r]   rT   rO   rO   rP   logger   s    zFabric.logger)argskwargsrB   c                 O   s   dS )zAll the code inside this run method gets accelerated by Fabric.

        You can pass arbitrary arguments to this function when overriding it.
        NrO   rN   r_   r`   rO   rO   rP   run   s    z
Fabric.runT)move_to_device)module
optimizersrc   rB   c                   s     || |} j|}|r2 j|t|d}|rN j|t|\}}n j|}t| j|d}|	|rx j
nt| j
  fdd|D }  jd7  _t|dr |_||_|rt|g|R S |S )a  Set up a model and its optimizers for accelerated training.

        Args:
            module: A :class:`torch.nn.Module` to set up
            *optimizers: The optimizer(s) to set up (no optimizers is also possible)
            move_to_device: If set ``True`` (default), moves the model to the correct device. Set this to ``False``
                and alternatively use :meth:`to_device` manually.

        Returns:
            The tuple containing wrapped module and the optimizers, in the same order they were passed in.
        modelre   original_modulec                    s   g | ]}t | jd qS )	optimizerr;   r6   rC   .0rk   rT   rO   rP   
<listcomp>       z Fabric.setup.<locals>.<listcomp>r8   _fabric)_validate_setuprE   convert_module_move_model_to_devicerG   rC   Zsetup_module_and_optimizerssetup_moduler5   torU   next
parametersrJ   hasattrrq   Z_fabric_optimizerstuple)rN   rd   rc   re   ri   rO   rT   rP   setup   s(    

zFabric.setup)rd   rc   rB   c                 C   s   |  | |}| j|}|r,| j|g d}| j|}t|| j|d}t| jtsr|	|rb| j
nt| j
 t|dr| |_|  jd7  _|S )a  Set up a model for accelerated training or inference.

        This is the same as calling ``.setup(model)`` with no optimizers. It is useful for inference or for certain
        strategies like `FSDP` that require setting up the module before the optimizer can be created and set up.
        See also :meth:`setup_optimizers`.

        Args:
            module: A :class:`torch.nn.Module` to set up
            move_to_device: If set ``True`` (default), moves the model to the correct device. Set this to ``False``
                and alternatively use :meth:`to_device` manually.

        Returns:
            The wrapped model.
        rf   rh   rq   r8   )_validate_setup_modulerE   rs   rt   rC   ru   r5   rF   r#   rv   rU   rw   rx   ry   rq   rJ   )rN   rd   rc   ri   rO   rO   rP   ru      s    

zFabric.setup_module.)re   rB   c                    sJ     |  fdd|D } fdd|D }t|dkrB|d S t|S )ay  Set up one or more optimizers for accelerated training.

        Some strategies do not allow setting up model and optimizer independently. For them, you should call
        ``.setup(model, optimizer, ...)`` instead to jointly set them up.

        Args:
            *optimizers: One or more optmizers to set up.

        Returns:
            The wrapped optimizer(s).
        c                    s   g | ]} j |qS rO   )rC   Zsetup_optimizerrm   rT   rO   rP   ro     rp   z+Fabric.setup_optimizers.<locals>.<listcomp>c                    s   g | ]}t | jd qS rj   rl   rm   rT   rO   rP   ro     rp   r8   r   )_validate_setup_optimizerslenrz   rN   re   rO   rT   rP   setup_optimizers  s    
zFabric.setup_optimizersreplace_samplerrc   )dataloadersr   rc   rB   c                   s<    |  fdd|D }t|dkr4|d n|}|S )a]  Set up one or multiple dataloaders for accelerated training. If you need different settings for each
        dataloader, call this method individually for each one.

        Args:
            *dataloaders: A single dataloader or a sequence of dataloaders.
            replace_sampler: If set ``True`` (default), automatically wraps or replaces the sampler on the dataloader(s)
                for distributed training. If you have a custom sampler defined, set this to this argument to ``False``.
            move_to_device: If set ``True`` (default), moves the data returned by the dataloader(s) automatically to
                the correct device. Set this to ``False`` and alternatively use :meth:`to_device` manually on the
                returned data.

        Returns:
            The wrapped dataloaders, in the same order they were passed in.
        c                    s   g | ]}j | d qS )r   )_setup_dataloader)rn   
dataloaderrc   r   rN   rO   rP   ro   $  s   z,Fabric.setup_dataloaders.<locals>.<listcomp>r8   r   )_validate_setup_dataloadersr~   )rN   r   rc   r   rO   r   rP   setup_dataloaders  s    
zFabric.setup_dataloaders)r   r   rc   rB   c                 C   s   |j }|r*| |r*| j|fi | jj}t||}t|| j | j|}|rbt	| jt
sb| jnd}t||d}tt|}|S )a  Set up a single dataloader for accelerated training.

        Args:
            dataloader: The dataloader to accelerate.
            replace_sampler: If set ``True`` (default), automatically wraps or replaces the sampler on the dataloader
                for distributed training. If you have a custom sampler defined, set this to this argument to ``False``.
            move_to_device: If set ``True`` (default), moves the data returned by the dataloader automatically to
                the correct device. Set this to ``False`` and alternatively use :meth:`to_device` manually on the
                returned data.

        Returns:
            The wrapped dataloader.
        N)r   rU   )sampler_requires_distributed_sampler_get_distributed_samplerrC   distributed_sampler_kwargsr.   r,   rV   Zprocess_dataloaderrF   r&   rU   r4   r   r   )rN   r   r   rc   r   rU   Zlite_dataloaderrO   rO   rP   r   +  s    

zFabric._setup_dataloader)rg   )tensorr_   rg   r`   rB   c                O   s|   |dur|j n|}t| jtr\|du rT| jdkr8td| jdkrJtd| jj}n|| j_| j	j
||g|R i | dS )a  Replaces ``loss.backward()`` in your training loop. Handles precision and automatically for you.

        Args:
            tensor: The tensor (loss) to back-propagate gradients from.
            *args: Optional positional arguments passed to the underlying backward function.
            model: Optional model instance for plugins that require the model for backward().
            **kwargs: Optional named keyword arguments passed to the underlying backward function.

        Note:
            When using ``strategy="deepspeed"`` and multiple models were set up, it is required to pass in the
            model as argument here.
        Nr   zJNo models were set up for backward. Did you forget to call `self.setup()`?r8   zWhen using multiple models + deepspeed, please provide the model used to perform the optimization: `self.backward(loss, model=model)`)_forward_modulerF   rC   r"   rJ   RuntimeError
ValueErrorrg   Z_deepspeed_enginerE   backward)rN   r   rg   r_   r`   rd   rO   rO   rP   r   K  s    


zFabric.backward)NNNc                 c   s4   | j   dV  W d   n1 s&0    Y  dS )zA context manager to automatically convert operations for the chosen precision.

        Use this only if the `forward` method of your model does not cover all operations you wish to run with the
        chosen precision setting.
        N)rE   Zforward_contextrT   rO   rO   rP   autocasti  s    zFabric.autocast)objrB   c                 C   s   d S rS   rO   rN   r   rO   rO   rP   	to_devices  s    zFabric.to_devicec                 C   s   d S rS   rO   r   rO   rO   rP   r   w  s    c                 C   s   d S rS   rO   r   rO   rO   rP   r   {  s    c                 C   s8   t |tjr*| j| j | j| |S t|| jdS )a  Move a :class:`torch.nn.Module` or a collection of tensors to the current device, if it is not already
        on that device.

        Args:
            obj: An object to move to the device. Can be an instance of :class:`torch.nn.Module`, a tensor, or a
                 (nested) collection of tensors (e.g., a dictionary).

        Returns:
            A reference to the object that was moved to the new device.
        rU   )	rF   nnModulerD   Zsetup_devicerU   rC   Zmodule_to_devicer)   r   rO   rO   rP   r     s
    c                 O   s   | j dkrt|i | dS )zPrint something only on the first process.

        Arguments passed to this method are forwarded to the Python built-in :func:`print` function.
        r   N)rY   printra   rO   rO   rP   r     s    
zFabric.print)namerB   c                 C   s   | j j|d dS )a  Wait for all processes to enter this call. Use this to synchronize all parallel processes, but only if
        necessary, otherwise the overhead of synchronization will cause your program to slow down.

        Example::

            if self.global_rank == 0:
                # let process 0 download the dataset
                dataset.download_files()

            # let all processes wait before reading the dataset
            self.barrier()

            # now all processes can read the files and start training
        )r   N)rC   barrier)rN   r   rO   rO   rP   r     s    zFabric.barrierF)datagroup
sync_gradsrB   c                 C   s:   |dur|nt jjj}t|| jd}t|t| jj	||dS )a;  Gather tensors or collections of tensors from multiple processes.

        Args:
            data: int, float, tensor of shape (batch, ...), or a (possibly nested) collection thereof.
            group: the process group to gather results from. Defaults to all processes (world)
            sync_grads: flag that allows users to synchronize gradients for the all_gather operation

        Return:
            A tensor of shape (world_size, batch, ...), or if the input was a collection
            the output will also be a collection with tensors of this shape.
        Nr   )r   r   )
torchZdistributedr   ZWORLDr+   rU   r   r   rC   
all_gather)rN   r   r   r   rO   rO   rP   r     s    zFabric.all_gatherr   )r   srcrB   c                 C   s   | j j||dS )N)r   )rC   	broadcast)rN   r   r   rO   rO   rP   r     s    zFabric.broadcast)rd   enabledrB   c                 c   s   t |tstd|r"t | jtr*t }n>| jjdu rXtd| jjj	 dt
d t }n| jj|j}| dV  W d   n1 s0    Y  dS )a  Skip gradient synchronization during backward to avoid redundant communication overhead.

        Use this context manager when performing gradient accumulation to speed up training with multiple devices.

        Example::

            # Accumulate gradient 8 batches at a time
            with self.no_backward_sync(model, enabled=(batch_idx % 8 != 0)):
                output = model(input)
                loss = ...
                self.backward(loss)
                ...

        For those strategies that don't support it, a warning is emitted. For single-device strategies, it is a no-op.
        Both the model's `.forward()` and the `self.backward()` call need to run under this context.

        Args:
            module: The module for which to control the gradient synchronization.
            enabled: Whether the context manager is enabled or not. ``True`` means skip the sync, ``False`` means do not
                skip.
        zrYou need to set up the model first before you can call `self.no_backward_sync()`: `model = self.setup(model, ...)`NThe `z` does not support skipping the gradient synchronization. Remove `.no_backward_sync()` from your code or choose a different strategy.category)rF   r5   	TypeErrorrC   r$   r   Z_backward_sync_controlr   	__class____name__r3   no_backward_syncr   )rN   rd   r   contextrO   rO   rP   r     s"    
zFabric.no_backward_syncc                 c   sH   t | jtr>| j  dV  W d   qD1 s20    Y  ndV  dS )a  Shard the parameters of the model instantly when instantiating the layers.

        Use this context manager with strategies that support sharding the model parameters to save peak memory usage.

        Example::

            with self.sharded_model():
                model = MyModel()

        The context manager is strategy-agnostic and for the ones that don't do sharding, it is a no-op.
        N)rF   rC   r'   Zmodule_sharded_contextrT   rO   rO   rP   sharded_model  s    &zFabric.sharded_model)contentfilepathrB   c                 C   s   | j || dS )ad  Save checkpoint contents to a file.

        How and which processes save gets determined by the `strategy`. For example, the `ddp` strategy
        saves checkpoints only on process 0.

        Args:
            content: A dictionary with contents, i.e., the state dict of your model
            filepath: A path to where the file should be saved
        N)rC   Zsave_checkpoint)rN   r   r   rO   rO   rP   save  s    
zFabric.save)r   rB   c                 C   s   | j |S )zLoad a checkpoint from a file.

        How and which processes load gets determined by the `strategy`

        Args:
            filepath: A path to where the file is located
        )rC   Zload_checkpoint)rN   r   rO   rO   rP   load  s    zFabric.load)functionr_   r`   rB   c                 O   sz   t  rtd|d ur*t|js*tdt| j|p6t}| g|}| j	j
d url| j	j
j|g|R i |S ||i |S )Nz}This script was launched through the CLI, and processes have already been created. Calling  `.launch()` again is not allowed.zThe function passed to `Fabric.launch()` needs to take at least one argument. The launcher will pass in the `Fabric` object so you can use it inside the function.)rL   r   inspect	signaturerx   r   r   _run_with_setup_do_nothingrC   launcherlaunch)rN   r   r_   r`   rO   rO   rP   r     s    
zFabric.launch)	hook_namer_   r`   rB   c                 O   sZ   | j D ]N}t||d}|du r qt|sFtdt|j d| d q||i | qdS )a  Trigger the callback methods with the given name and arguments.

        Not all objects registered via ``Fabric(callbacks=...)`` must implement a method with the given name. The ones
        that have a matching method name will get called.

        Args:
            hook_name: The name of the callback method.
            *args: Optional positional arguments that get passed down to the callback method.
            **kwargs: Optional keyword arguments that get passed down to the callback method.

        Example::

            class MyCallback:
                def on_train_epoch_end(self, results):
                    ...

            fabric = Fabric(callbacks=[MyCallback()])
            fabric.call("on_train_epoch_end", results={...})
        NzSkipping the callback `.z` because it is not callable.)rH   rX   callabler   typer   )rN   r   r_   r`   callbackmethodrO   rO   rP   call&  s    
zFabric.call)r   valuesteprB   c                 C   s   | j ||i|d dS )a  Log a scalar to all loggers that were added to Fabric.

        Args:
            name: The name of the metric to log.
            value: The metric value to collect. If the value is a :class:`torch.Tensor`, it gets detached from the
                graph automatically.
            step: Optional step number. Most Logger implementations auto-increment the step value by one with every
                log call. You can specify your own value here.
        metricsr   N)log_dict)rN   r   r   r   rO   rO   rP   logL  s    
z
Fabric.log)r   r   rB   c                 C   s&   t |}| jD ]}|j||d qdS )a  Log multiple scalars at once to all loggers that were added to Fabric.

        Args:
            metrics: A dictionary where the key is the name of the metric and the value the scalar to be logged.
                Any :class:`torch.Tensor` in the dictionary get detached from the graph automatically.
            step: Optional step number. Most Logger implementations auto-increment this value by one with every
                log call. You can specify your own value here.
        r   N)r*   rI   Zlog_metrics)rN   r   r   r^   rO   rO   rP   r   X  s    	
zFabric.log_dict)seedworkersrB   c                 C   s   |du rd}t | |dS )zHelper function to seed everything without explicitly importing Lightning.

        See :func:`pytorch_lightning.seed_everything` for more details.
        NTr   r   r1   r   rO   rO   rP   r2   e  s    zFabric.seed_everything)
run_methodr_   r`   rB   c                 O   sF   t | j|}| jjd ur4| jjj|g|R i |S ||i |S d S rS   )r   r   rC   r   r   )rN   r   r_   r`   rO   rO   rP   	_run_implq  s    zFabric._run_impl)run_functionr_   r`   rB   c              
   O   s   | j   |   ttdb tt: ||i |W  d    W  d    W  d    S 1 sh0    Y  W d    n1 s0    Y  W d    n1 s0    Y  d S )Ndataset)rC   rM   r   r-   r   r   )rN   r   r_   r`   rO   rO   rP   r   x  s
    
zFabric._run_with_setup)rg   re   rB   c                    s   t | j t fdd| D r4tdtd t| jtrt	|
 }| |}t	|
 fdd| D |D ]*}|jD ]}fdd|d	 D |d	< qq|n
| |}|S )
Nc                 3   s   | ]}|j  kV  qd S rS   r   )rn   param)initial_devicerO   rP   	<genexpr>  rp   z/Fabric._move_model_to_device.<locals>.<genexpr>zThe model passed to `Fabric.setup()` has parameters on different devices. Since `move_to_device=True`, all parameters will be moved to the new device. If this is not desired, set  `Fabric.setup(..., move_to_device=False)`.r   c                    s   i | ]\}}| | qS rO   rO   )rn   r   r   )params_on_devicerO   rP   
<dictcomp>  rp   z0Fabric._move_model_to_device.<locals>.<dictcomp>c                    s   g | ]}  ||qS rO   )get)rn   p)mappingrO   rP   ro     rp   z0Fabric._move_model_to_device.<locals>.<listcomp>params)rw   rx   rU   anyr   r3   rF   rC   r&   dictZnamed_parametersr   itemsZparam_groups)rN   rg   re   Zparams_before_moverk   Zparam_grouprO   )r   r   r   rP   rt     s     

 
zFabric._move_model_to_device)r   rB   c                 C   s*   t | jdd d uo(t|jt o(t| S )Nr   )rX   r;   rF   r   r   r/   )rN   r   rO   rO   rP   r     s
    z$Fabric._requires_distributed_sampler)r   r`   rB   c                 K   s`   | dt| jt | dttdd t| jttfrNt| j	fi |S t
| jfi |S )Nshuffler   ZPL_GLOBAL_SEEDr   )
setdefaultrF   r   r   intosgetenvr   r   r   r0   )r   r`   rO   rO   rP   r     s
    zFabric._get_distributed_samplerc                 C   s4   t d| trt rtdt| dt| j| j d S )Nrb   zOverriding `Fabric.run()` and launching from the CLI is not allowed. Run the script normally, or change your code to directly call `fabric = Fabric(...); fabric.setup(...)` etc.)r   r7   rL   r   setattrr   r   rb   rT   rO   rO   rP   rK     s
    zFabric._prepare_run_method)rd   re   rB   c                 C   sR   t |trtdtdd |D r,tdt | jtrNtdt| j dd S )Nz9A model should be passed only once to the `setup` method.c                 s   s   | ]}t |tV  qd S rS   rF   r6   rn   optrO   rO   rP   r     rp   z)Fabric._validate_setup.<locals>.<genexpr>z>An optimizer should be passed only once to the `setup` method.r   z` requires the model and optimizer(s) to be set up separately. Create and set up the model first through `model = self.setup_model(model)`. Then create the optimizer and set it up: `optimizer = self.setup_optimizer(optimizer)`.)	rF   r5   r   r   rC   r#   r   r   r   )rN   rd   re   rO   rO   rP   rr     s    
zFabric._validate_setup)rd   rB   c                 C   s   t |trtdd S )Nz@A model should be passed only once to the `setup_module` method.)rF   r5   r   )rN   rd   rO   rO   rP   r|     s    
zFabric._validate_setup_modulec                 C   sR   t | jttfr(tdt| jj d|s4tdtdd |D rNtdd S )Nr   zc` requires the model and optimizer(s) to be set up jointly through `.setup(model, optimizer, ...)`.z<`setup_optimizers` requires at least one optimizer as input.c                 s   s   | ]}t |tV  qd S rS   r   r   rO   rO   rP   r     rp   z4Fabric._validate_setup_optimizers.<locals>.<genexpr>zIAn optimizer should be passed only once to the `setup_optimizers` method.)	rF   rC   r"   r&   r   r   r   r   r   r   rO   rO   rP   r}     s    z!Fabric._validate_setup_optimizers)r   rB   c                 C   sD   | st dtdd | D r&t dtdd | D r@tdd S )Nz>`setup_dataloaders` requires at least one dataloader as input.c                 s   s   | ]}t |tV  qd S rS   )rF   r4   rn   dlrO   rO   rP   r     rp   z5Fabric._validate_setup_dataloaders.<locals>.<genexpr>zJA dataloader should be passed only once to the `setup_dataloaders` method.c                 s   s   | ]}t |t V  qd S rS   )rF   r   r   rO   rO   rP   r     rp   zGOnly PyTorch DataLoader are currently supported in `setup_dataloaders`.)r   r   r   )r   rO   rO   rP   r     s    z"Fabric._validate_setup_dataloaders)NNNr8   r9   NNN)T)TT)N)NF)r   )T)N)N)N)NN)Pr   
__module____qualname____doc__r   r   strr   r%   r   r   r!   r    r   r   rQ   propertyr:   r;   r   rU   rV   rY   rZ   r[   boolr\   rA   r^   rb   r   r   r   r{   r5   ru   r6   r   r   r   r   r   r   r   r   r
   r   r   r   r   r   r	   r   r(   r   r   r   r   r   r   r   r   r   r   r   r   staticmethodr2   r   r   rt   r   r   r   rK   r   rr   r|   r}   r   rO   rO   rO   rP   r7   3   s           "
3%    	( -"
$& 	r7   rR   c                   C   s   t ttjddS )NZLT_CLI_USED0)r   r   r   environr   rO   rO   rO   rP   rL     s    rL   )_rB   c                  G   s   d S rS   rO   )r   rO   rO   rP   r     s    r   )Sr   r   
contextlibr   r   	functoolsr   pathlibr   typingr   r   r   r	   r
   r   r   r   r   r   r   r   r   Ztorch.nnr   Z#lightning_utilities.core.apply_funcr   Z"lightning_utilities.core.overridesr   Z"lightning_utilities.core.rank_zeror   r   Ztorch.optimr   Ztorch.utils.datar   r   r   r   r   Zlightning_fabric.loggersr   Zlightning_fabric.pluginsr   Z)lightning_fabric.accelerators.acceleratorr   Zlightning_fabric.connectorr   r    r!   Zlightning_fabric.strategiesr"   r#   r$   r%   r&   Z$lightning_fabric.strategies.strategyr'   r(   Zlightning_fabric.utilitiesr)   Z%lightning_fabric.utilities.apply_funcr*   r+   Zlightning_fabric.utilities.datar,   r-   r.   r/   Z&lightning_fabric.utilities.distributedr0   Zlightning_fabric.utilities.seedr2   Z#lightning_fabric.utilities.warningsr3   Zlightning_fabric.wrappersr4   r5   r6   r7   r   rL   r   rO   rO   rO   rP   <module>   sD   8     0