a
    dZN                  
   @   s  d dl 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 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mZm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" d dl#m$Z$ d dl%m&Z& d dl'm(Z(m)Z)m*Z* d dl+m,Z, d dl-m.Z. d dl/m0Z0m1Z1m2Z2 eee3eedf ed f Z4e2 Z5e4ee	e6 ddf dddZ7e4e6dddZ8eee&f ded e9dddZ:eeef ee6e;f dddZ<d6eeeef e	e$ edd d!Z=d7eeeef e	e$ e9e
e
e ee3ef f d#d$d%Z>d8eeeef e	e$ e9ee3ef d#d&d'Z?eed(d)d*Z@e9e
e3d+f e
ed+f ee3ef e
e
e3d+f ee3ef f d,d-d.ZAeBe9dd/d0ZCeeed1d2d3Zeeed1d4d5ZdS )9    N)fields)AnyDict	GeneratorIterableMappingOptionalTupleUnion)is_dataclass_instance)Tensor)BatchSampler
DataLoaderDatasetIterableDatasetRandomSamplerSamplerSequentialSampler)_reinstantiate_wrapped_cls_replace_value_in_saved_args)has_iterable_dataset)has_len)IndexBatchSamplerWrapper)RunningStage)CombinedLoader)CaptureIterableDatasetCaptureMapDatasetFastForwardSampler)_FaultTolerantMode)MisconfigurationException)rank_zero_deprecationrank_zero_warnWarningCacheBType)batchreturnc                 c   s   t | tr*| jdkrdV  q| dV  nxt | ttfrnt | tsnt | trT|  } | D ]}t|E d H  qXn4t	| rt
| D ]}tt| |jE d H  q~nd V  d S )Nr      )
isinstancer   ndimsizer   r   strvalues_extract_batch_sizer   r   getattrname)r$   samplefield r1   i/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/pytorch_lightning/utilities/data.pyr,   1   s    


r,   c                 C   sv   d}d}z>t | D ]0}|du r$|}q||krtd| d  qDqW n ty`   t|Y n0 |du rrt||S )zUnpack a batch to find a ``torch.Tensor``.

    Returns:
        ``len(tensor)`` when found, or ``1`` when it hits an empty or non iterable.
    zWe could not infer the batch_size from the batch. Either simplify its structure or provide the batch_size as `self.log(..., batch_size=batch_size)`.NzZTrying to infer the `batch_size` from an ambiguous collection. The batch size we found is zK. To avoid any miscalculations, use `self.log(..., batch_size=batch_size)`.)r,   warning_cachewarnRecursionErrorr   )r$   	error_msg
batch_sizebsr1   r1   r2   extract_batch_sizeD   s&    
r9   zpl.strategies.Strategy)zpl.LightningModulezpl.LightningDataModule)
dataloaderstrategymodelr%   c              	   C   s   zt | }|jtj||jddd}|dkr@td| jj d |dkr|dkr|jrptd| jj d d}qt	d	| jj d
nd}W n t
tfy   d}Y n0 |rt| rtd |S )z}Checks if a given Dataloader has ``__len__`` method implemented i.e. if it is a finite dataloader or
    infinite dataloader.)Zdevicesum)Z	reduce_opr   zTotal length of `zA` across ranks is zero. Please make sure this was your intention.zb` across ranks is zero, but local rank has zero length. Please be cautious of uneven batch length.F`zW` within local rank has zero length. Please make sure that it returns at least 1 batch.TzYour `IterableDataset` has `__len__` defined. In combination with multi-process data loading (when num_workers > 1), `__len__` could be inaccurate if each worker is not configured independently to avoid having duplicate data.)lenreducetorchZtensorZroot_devicer!   	__class____name__Z2allow_zero_length_dataloader_with_multiple_devicesr   	TypeErrorNotImplementedErrornew_has_iterable_dataset)r:   r;   r<   Zlocal_lengthtotal_lengthr   r1   r1   r2   has_len_all_ranksb   s0    
rH   )r:   r%   c                 C   s   t | rt| S tdS )zsReturn the length of the given DataLoader.

    If ``__len__`` method is not implemented, return float('inf').
    inf)new_has_lenr?   float)r:   r1   r1   r2   get_len   s    rL   )r:   samplermoder%   c                 C   s*   t | ||\}}t| g|R i |} | S N)$_get_dataloader_init_args_and_kwargsr   )r:   rM   rN   dl_args	dl_kwargsr1   r1   r2   _update_dataloader   s    rS   F)r:   rM   rN   disallow_batch_samplerr%   c              
      s6  t | tstd|  dt| d}|rB| j}| j| j | j}n(dd t| 	 D d }| j
d< d tt| jj}tdd	 | D }|r|r|d
d ttjj	 D  n |ttjj |dd  |sfdd|	 D d fdd	 D d}d|}	t |	trHd d< d d< nt| |||  fdd| D }
|
rt|
}| jj}ddd	 |D }td| d| d| d| d	|stt B |  }|rt|}| jj}td| d| d| dt  j!r.t"| |\}|fS )NzThe dataloader z0 needs to subclass `torch.utils.data.DataLoader`__pl_saved_argsc                 S   s    i | ]\}}| d s||qS )_)
startswith.0kvr1   r1   r2   
<dictcomp>       z8_get_dataloader_init_args_and_kwargs.<locals>.<dictcomp>multiprocessing_contextr1   c                 s   s   | ]}|j |ju V  qd S rO   )kindVAR_KEYWORDrY   pr1   r1   r2   	<genexpr>   r]   z7_get_dataloader_init_args_and_kwargs.<locals>.<genexpr>c                 S   s"   i | ]\}}|j |jur||qS r1   )defaultemptyrX   r1   r1   r2   r\      r]   selfc                    s*   h | ]"\}}| v r|j  | ur|qS r1   )rd   )rY   r.   rb   )attrsr1   r2   	<setcomp>   r]   z7_get_dataloader_init_args_and_kwargs.<locals>.<setcomp>datasetc                    s   i | ]\}}| v r||qS r1   r1   rX   )non_defaultsr1   r2   r\      r]   batch_samplerrM   c                    sD   h | ]<}|j |j|jfv r|j|ju r|jvr|j vr|jqS r1   )r_   POSITIONAL_ONLYPOSITIONAL_OR_KEYWORDrd   re   r.   ra   )	arg_namesrR   r1   r2   rh      s   

z, c                 s   s   | ]}d | dV  qdS )z`self.r>   Nr1   )rY   Zarg_namer1   r1   r2   rc      r]   z,Trying to inject custom `Sampler` into the `z` instance. This would fail as some of the `__init__` arguments are not available as instance attributes. The missing attributes are z. If you instantiate your `zZ` inside a `*_dataloader` hook of your module, we will do this for you. Otherwise, define z inside your `__init__`.z&Trying to inject parameters into the `z{` instance. This would fail as it doesn't expose all its attributes in the `__init__` signature. The missing arguments are z. HINT: If you wrote the `zA` class, add the `__init__` arguments or allow passing `**kwargs`)#r'   r   
ValueErrorhasattrrU   __pl_saved_kwargs__pl_saved_arg_namesZ	__datasetvarsitemsr^   dictinspect	signature__init__
parametersanyr+   updatepopaddgetr   '_dataloader_init_kwargs_resolve_samplersortedrB   rC   joinr   setkeysr   detect_current_modeis_automatic7_apply_fault_tolerant_automatic_capture_dataset_wrapper)r:   rM   rN   rT   was_wrappedrQ   Zoriginal_datasetparamsZhas_variadic_kwargsri   Zrequired_argsZsorted_required_argsZdataloader_cls_nameZmissing_args_messageZmissing_kwargsZsorted_missing_kwargsr1   )rn   rg   rR   rj   r2   rP      s    




	rP   c              
   C   s  t  }t| d}|tjk}|dur|rXt|tu rL|j|krL| j|jksTt	dnft|tusj|rt|}t
|dr|j}|j}	|j}
|j}|rtdd||	|
|\}}}	|std|j d td	|||	|
|\}}}	|std
|j dt|g|R i |	}nrz |||j|r"dn|jd}W nP ty~ } z6ddl}|dt|}|s` t	d|W Y d}~n
d}~0 0 |rt|}|jrt| }}|jdd dd|dddS |jrt| }}|j| jd |dddS )aS  This function is used to handle the sampler, batch_sampler arguments associated within a DataLoader for its
    re-instantiation.

    If the dataloader is being used for prediction, the sampler will be wrapped into an `IndexBatchSamplerWrapper`, so
    Lightning can keep track of its indices. If fault tolerant training is enabled, the sampler will be wrapped into a
    `FastForwardSampler`.

    If there are multiple devices in IPU mode, it is necessary to disallow BatchSampler that isn't instantiated
    automatically, since `poptorch.DataLoader` will try to increase the batch_size
    rk   NzdIt is not possible to have a batch sampler in your dataloader, when running on multiple IPU devices.rU   	drop_lastFzlTrying to inject `drop_last=False` into batch sampler since you are predicting, however it seems the class `z` does not support it. Your predictions might be incomplete. To mitigate this, expose `drop_last` in the `__init__` method of your custom class.rM   zYTrying to inject a modified sampler into the batch sampler; however, it seems the class `z` does not have an argument called `sampler.` To mitigate this, expose an argument `sampler` in the `__init__` method of your custom class.)r7   r   r   z:.*__init__\(\) (got multiple values)|(missing \d required)zWe tried to re-instantiate your custom batch sampler and failed. To mitigate this, either follow the API of `BatchSampler` or instantiate your custom batch sampler inside `*_dataloader` hooks of your module.r&   )Zdataloader_batch_size)rM   shufflerk   r7   r   )rM   r   rk   )r   r   r-   r   Z
PREDICTINGtyper   rM   r7   r   rp   rU   rq   Z__pl_saved_default_kwargsrr   r   r!   __qualname__rD   r   r   rematchr*   r   r   r   setup)r:   rM   rN   rT   Zfault_tolerant_moderk   Zis_predictingZbatch_sampler_clsargskwargsZdefault_kwargsrn   successer   r   Zfast_forward_samplerr1   r1   r2   r     s    







r   )ri   r%   c                 C   s:   t | trt| dS t| tdkr.t| dS tdd S )Nri   rI   zKThis shouldn't happen, please open an issue on Lightning Github repository.)r'   r   r   rL   rK   r   RuntimeErrorr   r1   r1   r2   _wrap_with_capture_datasets  s
    


r   .)r   rn   rQ   rR   r%   c                 C   s~   d|v rt |d |d< n\d|v r\|d}t || }|d | |f ||d d   }n| rfd}nd}td| ||fS )Nri   r&   z To avoid this, either pass `DataLoader(dataset=your_dataset)` or the positional dataset argument `DataLoader(your_dataset, ...)`.zT To avoid this, define `self.dataset = dataset` inside your DataLoader's `__init__`.zYou enabled automatic Fault Tolerant mode, but we were not able to replace your dataset with Fault Tolerant wrapper, because you have a custom DataLoader.)r   indexr   )r   rn   rQ   rR   Zdataset_idxri   Zavoid_messager1   r1   r2   r   |  s     
$r   c                 C   sv   t | dr:d| jv r| jd S d| jv r:| j| jd S t| jtrJdS t | dsXdS | j}t|t	rldS t|t
S )Nrq   r   FrM   )rp   rq   rr   rU   r   r'   ri   r   rM   r   r   )r:   rM   r1   r1   r2   _is_dataloader_shuffled  s    





r   )r   r   r%   c                  O   s   t d t| i |S )Nz`pytorch_lightning.utilities.data.has_iterable_dataset` has been deprecated in v1.8.0 and will be removed in v2.0.0. Please use `lightning_fabric.utilities.data.has_iterable_dataset` instead.)r    rF   r   r   r1   r1   r2   r     s    r   c                  O   s   t d t| i |S )Nz`pytorch_lightning.utilities.data.has_len` has been deprecated in v1.8.0 and will be removed in v2.0.0. Please use `lightning_fabric.utilities.data.has_len` instead.)r    rJ   r   r1   r1   r2   r     s    r   )N)NF)NF)Drv   Zdataclassesr   typingr   r   r   r   r   r   r	   r
   rA   Z#lightning_utilities.core.apply_funcr   r   Ztorch.utils.datar   r   r   r   r   r   r   Zpytorch_lightningplZlightning_fabric.utilities.datar   r   r   rF   r   rJ   Z'pytorch_lightning.overrides.distributedr   Z pytorch_lightning.trainer.statesr   Z$pytorch_lightning.trainer.supportersr   Z(pytorch_lightning.utilities.auto_restartr   r   r   Z!pytorch_lightning.utilities.enumsr   Z&pytorch_lightning.utilities.exceptionsr   Z%pytorch_lightning.utilities.rank_zeror    r!   r"   r*   r#   r3   intr,   r9   boolrH   rK   rL   rS   rP   r   r   r   objectr   r1   r1   r1   r2   <module>   sr   ($

-    
g  

l
 