
      iA                     ,   d dl Z d dlmZmZmZmZ d dlmZ d dl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 d dlmZ d dlZd d	l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' d dl(m)Z)m*Z* eee+ee	df   ed   f   Z, e)       Z-de,dee
e.   ddf   fdZ/de,de.fdZ0	 dde1ddde2dee   fdZ3	 d dedeeef   de
e%   defdZ4	 d dedeeef   de
e%   de5e5e	   e6e+e	f   f   fdZ7	 d dedeeef   de
e%   de6e+e	f   fdZ8de1de2fdZ9y)!    N)	GeneratorIterableMappingSized)fields)AnyOptionalUnion)is_dataclass_instance)Tensor)BatchSampler
DataLoaderIterableDatasetRandomSamplerSamplerSequentialSampler)	TypeGuard)_reinstantiate_wrapped_cls_replace_value_in_saved_argshas_iterable_dataset	sized_len)PossibleUserWarning)_IndexBatchSamplerWrapper)RunningStage)MisconfigurationException)WarningCacherank_zero_warnBTypebatchreturnc              #     K   t        | t              r(| j                  dk(  rd y | j                  d       y t        | t        t
        f      rKt        | t              s;t        | t
              r| j                         } | D ]  }t        |      E d {     y t        |       r8t        |       D ])  }t        t        | |j                              E d {    + y d  y 7 O7 w)Nr      )
isinstancer   ndimsizer   r   strvalues_extract_batch_sizer   r   getattrname)r   samplefields      u/Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/pytorch_lightning/utilities/data.pyr(   r(   +   s     % ::?G**Q-	EHg.	/
5#8NeW%LLNEF*6222 	u	%E]E*75%**+EFFF # 
 3 Gs%   BC(C$AC(C&C(&C(c                     d}d}	 t        |       D ]'  }||}||k7  st        j                  d| d        n |t	        |      |S # t        $ r t        |      w xY w)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bss       r-   extract_batch_sizer5   >   s    	P  J(%e,B!
r!""!!+,wy  - '	22  (Y''(s   A
 A
 
A
dataloaderstrategyzpl.strategies.Strategy2allow_zero_length_dataloader_with_multiple_devicesc                 |   t        |       }|y|j                  t        j                  ||j                        d      }|dk(  r"t        dt        |       j                   d       |dkD  r:|dk(  r5t        |       j                  }|st        d| d	      t        d| d
       t        |       rt        d       y)zIChecks if a given object has ``__len__`` method implemented on all ranks.F)devicesum)	reduce_opr   zTotal length of `zA` across ranks is zero. Please make sure this was your intention.`zW` within local rank has zero length. Please make sure that it returns at least 1 batch.zb` across ranks is zero, but local rank has zero length. Please be cautious of uneven batch length.zYour `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.T)
r   reducetorchtensorroot_devicer   type__name__RuntimeErrorr   )r6   r7   r8   local_lengthtotal_lengthdataloader_cls_names         r-   has_len_all_ranksrH   ]   s     Z(L??5<<XEYEY#Zfk?lLqZ 0 9 9: ;9 9	
 aLA-":.77A'( )F F  	 34 5B B	

 J'/	
     samplermodec                 @    t        | ||      \  }}t        | g|i |S N)$_get_dataloader_init_args_and_kwargsr   )r6   rJ   rK   dl_args	dl_kwargss        r-   _update_dataloaderrQ      s-     >j'SWXGY%jH7HiHHrI   c                    t        | t              st        d|  d      t        | d      }|r1| j                  }| j
                  }| j                  }| j                  }nQt        |       j                         D 	ci c]  \  }}	|j                  d      r||	 }
}}	d }| j                  |
d<   d}t        t        j                  | j                        j                         }t#        d |j%                         D              }|r|rx|j'                  t        j                  t        j                        j                   j                         D 	ci c]!  \  }}	|	j(                  |	j*                  us||	# c}	}       nN|j'                  t        j                  t        j                        j                          |j-                  dd        |st|j                         D ch c]  \  }}|
v s|j(                  |
|   us|  }}}|j/                  d	       
j                         D 	ci c]  \  }}	||v s||	 }}}	d}j1                  d	|      }t        |t2              rd |d
<   d |d<   n|j'                  t5        | ||             |j%                         D ch c]f  }|j6                  |j8                  |j:                  fv r@|j(                  |j*                  u r(|j<                  |vr|j<                  |vr|j<                  h }}|rQt?        |      }| j@                  jB                  }djE                  d |D              }tG        d| d| d| d| d	      |s`tI        |      tI        |      z  |jK                         z
  }|r6t?        |      }| j@                  jB                  }tG        d| d| d| d      |fS c c}	}w c c}	}w c c}}w c c}	}w c c}w )NzThe dataloader z0 needs to subclass `torch.utils.data.DataLoader`__pl_saved_args_multiprocessing_context c              3   L   K   | ]  }|j                   |j                  u   y wrM   )kindVAR_KEYWORD).0ps     r-   	<genexpr>z7_get_dataloader_init_args_and_kwargs.<locals>.<genexpr>   s     O!aff5s   "$selfdatasetbatch_samplerrJ   z, c              3   (   K   | ]
  }d | d  yw)z`self.r=   NrV   )rZ   arg_names     r-   r\   z7_get_dataloader_init_args_and_kwargs.<locals>.<genexpr>   s     (cNb(6(1)=Nbs   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hasattrrS   __pl_saved_kwargs__pl_saved_arg_names	__datasetvarsitems
startswithrU   dictinspect	signature__init__
parametersanyr'   updatedefaultemptypopaddgetr   '_dataloader_init_kwargs_resolve_samplerrX   POSITIONAL_ONLYPOSITIONAL_OR_KEYWORDr*   sorted	__class__rC   joinr   setkeys)r6   rJ   rK   was_wrappedrO   rP   	arg_namesoriginal_datasetkvattrsparamshas_variadic_kwargsr*   r[   non_defaultsr^   required_argssorted_required_argsrG   missing_args_messagemissing_kwargssorted_missing_kwargss                          r-   rN   rN      s   
 j*-?:,6fghh*&78K,,00	33	%// #'z"2"8"8":T":$!Q!,,sBSA":T  +5+M+M'(	 '##J$7$78CCDFOv}}OO  MM!(!2!2:3F3F!G!R!R!X!X!Z!ZA^_^g^gopovov^v1!Z  MM'++J,?,?@KKLJJvt$,2LLNmNqdemPQPYPYafgkalPlNm 	#&+kkmImdaqL7HQTm	ImmI'78G'?+%)	/"#	)@WVZ[\  A66a'')@)@AAII FF)#FF)# 	
    %m4(22;;#yy(cNb(cc':;N:O P**>)??Z[nZo p""6!77O	Q
 	
 i.3y>9V[[]J$*>$:!","6"6"?"?+89L8M N--B,CC]^q]r sRR  IW U" n
 Js=   ;OO O	
0O	
!O.O O+O8OA+Oc                 R   |t         j                  k(  }t        | d      }t        |      }|6|t        us|r+t        |d      r|j                  }|j                  }|j                  }|j                  }	|r/t        dd||||	      \  }
}}|
st        d|j                   d       t        d|||||	      \  }
}}|
st        d	|j                   d
      t        |g|i |}njt        |d      r1t        |d      r%	  |||j                  |rdn|j                         }n-|r t        d|j                   dt(               nt        d      |rt+        |      }dd|dddS |dddS # t        $ r3}ddl}|j%                  dt'        |            }|s t        d      |d}~ww xY w)a.  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.

    r_   NrS   	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.rJ   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.r3   )r3   r   r   z:.*__init__\(\) (got multiple values)|(missing \d required)a   Lightning can't inject a (distributed) sampler into your batch sampler, because it doesn't subclass PyTorch's `BatchSampler`. To mitigate this, either follow the API of `BatchSampler` and instantiate your custom batch sampler inside the `*_dataloader` hook of your module, or set `Trainer(use_distributed_sampler=False)`. If you choose the latter, you will be responsible for handling the distributed sampling within your batch sampler.z&You are using a custom batch sampler `z` for prediction. Lightning would normally set `drop_last=False` to ensure all samples are returned, but for custom samplers it can't guarantee this. Make sure your sampler is configured correctly to return all indices.)categorya\   Lightning can't inject a (distributed) sampler into your batch sampler, because it doesn't subclass PyTorch's `BatchSampler`. To mitigate this, either follow the API of `BatchSampler` or set `Trainer(use_distributed_sampler=False)`. If you choose the latter, you will be responsible for handling the distributed sampling within your batch sampler.r"   )rJ   shuffler_   r3   r   )rJ   r   r_   )r   
PREDICTINGr)   rB   r   rc   rS   rd   __pl_saved_default_kwargsre   r   r   __qualname__	TypeErrorr   r3   r   rematchr&   r   r   )r6   rJ   rK   is_predictingr_   batch_sampler_clsargskwargsdefault_kwargsr   successexr   r   s                 r-   rv   rv      s'    L333MJ8M]+ &7|&K}="34 00D"44F*DDN%::I(Dfni)%v "//@/M/M.N OFF %A7D&.)%!GT6 )667 8hh  7}VtVvVM]L1gm[6Y 1,77(5u=;R;R!, 89J9W9W8X Y    - `  5mDM *
 	
 54HH_  !^`cdf`gh  d s   >#E* *	F&3.F!!F&c                    t        | d      rSd| j                  v r| j                  d   S d| j                  v r(| j                  | j                  j	                  d         S t        | d      rt        | j                  t              ryt        | d      sy| j                  }|t        |d      r|j                  n|}n| j                  }t        |t              ryt        |t              S )Nrd   r   r^   FrJ   )rc   rd   re   rS   indexr#   r^   r   r_   rJ   r   r   )r6   r_   rJ   s      r-   _is_dataloader_shuffledr   S  s    z./ 
444//	::
777--j.M.M.S.ST].^__z9%*Z5G5G*Y:y),,M +2=)+L-''R_$$',-g}--rI   )FrM   ):rk   collections.abcr   r   r   r   dataclassesr   typingr   r	   r
   r?   #lightning_utilities.core.apply_funcr   r   torch.utils.datar   r   r   r   r   r   typing_extensionsr   pytorch_lightningpllightning_fabric.utilities.datar   r   r   r   #lightning_fabric.utilities.warningsr   'pytorch_lightning.overrides.distributedr    pytorch_lightning.trainer.statesr   &pytorch_lightning.utilities.exceptionsr   %pytorch_lightning.utilities.rank_zeror   r   r&   r   r/   intr(   r5   objectboolrH   rQ   tuplerj   rN   rv   r   rV   rI   r-   <module>r      s    ? ?  ' '  E  q q '   D M 9 L Nfc73<0(72CCDu 8C=$3L)M &e  D @E$$&$ 9=$ u	$P _cII%*7H+<%=IEMlE[II $([[7H$%[ <
 [ 5:tCH~%&	[B $(gIgI7H$%gI <
 gI 
#s(^	gIT. .4 .rI   