
    h8A                    R   S SK Jr  S SKrS SKrS SKrS SKJr  S SKJr  S SK	J
r
  S SKJr  S SKrS SKrS SKJr  S SKJr  S SKJrJr  S S	KJr  S S
KJrJrJr  S SKJrJrJ r J!r!J"r"J#r#J$r$J%r%  S SK&J'r'J(r(  S SK)J*r*J+r+  S SK,J-r-  S SK.J/r/   " S S\R`                  5      r1 " S S5      r2 " S S\Rf                  Rh                  Rj                  5      r6SS jr7    S               SS jjr8    S               S S jjr9    S!           S"S jjr:S r;S#S$S jjr<g)%    )annotationsN)Iterator)Path)Any)urlsplit)Image)
dataloaderdistributed)IterableSimpleNamespace)GroundingDatasetYOLODatasetYOLOMultiModalDataset)LOADERSLoadImagesAndVideosLoadPilAndNumpyLoadScreenshotsLoadStreams
LoadTensorSourceTypesautocast_list)IMG_FORMATSVID_FORMATS)RANKcolorstr)
check_file)	TORCH_2_0c                  P   ^  \ rS rSrSrS	U 4S jjrS
S jrSS jrS rS r	Sr
U =r$ )InfiniteDataLoader%   a  
Dataloader that reuses workers for infinite iteration.

This dataloader extends the PyTorch DataLoader to provide infinite recycling of workers, which improves efficiency
for training loops that need to iterate through the dataset multiple times without recreating workers.

Attributes:
    batch_sampler (_RepeatSampler): A sampler that repeats indefinitely.
    iterator (Iterator): The iterator from the parent DataLoader.

Methods:
    __len__: Return the length of the batch sampler's sampler.
    __iter__: Create a sampler that repeats indefinitely.
    __del__: Ensure workers are properly terminated.
    reset: Reset the iterator, useful when modifying dataset settings during training.

Examples:
    Create an infinite dataloader for training
    >>> dataset = YOLODataset(...)
    >>> dataloader = InfiniteDataLoader(dataset, batch_size=16, shuffle=True)
    >>> for batch in dataloader:  # Infinite iteration
    >>>     train_step(batch)
c                   > [         (       d  UR                  SS5        [        TU ]  " U0 UD6  [        R                  U S[        U R                  5      5        [        TU ]!  5       U l	        g)zHInitialize the InfiniteDataLoader with the same arguments as DataLoader.prefetch_factorNbatch_sampler)
r   popsuper__init__object__setattr___RepeatSamplerr"   __iter__iterator)selfargskwargs	__class__s      P/home/james-whalen/.local/lib/python3.13/site-packages/ultralytics/data/build.pyr%   InfiniteDataLoader.__init__>   sU    yJJ($/$)&)4.ASAS2TU(*    c                @    [        U R                  R                  5      $ )z1Return the length of the batch sampler's sampler.)lenr"   samplerr+   s    r/   __len__InfiniteDataLoader.__len__F   s    4%%--..r1   c              #  p   #    [        [        U 5      5       H  n[        U R                  5      v   M     g7f)zICreate an iterator that yields indefinitely from the underlying iterator.N)ranger3   nextr*   )r+   _s     r/   r)   InfiniteDataLoader.__iter__J   s'     s4y!At}}%% "s   46c                    [        U R                  S5      (       d  gU R                  R                   H*  nUR                  5       (       d  M  UR	                  5         M,     U R                  R                  5         g! [         a     gf = f)zKEnsure that workers are properly terminated when the dataloader is deleted._workersN)hasattrr*   r>   is_alive	terminate_shutdown_workers	Exception)r+   ws     r/   __del__InfiniteDataLoader.__del__O   sg    	4==*55]]++::<<KKM , MM++- 		s   A= ,A= .A= =
B
	B
c                .    U R                  5       U l        g)zIReset the iterator to allow modifications to the dataset during training.N)_get_iteratorr*   r5   s    r/   resetInfiniteDataLoader.reset[   s    **,r1   )r*   )r,   r   r-   r   )returnintrK   r   )__name__
__module____qualname____firstlineno____doc__r%   r6   r)   rE   rI   __static_attributes____classcell__)r.   s   @r/   r   r   %   s&    0+/&

- -r1   r   c                  ,    \ rS rSrSrSS jrSS jrSrg)	r(   `   a  
Sampler that repeats forever for infinite iteration.

This sampler wraps another sampler and yields its contents indefinitely, allowing for infinite iteration
over a dataset without recreating the sampler.

Attributes:
    sampler (Dataset.sampler): The sampler to repeat.
c                    Xl         g)zDInitialize the _RepeatSampler with a sampler to repeat indefinitely.Nr4   )r+   r4   s     r/   r%   _RepeatSampler.__init__k   s    r1   c              #  N   #     [        U R                  5       Sh  vN   M   N7f)z=Iterate over the sampler indefinitely, yielding its contents.N)iterr4   r5   s    r/   r)   _RepeatSampler.__iter__o   s"     DLL))) )s   %#%rX   N)r4   r   rM   )rN   rO   rP   rQ   rR   r%   r)   rS    r1   r/   r(   r(   `   s    *r1   r(   c                  :    \ rS rSrSrS
S jrS rS rS rS r	S	r
g)ContiguousDistributedSampleru   a  
Distributed sampler that assigns contiguous batch-aligned chunks of the dataset to each GPU.

Unlike PyTorch's DistributedSampler which distributes samples in a round-robin fashion (GPU 0 gets indices
[0,2,4,...], GPU 1 gets [1,3,5,...]), this sampler gives each GPU contiguous batches of the dataset
(GPU 0 gets batches [0,1,2,...], GPU 1 gets batches [k,k+1,...], etc.). This preserves any ordering or
grouping in the original dataset, which is critical when samples are organized by similarity (e.g., images
sorted by size to enable efficient batching without padding when using rect=True).

The sampler handles uneven batch counts by distributing remainder batches to the first few ranks, ensuring
all samples are covered exactly once across all GPUs.

Args:
    dataset (torch.utils.data.Dataset): Dataset to sample from. Must implement __len__.
    num_replicas (int, optional): Number of distributed processes. Defaults to world size.
    batch_size (int, optional): Batch size used by dataloader. Defaults to dataset batch size.
    rank (int, optional): Rank of current process. Defaults to current rank.
    shuffle (bool, optional): Whether to shuffle indices within each rank's chunk. Defaults to False.
        When True, shuffling is deterministic and controlled by set_epoch() for reproducibility.

Example:
    >>> # For validation with size-grouped images
    >>> sampler = ContiguousDistributedSampler(val_dataset, batch_size=32, shuffle=False)
    >>> loader = DataLoader(val_dataset, batch_size=32, sampler=sampler)
    >>> # For training with shuffling
    >>> sampler = ContiguousDistributedSampler(train_dataset, batch_size=32, shuffle=True)
    >>> for epoch in range(num_epochs):
    ...     sampler.set_epoch(epoch)
    ...     for batch in loader:
    ...         ...
Nc                   Uc1  [         R                  " 5       (       a  [         R                  " 5       OSnUc1  [         R                  " 5       (       a  [         R                  " 5       OSnUc  [	        USS5      nXl        X l        X0l        X@l        SU l	        XPl
        [        U5      U l        [        R                  " U R                  U R                  -  5      U l        g)zHInitialize the sampler with dataset and distributed training parameters.N   r   
batch_size)distis_initializedget_world_sizeget_rankgetattrdatasetnum_replicasrc   rankepochshuffler3   
total_sizemathceilnum_batches)r+   ri   rj   rc   rk   rm   s         r/   r%   %ContiguousDistributedSampler.__init__   s    484G4G4I4I4..0qL<&*&9&9&;&;4==?D ,:J($	
g,99T__t%FGr1   c                L   U R                   U R                  -  nU R                   U R                  -  nXR                  U:  a  SOS-   nU R                  U-  [        U R                  U5      -   nXC-   nX@R                  -  n[        XPR                  -  U R
                  5      nXg4$ )z9Calculate the start and end sample indices for this rank.rb   r   )rq   rj   rk   minrc   rn   )r+   batches_per_rank_base	remainderbatches_for_this_rankstart_batch	end_batch	start_idxend_idxs           r/   _get_rank_indices.ContiguousDistributedSampler._get_rank_indices   s     !% 0 0D4E4E E$$t'8'88	 !6ii)>SYZ [ ii"77#dii:SS7	  //1	i//14??C!!r1   c                l   U R                  5       u  p[        [        X5      5      nU R                  (       an  [        R
                  " 5       nUR                  U R                  5        [        R                  " [        U5      US9R                  5        Vs/ s H  oSU   PM	     nn[        U5      $ s  snf )zAGenerate indices for this rank's contiguous chunk of the dataset.)	generator)r|   listr9   rm   torch	Generatormanual_seedrl   randpermr3   tolistr[   )r+   rz   r{   indicesgis         r/   r)   %ContiguousDistributedSampler.__iter__   s    !335	uY01<<!AMM$**%+0>>#g,RS+T+[+[+]^+]aqz+]G^G} _s   B1c                .    U R                  5       u  pX!-
  $ )z2Return the number of samples in this rank's chunk.)r|   )r+   rz   r{   s      r/   r6   $ContiguousDistributedSampler.__len__   s    !335	""r1   c                    Xl         g)z
Set the epoch for this sampler to ensure different shuffling patterns across epochs.

Args:
    epoch (int): Epoch number to use as the random seed for shuffling.
N)rl   )r+   rl   s     r/   	set_epoch&ContiguousDistributedSampler.set_epoch   s	     
r1   )rc   ri   rl   rq   rj   rk   rm   rn   )NNNF)rN   rO   rP   rQ   rR   r%   r|   r)   r6   r   rS   r]   r1   r/   r_   r_   u   s"    @H$"&
#
r1   r_   c                    [         R                  " 5       S-  n[        R                  R	                  U5        [        R                  " U5        g)zGSet dataloader worker seed for reproducibility across worker processes.l        N)r   initial_seednprandomseed)	worker_idworker_seeds     r/   seed_workerr      s1    $$&.KIINN;
KKr1   c                T   U(       a  [         O[        nU" UU R                  UUS:H  U U R                  =(       d    UU R                  =(       d    SU R
                  =(       d    SUUS:X  a  SOS[        U S35      U R                  U R                  UUS:X  a  U R                  S9$ SS9$ )	zBBuild and return a YOLO dataset based on configuration parameters.trainNF              ?:       ?)img_pathimgszrc   augmenthyprectcache
single_clsstridepadprefixtaskclassesdatafraction)
r   r   r   r   r   r   r   r   r   r   )	cfgr   batchr   moder   r   multi_modalri   s	            r/   build_yolo_datasetr      s     (3#GiiXXii4>>*U7?C4&$XX!%  7: r1   c           	     x   [        S0 SU_SU_SU_SU R                  _SU_SUS:H  _SU _S	U R                  =(       d    U_S
U R                  =(       d    S_SU R                  =(       d    S_SU_SUS:X  a  SOS_S[        U S35      _SU R                  _SU R                  _SUS:X  a  U R                  _6$ S_6$ )zFBuild and return a GroundingDataset based on configuration parameters.r   	json_filemax_samplesr   rc   r   r   r   r   r   Nr   Fr   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   s           r/   build_groundingr      s        ii	
    XX ii4 >>*U  7?C 4&$ XX   "&!   7:! r1   c                (   [        U[        U 5      5      n[        R                  R	                  5       n[        [
        R                  " 5       [        US5      -  U5      nUS:X  a  SO%U(       a  [        R                  " XS9O
[        U 5      n	[        R                  " 5       n
U
R                  S[        -   5        [        U UU=(       a    U	SL UU	US:  a  SOSUS:  =(       a    U[        U SS5      [         U
U=(       a    [        U 5      U-  S:g  S	9$ )
a0  
Create and return an InfiniteDataLoader or DataLoader for training or validation.

Args:
    dataset (Dataset): Dataset to load data from.
    batch (int): Batch size for the dataloader.
    workers (int): Number of worker threads for loading data.
    shuffle (bool, optional): Whether to shuffle the dataset.
    rank (int, optional): Process rank in distributed training. -1 for single-GPU training.
    drop_last (bool, optional): Whether to drop the last incomplete batch.
    pin_memory (bool, optional): Whether to use pinned memory for dataloader.

Returns:
    (InfiniteDataLoader): A dataloader that can be used for training or validation.

Examples:
    Create a dataloader for training
    >>> dataset = YOLODataset(...)
    >>> dataloader = build_dataloader(dataset, batch=16, workers=4, shuffle=True)
rb   N)rm   l   UU*UU* r      
collate_fn)ri   rc   rm   num_workersr4   r!   
pin_memoryr   worker_init_fnr   	drop_last)rt   r3   r   cudadevice_countos	cpu_countmaxr
   DistributedSamplerr_   r   r   r   r   rh   r   )ri   r   workersrm   rk   r   r   ndnwr4   r   s              r/   build_dataloaderr     s    : s7|$E		 	 	"B	R\\^s2qz)7	3B 2: 	  ++GE)'2  !I-45+GtO!V6(j7L$7"9Gu 4 9 r1   c                (   Su  pp4n[        U [        [        [        45      (       a  [        U 5      n U R	                  5       nUR                  S5      nU(       a  [        U5      R                  OUR                  S5      S   [        [        -  ;   nU R                  5       =(       d(    U R                  S5      =(       d    U=(       a    U(       + nUS:H  nU(       a  U(       a  [        U 5      n O[        U [        5      (       a  SnO[        U [        [         45      (       a  [#        U 5      n SnO_[        U [$        R$                  [&        R(                  45      (       a  SnO-[        U [*        R,                  5      (       a  SnO[/        S5      eXX#XE4$ )	aT  
Check the type of input source and return corresponding flag values.

Args:
    source (str | int | Path | list | tuple | np.ndarray | PIL.Image | torch.Tensor): The input source to check.

Returns:
    source (str | int | Path | list | tuple | np.ndarray | PIL.Image | torch.Tensor): The processed source.
    webcam (bool): Whether the source is a webcam.
    screenshot (bool): Whether the source is a screenshot.
    from_img (bool): Whether the source is an image or list of images.
    in_memory (bool): Whether the source is an in-memory object.
    tensor (bool): Whether the source is a torch.Tensor.

Examples:
    Check a file path source
    >>> source, webcam, screenshot, from_img, in_memory, tensor = check_source("image.jpg")

    Check a webcam source
    >>> source, webcam, screenshot, from_img, in_memory, tensor = check_source(0)
)FFFFF)zhttps://zhttp://zrtsp://zrtmp://ztcp://.r   z.streamsscreenTzZUnsupported image type. For supported types see https://docs.ultralytics.com/modes/predict)
isinstancestrrL   r   lower
startswithr   path
rpartitionr   r   	isnumericendswithr   r   r   tupler   r   r   ndarrayr   Tensor	TypeError)	sourcewebcam
screenshotfrom_img	in_memorytensorsource_loweris_urlis_files	            r/   check_sourcer   S  sC   , 7X3FV&3T*++V||~(()`a288L)..lVVWZ[\^_+%
 !!#^vz'B^vG]V]R]!X-
g'F	FG	$	$		FT5M	*	*v&	FU[["**5	6	6	FELL	)	)tuu:BBr1   c                2   [        U 5      u  ppgpU(       a  U R                  O[        XVXy5      n
U	(       a  [        U 5      nOHU(       a  U nO>U(       a  [	        XX4S9nO,U(       a
  [        XS9nOU(       a
  [        XS9nO
[        XX$S9n[        USU
5        U$ )a#  
Load an inference source for object detection and apply necessary transformations.

Args:
    source (str | Path | torch.Tensor | PIL.Image | np.ndarray, optional): The input source for inference.
    batch (int, optional): Batch size for dataloaders.
    vid_stride (int, optional): The frame interval for video sources.
    buffer (bool, optional): Whether stream frames will be buffered.
    channels (int, optional): The number of input channels for the model.

Returns:
    (Dataset): A dataset object for the specified input source with attached source_type attribute.

Examples:
    Load an image source for inference
    >>> dataset = load_inference_source("image.jpg", batch=1)

    Load a video stream source
    >>> dataset = load_inference_source("rtsp://example.com/stream", vid_stride=2)
)
vid_stridebufferchannels)r   )r   r   r   source_type)	r   r   r   r   r   r   r   r   setattr)r   r   r   r   r   streamr   r   r   r   r   ri   s               r/   load_inference_sourcer     s    * ?K6>R;FJ)(1&$${6W_7hK V$		fF^	!&<	!&<%fjd G]K0Nr1   )r   rL   )r   F    F)r   r   r   r   r   rL   r   zdict[str, Any]r   r   r   boolr   rL   r   r   )r   Fr   P   )r   r   r   r   r   r   r   rL   r   r   r   r   r   rL   r   rL   )Tr   FT)r   rL   r   rL   rm   r   rk   rL   r   r   r   r   )Nrb   rb   F   )r   rL   r   rL   r   r   r   rL   )=
__future__r   ro   r   r   collections.abcr   pathlibr   typingr   urllib.parser   numpyr   r   torch.distributedr
   rd   PILr   torch.utils.datar	   ultralytics.cfgr   ultralytics.data.datasetr   r   r   ultralytics.data.loadersr   r   r   r   r   r   r   r   ultralytics.data.utilsr   r   ultralytics.utilsr   r   ultralytics.utils.checksr   ultralytics.utils.torch_utilsr   
DataLoaderr   r(   utilsr   Samplerr_   r   r   r   r   r   r   r]   r1   r/   <module>r      s   #  	  $   !      4 3 Y Y	 	 	 < , / 38-.. 8-v* **^5;;#3#3#;#; ^B 	   	
    H 	   	
    F 55 5 	5
 5 5 5p.Cb)r1   