
    |h7                     *   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	 d dl
Z
d dlmZmZ d dlmZ d dlmZ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mZ  G d de      Z G d de      Z  G d dee      Z! G d de e!      Z" G d de!      Z#y)    N)copydeepcopy)Path)DictListOptionalUnion)YOLOConcatDatasetbuild_yolo_dataset)LoadVisualPrompt)DetectionTrainerDetectionValidator)
YOLOEModel)DEFAULT_CFGLOGGERRANK)de_parallel   )WorldTrainerFromScratch   )YOLOEDetectValidatorc                   f     e Zd ZdZeddfdee   f fdZddefdZ	d Z
dded	ed
ee   fdZ xZS )YOLOETrainerae  
    A trainer class for YOLOE object detection models.

    This class extends DetectionTrainer to provide specialized training functionality for YOLOE models,
    including custom model initialization, validation, and dataset building with multi-modal support.

    Attributes:
        loss_names (tuple): Names of loss components used during training.

    Methods:
        get_model: Initialize and return a YOLOEModel with specified configuration.
        get_validator: Return a YOLOEDetectValidator for model validation.
        build_dataset: Build YOLO dataset with multi-modal support for training.
    N	overridesc                 :    |i }d|d<   t         |   |||       y)aQ  
        Initialize the YOLOE Trainer with specified configurations.

        This method sets up the YOLOE trainer with the provided configuration and overrides, initializing
        the training environment, model, and callbacks for YOLOE object detection training.

        Args:
            cfg (dict): Configuration dictionary with default training settings from DEFAULT_CFG.
            overrides (dict, optional): Dictionary of parameter overrides for the default configuration.
            _callbacks (list, optional): List of callback functions to be applied during training.
        NFoverlap_mask)super__init__)selfcfgr   
_callbacks	__class__s       b/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/models/yolo/yoloe/train.pyr   zYOLOETrainer.__init__%   s+     I$)	.!i4    verbosec                     t        t        |t              r|d   n|| j                  d   t	        | j                  d   d      |xr	 t
        dk(        }|r|j                  |       |S )aX  
        Return a YOLOEModel initialized with the specified configuration and weights.

        Args:
            cfg (dict | str, optional): Model configuration. Can be a dictionary containing a 'yaml_file' key,
                a direct path to a YAML file, or None to use default configuration.
            weights (str | Path, optional): Path to pretrained weights file to load into the model.
            verbose (bool): Whether to display model information during initialization.

        Returns:
            (YOLOEModel): The initialized YOLOE model.

        Notes:
            - The number of classes (nc) is hard-coded to a maximum of 80 following the official configuration.
            - The nc parameter here represents the maximum number of different text samples in one image,
              rather than the actual number of classes.
        	yaml_filechannelsncP   chr)   r%   )r   
isinstancedictdataminr   load)r   r    weightsr%   models        r#   	get_modelzYOLOETrainer.get_model6   sa    (  *3 5C3yy$499T?B'*
	
 JJwr$   c                     d| _         t        | j                  | j                  t	        | j
                        | j                        S )z9Return a YOLOEDetectValidator for YOLOE model validation.boxclsdflsave_dirargsr!   )
loss_namesr   test_loaderr<   r   r=   	callbacksr   s    r#   get_validatorzYOLOETrainer.get_validatorU   s8    -#t}}4		?W[WeWe
 	
r$   img_pathmodebatchc                     t        t        | j                  r-t        | j                        j                  j                         nd      d      }t        | j                  ||| j                  ||dk(  ||dk(        S )a  
        Build YOLO Dataset.

        Args:
            img_path (str): Path to the folder containing images.
            mode (str): 'train' mode or 'val' mode, users are able to customize different augmentations for each mode.
            batch (int, optional): Size of batches, this is for rectangular training.

        Returns:
            (Dataset): YOLO dataset configured for training or validation.
        r       valtrain)rD   rectstridemulti_modal)maxintr4   r   rK   r   r=   r0   )r   rC   rD   rE   gss        r#   build_datasetzYOLOETrainer.build_dataset\   sh     TZZ[,33779QOQST!IIx		45=Y[imqxix
 	
r$   NNTrI   N)__name__
__module____qualname____doc__r   r   r   r   boolr5   rB   strrN   rP   __classcell__r"   s   @r#   r   r      sR     'DUY 58D> 5" >

c 
 
xPS} 
r$   r   c                       e Zd ZdZddefdZy)YOLOEPETraineraM  
    Fine-tune YOLOE model using linear probing approach.

    This trainer freezes most model layers and only trains specific projection layers for efficient
    fine-tuning on new datasets while preserving pretrained features.

    Methods:
        get_model: Initialize YOLOEModel with frozen layers except projection layers.
    Nr%   c                    t        t        |t              r|d   n|| j                  d   | j                  d   |xr	 t        dk(        }|j
                  d   `|J d       |r|j                  |       |j                          t        | j                  d   j                               }|j                  |      }|j                  ||       |j
                  d   j                  |j                         t        |j
                  d   j                   d   d	         j#                  d
      |j
                  d   j                   d   d	<   t        |j
                  d   j                   d   d	         j#                  d
      |j
                  d   j                   d   d	<   t        |j
                  d   j                   d	   d	         j#                  d
      |j
                  d   j                   d	   d	<   |`|j%                          |S )a  
        Return YOLOEModel initialized with specified config and weights.

        Args:
            cfg (dict | str, optional): Model configuration.
            weights (str, optional): Path to pretrained weights.
            verbose (bool): Whether to display model information.

        Returns:
            (YOLOEModel): Initialized model with frozen layers except for specific projection layers.
        r'   r(   r)   r+   r,   z7Pretrained weights must be provided for linear probing.namesr   r   Tr   )r   r.   r/   r0   r   r4   savper2   evallistvaluesget_text_peset_classesfuseper   cv3requires_grad_rI   )r   r    r3   r%   r4   r^   tpes          r#   r5   zYOLOEPETrainer.get_modely   s     *3 5C3yy$yy*
	
 KKO!"]$]]"JJw

TYYw'..01 &%%BUXX&$,U[[_-@-@-CA-F$G$V$VW[$\BAq!$,U[[_-@-@-CA-F$G$V$VW[$\BAq!$,U[[_-@-@-CA-F$G$V$VW[$\BAq!Hr$   rQ   )rS   rT   rU   rV   rW   r5    r$   r#   r\   r\   n   s    ( (r$   r\   c                   \    e Zd ZdZddeee   ef   dedee   fdZ	d Z
dee   ded	efd
Zy)YOLOETrainerFromScratcha  
    Train YOLOE models from scratch with text embedding support.

    This trainer combines YOLOE training capabilities with world training features, enabling
    training from scratch with text embeddings and grounding datasets.

    Methods:
        build_dataset: Build datasets for training with grounding support.
        preprocess_batch: Process batches with text features.
        generate_text_embeddings: Generate and cache text embeddings for training.
    NrC   rD   rE   c                 2    t        j                  | |||      S )a  
        Build YOLO Dataset for training or validation.

        This method constructs appropriate datasets based on the mode and input paths, handling both
        standard YOLO datasets and grounding datasets with different formats.

        Args:
            img_path (List[str] | str): Path to the folder containing images or list of paths.
            mode (str): 'train' mode or 'val' mode, allowing customized augmentations for each mode.
            batch (int, optional): Size of batches, used for rectangular training/validation.

        Returns:
            (YOLOConcatDataset | Dataset): The constructed dataset for training or validation.
        )r   rP   )r   rC   rD   rE   s       r#   rP   z%YOLOETrainerFromScratch.build_dataset   s     '44T8T5QQr$   c                 l   t        j                  | |      }t        t        j                  |d          }t        j                  |D cg c]  }| j                  |    c}      j                  | j                        }|j                  t        |d         d|j                  d         }||d<   |S c c}w )zKProcess batch for training, moving text features to the appropriate device.textsr+   	txt_feats)r   preprocess_batchra   	itertoolschaintorchstacktext_embeddingstodevicereshapelenshape)r   rE   ro   textrp   s        r#   rq   z(YOLOETrainerFromScratch.preprocess_batch   s     11$>Y__eGn56KK N!5!5d!; NORRSWS^S^_	%%c%.&92yr?RS	&k !Os   B1ro   	cache_dirc                 P   d}|d|j                  dd      j                  dd       dz  }|j                         rat        j                  d| d       t	        j
                  || j                  	      }t        |j                               t        |      k(  r|S t        j                  d
| d       | j                  J t        | j                        j                  ||dd      }t        t        ||j                  d                  }t	        j                  ||       |S )ak  
        Generate text embeddings for a list of text samples.

        Args:
            texts (List[str]): List of text samples to encode.
            batch (int): Batch size for processing.
            cache_dir (Path): Directory to save/load cached embeddings.

        Returns:
            (dict): Dictionary mapping text samples to their embeddings.
        zmobileclip:blttext_embeddings_:_/z.ptzReading existed cache from '')map_locationzCaching text embeddings to 'TF)without_reprtacache_clip_modelr   )replaceexistsr   infort   r2   rx   sortedkeysr4   r   rc   r/   zipsqueezesave)r   ro   rE   r}   r4   
cache_pathtxt_maprp   s           r#   generate_text_embeddingsz0YOLOETrainerFromScratch.generate_text_embeddings   s    !#3EMM#s4K4S4STWY\4]3^^a!bb
KK6zl!DEjj$++FGglln%62:,a@Azz%%%

+77uUYlq7r	s5)"3"3A"678

7J'r$   rR   )rS   rT   rU   rV   r	   r   rX   r   rN   rP   rq   r   r   rj   r$   r#   rl   rl      s]    
ReDIsN&; R3 RYabeYf R"d3i  PT r$   rl   c                   (    e Zd ZdZd Zd ZdefdZy)YOLOEPEFreeTrainera  
    Train prompt-free YOLOE model.

    This trainer combines linear probing capabilities with from-scratch training for prompt-free
    YOLOE models that don't require text prompts during inference.

    Methods:
        get_validator: Return standard DetectionValidator for validation.
        preprocess_batch: Preprocess batches without text features.
        set_text_embeddings: Set text embeddings for datasets (no-op for prompt-free).
    c                     d| _         t        | j                  | j                  t	        | j
                        | j                        S )z6Return a DetectionValidator for YOLO model validation.r7   r;   )r>   r   r?   r<   r   r=   r@   rA   s    r#   rB   z YOLOEPEFreeTrainer.get_validator   s8    -!t}}4		?W[WeWe
 	
r$   c                 2    t        j                  | |      }|S )z_Preprocess a batch of images for YOLOE training, adjusting formatting and dimensions as needed.)r   rq   )r   rE   s     r#   rq   z#YOLOEPEFreeTrainer.preprocess_batch   s     11$>r$   rE   c                      y)a8  
        Set text embeddings for datasets to accelerate training by caching category names.

        This method collects unique category names from all datasets, generates text embeddings for them,
        and caches these embeddings to improve training efficiency. The embeddings are stored in a file
        in the parent directory of the first dataset's image path.

        Args:
            datasets (List[Dataset]): List of datasets containing category names to process.
            batch (int): Batch size for processing text embeddings.

        Notes:
            The method creates a dictionary mapping text samples to their embeddings and stores it
            at the path specified by 'cache_path'. If the cache file already exists, it will be loaded
            instead of regenerating the embeddings.
        Nrj   )r   datasetsrE   s      r#   set_text_embeddingsz&YOLOEPEFreeTrainer.set_text_embeddings   s    " 	r$   N)rS   rT   rU   rV   rB   rq   rN   r   rj   r$   r#   r   r      s    


3 r$   r   c                   \     e Zd ZdZddeee   ef   dedee   f fdZ	 fdZ
 fdZ xZS )	YOLOEVPTrainera{  
    Train YOLOE model with visual prompts.

    This trainer extends YOLOETrainerFromScratch to support visual prompt-based training,
    where visual cues are provided alongside images to guide the detection process.

    Methods:
        build_dataset: Build dataset with visual prompt loading transforms.
        preprocess_batch: Preprocess batches with visual prompts.
    rC   rD   rE   c                     t         |   |||      }t        |t              r6|j                  D ]%  }|j
                  j                  t                      ' |S |j
                  j                  t                      |S )a	  
        Build YOLO Dataset for training or validation with visual prompts.

        Args:
            img_path (List[str] | str): Path to the folder containing images or list of paths.
            mode (str): 'train' mode or 'val' mode, allowing customized augmentations for each mode.
            batch (int, optional): Size of batches, used for rectangular training/validation.

        Returns:
            (Dataset): YOLO dataset configured for training or validation, with visual prompts for training mode.
        )r   rP   r.   r
   r   
transformsappendr   )r   rC   rD   rE   datasetdr"   s         r#   rP   zYOLOEVPTrainer.build_dataset   st     ''$>g01%% 8##$4$678  %%&6&89r$   c                 j   t         |           t        | j                  j                  t
              rI| j                  j                  j                  D ]%  }|j                  j                  t                      ' y| j                  j                  j                  j                  t                      y)zPClose mosaic augmentation and add visual prompt loading to the training dataset.N)
r   _close_dataloader_mosaicr.   train_loaderr   r
   r   r   r   r   )r   r   r"   s     r#   r   z'YOLOEVPTrainer._close_dataloader_mosaic4  s    (*d''//1BC&&..77 8##$4$678 %%00778H8JKr$   c                 h    t         |   |      }|d   j                  | j                        |d<   |S )zaPreprocess a batch of images for YOLOE training, moving visual prompts to the appropriate device.visuals)r   rq   rw   rx   )r   rE   r"   s     r#   rq   zYOLOEVPTrainer.preprocess_batch=  s5    (/ +..t{{;ir$   rR   )rS   rT   rU   rV   r	   r   rX   r   rN   rP   r   rq   rY   rZ   s   @r#   r   r     sF    	eDIsN&; 3 YabeYf (L r$   r   )$rr   r   r   pathlibr   typingr   r   r   r	   rt   ultralytics.datar
   r   ultralytics.data.augmentr   ultralytics.models.yolo.detectr   r   ultralytics.nn.tasksr   ultralytics.utilsr   r   r   ultralytics.utils.torch_utilsr   world.train_worldr   rH   r   r   r\   rl   r   r   rj   r$   r#   <module>r      s       . .  B 5 O + 7 7 5 7 %V
# V
r3% 3l@l,C @F*)@ *Z-, -r$   