§
    l¬¸j˜0  ã                  óæ   — d dl mZ d dlZd dlZd dlmZ d dlmZ d dlZd dl	Z	d dl	m
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mZmZ d dlmZ d dlmZmZ d dlmZmZ  G d„ de¦  «        Z dS )é    )ÚannotationsN)Úcopy)ÚAny)Únn)Úbuild_dataloaderÚbuild_yolo_dataset)ÚBaseTrainer)Úyolo)ÚDetectionModel)ÚDEFAULT_CFGÚLOGGERÚRANK)Úoverride_configs)Úplot_imagesÚplot_labels)Útorch_distributed_zero_firstÚunwrap_modelc                  óž   ‡ — e Zd ZdZeddfd.ˆ fd„Zd/d0d„Zd1d2d„Zd3d„Zd„ Z	d„ Z
d„ Zd„ Zd„ Zd4d5d$„Zd%„ Zˆ fd&„Zd'„ Zd6d+„Zd,„ Zˆ fd-„Zˆ xZS )7ÚDetectionTraineraZ  A class extending the BaseTrainer class for training based on a detection model.

    This trainer specializes in object detection tasks, handling the specific requirements for training YOLO models for
    object detection including dataset building, data loading, preprocessing, and model configuration.

    Attributes:
        model (DetectionModel): The YOLO detection model being trained.
        data (dict): Dictionary containing dataset information including class names and number of classes.
        loss_names (tuple): Names of the loss components, derived from the loss dict returned by the criterion.

    Methods:
        build_dataset: Build YOLO dataset for training or validation.
        get_dataloader: Construct and return dataloader for the specified mode.
        preprocess_batch: Preprocess a batch of images by scaling and converting to float.
        set_model_attributes: Set model attributes based on dataset information.
        get_model: Return a YOLO detection model.
        get_validator: Return a validator for model evaluation.
        progress_string: Return a formatted string of training progress.
        plot_training_samples: Plot training samples with their annotations.
        plot_training_labels: Create a labeled training plot of the YOLO model.
        auto_batch: Calculate optimal batch size based on model memory requirements.

    Examples:
        >>> from ultralytics.models.yolo.detect import DetectionTrainer
        >>> args = dict(model="yolo26n.pt", data="coco8.yaml", epochs=3)
        >>> trainer = DetectionTrainer(overrides=args)
        >>> trainer.train()
    NÚ	overridesúdict[str, Any] | NoneÚ
_callbacksúdict | Nonec                óN   •— t          ¦   «                              |||¦  «         dS )a�  Initialize a DetectionTrainer object for training YOLO object detection models.

        Args:
            cfg (dict, optional): Default configuration dictionary containing training parameters.
            overrides (dict, optional): Dictionary of parameter overrides for the default configuration.
            _callbacks (dict, optional): Dictionary of callback functions to be executed during training.
        N)ÚsuperÚ__init__)ÚselfÚcfgr   r   Ú	__class__s       €út/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/ultralytics/models/yolo/detect/train.pyr   zDetectionTrainer.__init__6   s'   ø€ õ 	‰Œ×Ò˜˜i¨Ñ4Ô4Ð4Ð4Ð4ó    ÚtrainÚimg_pathÚstrÚmodeÚbatchú
int | Nonec           	     óÖ   — t          t          t          | j        ¦  «        j                              ¦   «         ¦  «        d¦  «        }t          | j        ||| j        ||dk    |¬¦  «        S )a¬  Build YOLO Dataset for training or validation.

        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 'rect' mode.

        Returns:
            (Dataset): YOLO dataset object configured for the specified mode.
        é    Úval)r%   ÚrectÚstride)ÚmaxÚintr   Úmodelr,   r   ÚargsÚdata)r   r#   r%   r&   Úgss        r    Úbuild_datasetzDetectionTrainer.build_dataset@   s]   € õ ••\ $¤*Ñ-Ô-Ô4×8Ò8Ñ:Ô:Ñ;Ô;¸RÑ@Ô@ˆÝ! $¤)¨X°u¸d¼iÈdÐY]ÐafÒYfÐoqÐrÑrÔrÐrr!   é   r   Údataset_pathÚ
batch_sizer.   Úrankc           	     óä  — |dv sJ d|› d�¦   «         ‚t          |¦  «        5  |                      |||¦  «        }ddd¦  «         n# 1 swxY w Y   |dk    }t          |dd¦  «        r@|r>t          j        |j        |j        d         k    ¦  «        st          j        d	¦  «         d}t          |||dk    r| j	        j
        n| j	        j
        d
z  ||| j	        j        o|dk    | j        ¬¦  «        S )až  Construct and return dataloader for the specified mode.

        Args:
            dataset_path (str): Path to the dataset.
            batch_size (int): Number of images per batch.
            rank (int): Process rank for distributed training.
            mode (str): 'train' for training dataloader, 'val' for validation dataloader.

        Returns:
            (DataLoader): PyTorch dataloader object.
        >   r*   r"   z#Mode must be 'train' or 'val', not ú.Nr"   r+   Fr   zJ'rect=True' is incompatible with DataLoader shuffle, setting shuffle=Falseé   )r&   ÚworkersÚshuffler7   Ú	drop_lastÚdevice)r   r3   ÚgetattrÚnpÚallÚbatch_shapesr   Úwarningr   r0   r;   Úcompiler>   )r   r5   r6   r7   r%   Údatasetr<   s          r    Úget_dataloaderzDetectionTrainer.get_dataloaderN   sk  € ð Ð'Ð'Ð'Ð'Ð)VÈtÐ)VÐ)VÐ)VÑ'Ô'Ð'Ý)¨$Ñ/Ô/ð 	Ið 	IØ×(Ò(¨°t¸ZÑHÔHˆGð	Ið 	Ið 	Iñ 	Iô 	Ið 	Ið 	Ið 	Ið 	Ið 	Ið 	Iøøøð 	Ið 	Ið 	Ið 	Ià˜'’/ˆÝ�7˜F EÑ*Ô*ð 	¨wð 	½r¼vÀgÔFZÐ^eÔ^rÐstÔ^uÒFuÑ?vÔ?vð 	ÝŒNÐgÑhÔhÐhØˆGÝØØØ)-°ª¨�D”IÔ%Ð%¸d¼iÔ>OÐRSÑ>SØØØ”iÔ'Ð;¨D°GªOØ”;ð
ñ 
ô 
ð 	
s   ¢AÁA
ÁA
ÚdictÚreturnc           
     ó&  ‡ ‡— |                      ¦   «         D ]J\  }}t          |t          j        ¦  «        r+|                     ‰ j        ‰ j        j        dv¬¦  «        ||<   ŒK|d                              ¦   «         dz  |d<   ‰ j        j	        dk    rÿ|d         }t          j        t          ‰ j        t          ‰ j        j        d‰ j        j	        z
  z  ¦  «        ¦  «        t          ‰ j        j        d‰ j        j	        z   z  ‰ j        z   ¦  «        ¦  «        ‰ j        z  ‰ j        z  }|t          |j        dd…         ¦  «        z  Š‰d	k    r?ˆ ˆfd
„|j        dd…         D ¦   «         }t"          j                             ||dd¬¦  «        }||d<   |S )z÷Preprocess a batch of images by scaling and converting to float.

        Args:
            batch (dict): Dictionary containing batch data with 'img' tensor.

        Returns:
            (dict): Preprocessed batch with normalized images.
        >   ÚcpuÚmps)Únon_blockingÚimgéÿ   ç        ç      ð?r:   Né   c                ó^   •— g | ])}t          j        |‰z  ‰j        z  ¦  «        ‰j        z  ‘Œ*S © )ÚmathÚceilr,   )Ú.0Úxr   Úsfs     €€r    ú
<listcomp>z5DetectionTrainer.preprocess_batch.<locals>.<listcomp>„   sB   ø€ ð ð ð ØFG•D”I˜a "™f t¤{Ñ2Ñ3Ô3°d´kÑAðð ð r!   ÚbilinearF)Úsizer%   Úalign_corners)ÚitemsÚ
isinstanceÚtorchÚTensorÚtor>   ÚtypeÚfloatr0   Úmulti_scaleÚrandomÚ	randranger-   r,   r.   ÚimgszÚshaper   Ú
functionalÚinterpolate)r   r&   ÚkÚvÚimgsÚszÚnsrX   s   `      @r    Úpreprocess_batchz!DetectionTrainer.preprocess_batchk   s¢  øø€ ð —K’K‘M”Mð 	bð 	b‰DˆAˆqÝ˜!�Uœ\Ñ*Ô*ð bØŸ4š4 ¤¸$¼+Ô:JÐR`Ð:`˜4ÑaÔa��a‘øØ˜U”|×)Ò)Ñ+Ô+¨cÑ1ˆˆe‰ØŒ9Ô  3Ò&Ð&Ø˜”<ˆDåÔ Ý˜œ¥S¨¬¬¸CÀ$Ä)ÔBWÑ<WÑ)XÑ%YÔ%YÑZÔZÝ˜œ	œ¨3°´Ô1FÑ+FÑGÈ$Ì+ÑUÑVÔVñô ð ”;ñ	ð
 ”+ñð ð •c˜$œ* Q R Rœ.Ñ)Ô)Ñ)ˆBØ�QŠwˆwðð ð ð ð ØKOÌ:ÐVWÐVXÐVXÌ>ðñ ô �õ ”}×0Ò0°¸BÀZÐ_dÐ0ÑeÔe�ØˆE�%‰LØˆr!   c                ó„   — | j         d         | j        _        | j         d         | j        _        | j        | j        _        dS )z2Set model attributes based on dataset information.ÚncÚnamesN)r1   r/   rr   rs   r0   ©r   s    r    Úset_model_attributesz%DetectionTrainer.set_model_attributes‹   s3   € ð œ	 $œˆŒ
ŒØœ9 WÔ-ˆŒ
ÔØœ)ˆŒ
Œˆˆr!   c                óŠ   — t          | j        dd¦  «        r,| j                             d¦  «        r| j        d         |_        |S )zOSet target dataset names before loading weights so cls heads can remap by name.Ú	cls_remapTrs   )r?   r0   r1   Úgetrs   )r   r/   s     r    Úset_model_names_for_loadz)DetectionTrainer.set_model_names_for_load•   s@   € å�4”9˜k¨4Ñ0Ô0ð 	-°T´Y·]²]À7Ñ5KÔ5Kð 	-Øœ) GÔ,ˆEŒKØˆr!   c                ó
  — t          j        d„ | j        j        j        D ¦   «         d¦  «        }t          j        |                     t          ¦  «        | j        d         ¬¦  «                             t           j	        ¦  «        S )zBReturn per-class instance counts from the training dataset labels.c                óB   — g | ]}|d                                ¦   «         ‘ŒS ©Úcls)Úflatten©rV   Úlbs     r    rY   z5DetectionTrainer.get_class_counts.<locals>.<listcomp>�   s(   € Ð!aÐ!aÐ!a¸" " U¤)×"3Ò"3Ñ"5Ô"5Ð!aÐ!aÐ!ar!   r   rr   )Ú	minlength)
r@   ÚconcatenateÚtrain_loaderrE   ÚlabelsÚbincountÚastyper.   r1   Úfloat32)r   Úclassess     r    Úget_class_countsz!DetectionTrainer.get_class_counts›   se   € å”.Ð!aÐ!aÀÔ@QÔ@YÔ@`Ð!aÑ!aÔ!aÐcdÑeÔeˆÝŒ{˜7Ÿ>š>­#Ñ.Ô.¸$¼)ÀD¼/ÐJÑJÔJ×QÒQÕRTÔR\Ñ]Ô]Ð]r!   c                óZ   — t          j        |dk    d|¦  «        }d|z  | j        j        z  S )zPConvert class counts to inverse-frequency weights raised to the power of cls_pw.r   rP   )r@   Úwherer0   Úcls_pw)r   Úclass_countss     r    Úcompute_class_weightsz&DetectionTrainer.compute_class_weights    s/   € å”x °Ò 1°3¸ÑEÔEˆØ�lÑ" t¤yÔ'7Ñ7Ð7r!   c                óz  — d| j         j        cxk    rdk    sn J d¦   «         ‚| j         j        dk    rdS |                      ¦   «         }|                     ¦   «         sdS |                      |¦  «        }||                     ¦   «         z  }t          | j        ¦  «        }t          |d¦  «        r|j	        }t          j        |¦  «                             | j        ¦  «        |_        t          j        d|j                             ¦   «                              ¦   «                              d¦  «        › �¦  «         dS )	aM  Compute and set class weights for handling class imbalance.

        Class weights are computed based on inverse class frequency in the training dataset,
        raised to the power of cls_pw (0 < cls_pw <= 1 dampens; values are restricted to the range [0, 1]).
        Final weights are normalized so their mean equals 1.0.
        r   rP   z"cls_pw must be in the range [0, 1]rO   NÚstudent_modelzClass weights: é   )r0   rŒ   r‰   ÚanyrŽ   Úmeanr   r/   Úhasattrr�   r_   Ú
from_numpyra   r>   Úclass_weightsr   ÚinforJ   ÚnumpyÚround)r   r�   Úweightsr/   s       r    Úset_class_weightsz"DetectionTrainer.set_class_weights¥   s/  € ð �D”IÔ$Ð+Ð+Ò+Ð+¨Ò+Ð+Ð+Ð+Ð+Ð-QÑ+Ô+Ð+ØŒ9Ô˜sÒ"Ð"ØˆFØ×,Ò,Ñ.Ô.ˆØ×ÒÑ!Ô!ð 	ØˆFØ×,Ò,¨\Ñ:Ô:ˆØ˜GŸLšL™NœNÑ*ˆÝ˜TœZÑ(Ô(ˆÝ�5˜/Ñ*Ô*ð 	(ØÔ'ˆEÝ#Ô.¨wÑ7Ô7×:Ò:¸4¼;ÑGÔGˆÔÝŒÐR eÔ&9×&=Ò&=Ñ&?Ô&?×&EÒ&EÑ&GÔ&G×&MÒ&MÈaÑ&PÔ&PÐRÐRÑSÔSÐSÐSÐSr!   Tr   ú
str | Nonerš   ÚverboseÚboolc           	     óÂ   — |                       t          || j        d         | j        d         |o
t          dk    ¬¦  «        ¦  «        }|r|                     |¦  «         |S )a=  Return a YOLO detection model.

        Args:
            cfg (str, optional): Path to model configuration file.
            weights (str, optional): Path to model weights.
            verbose (bool): Whether to display model information.

        Returns:
            (DetectionModel): YOLO detection model.
        rr   Úchannelséÿÿÿÿ)rr   Úchr�   )ry   r   r1   r   Úload)r   r   rš   r�   r/   s        r    Ú	get_modelzDetectionTrainer.get_modelº   sh   € ð ×-Ò-Ý˜3 4¤9¨T¤?°t´yÀÔ7LÐV]ÐVlÕbfÐjlÒblÐmÑmÔmñ
ô 
ˆð ð 	 Ø�JŠJ�wÑÔÐØˆr!   c                óŠ   — t           j                             | j        | j        t          | j        ¦  «        | j        ¬¦  «        S )z6Return a DetectionValidator for YOLO model validation.)Úsave_dirr0   r   )r
   ÚdetectÚDetectionValidatorÚtest_loaderr¦   r   r0   Ú	callbacksrt   s    r    Úget_validatorzDetectionTrainer.get_validatorÌ   s;   € åŒ{×-Ò-ØÔ t¤}½4ÀÄ	¹?¼?ÐW[ÔWeð .ñ 
ô 
ð 	
r!   c                óR  •— t          ¦   «                              ¦   «          | j        j        dv rw| j        j        | j        j        dœ}t          j        j	         
                    | j        |¦  «         t          | j        ¦  «                             | j        j        ¬¦  «         dS dS )zfBuild the training pipeline and align the default detection limit with observed dataset object counts.>   ÚobbÚposer§   Úsegment)r"   r*   )Úmax_detN)r   Ú_build_train_pipeliner0   Útaskrƒ   rE   r©   r
   r§   r¨   Ú_check_max_detr   r/   Úset_head_attrr°   )r   Údatasetsr   s     €r    r±   z&DetectionTrainer._build_train_pipelineÒ   s”   ø€ å‰Œ×%Ò%Ñ'Ô'Ð'ØŒ9Œ>ÐAÐAÐAØ!%Ô!2Ô!:À4ÔCSÔC[Ð\Ð\ˆHÝŒKÔ*×9Ò9¸$¼)ÀXÑNÔNÐNÝ˜œÑ$Ô$×2Ò2¸4¼9Ô;LÐ2ÑMÔMÐMÐMÐMð BÐAr!   c                ó^   — dddt          | j        ¦  «        z   z  z   ddg| j        ¢d‘d‘R z  S )z`Return a formatted string of training progress with epoch, GPU memory, loss, instances and size.ú
z%11sé   ÚEpochÚGPU_memÚ	InstancesÚSize)ÚlenÚ
loss_namesrt   s    r    Úprogress_stringz DetectionTrainer.progress_stringÚ   sX   € à�v ¥S¨¬Ñ%9Ô%9Ñ!9Ñ:Ñ:ØØð?
ð Œ_ð?
ð ð	?
ð
 ð?
ð ?
ñ 
ð 	
r!   údict[str, Any]ÚniÚNonec                óZ   — t          ||d         | j        d|› d�z  | j        ¬¦  «         dS )zÎPlot training samples with their annotations.

        Args:
            batch (dict[str, Any]): Dictionary containing batch data.
            ni (int): Batch index used for naming the output file.
        Úim_fileÚtrain_batchz.jpg)r„   ÚpathsÚfnameÚon_plotN)r   r¦   rÈ   )r   r&   rÁ   s      r    Úplot_training_samplesz&DetectionTrainer.plot_training_samplesä   sK   € õ 	ØØ˜	Ô"Ø”-Ð"8°Ð"8Ð"8Ð"8Ñ8Ø”Lð		
ñ 	
ô 	
ð 	
ð 	
ð 	
r!   c                ó4  — t          j        d„ | j        j        j        D ¦   «         d¦  «        }t          j        d„ | j        j        j        D ¦   «         d¦  «        }t          ||                     ¦   «         | j        d         | j        | j	        ¬¦  «         dS )z1Create a labeled training plot of the YOLO model.c                ó   — g | ]
}|d          ‘ŒS )ÚbboxesrS   r   s     r    rY   z9DetectionTrainer.plot_training_labels.<locals>.<listcomp>ô   s   € ÐXÐXÐX°  8¤ÐXÐXÐXr!   r   c                ó   — g | ]
}|d          ‘ŒS r|   rS   r   s     r    rY   z9DetectionTrainer.plot_training_labels.<locals>.<listcomp>õ   s   € ÐSÐSÐS¨B˜b œiÐSÐSÐSr!   rs   )rs   r¦   rÈ   N)
r@   r‚   rƒ   rE   r„   r   Úsqueezer1   r¦   rÈ   )r   Úboxesr}   s      r    Úplot_training_labelsz%DetectionTrainer.plot_training_labelsò   sŠ   € å”ÐXÐX°tÔ7HÔ7PÔ7WÐXÑXÔXÐZ[Ñ\Ô\ˆÝŒnÐSÐS°$Ô2CÔ2KÔ2RÐSÑSÔSÐUVÑWÔWˆÝ�E˜3Ÿ;š;™=œ=°´	¸'Ô0BÈTÌ]ÐdhÔdpÐqÑqÔqÐqÐqÐqr!   c                ó\  •— t          | j        ddi¬¦  «        5 | _        |                      | j        d         dd¬¦  «        }ddd¦  «         n# 1 swxY w Y   t	          d„ |j        D ¦   «         ¦  «        d	z  }t          |¦  «        }~t          ¦   «                              ||¬
¦  «        S )zƒGet optimal batch size by calculating memory occupation of model.

        Returns:
            (int): Optimal batch size.
        ÚcacheF)r   r"   r4   )r%   r&   Nc              3  ó@   K  — | ]}t          |d          ¦  «        V — ŒdS )r}   N)r½   )rV   Úlabels     r    ú	<genexpr>z.DetectionTrainer.auto_batch.<locals>.<genexpr>   s.   è è € ÐNÐN°�#˜e EœlÑ+Ô+ÐNÐNÐNÐNÐNÐNr!   r¸   )Údataset_size)	r   r0   r3   r1   r-   r„   r½   r   Ú
auto_batch)r   Útrain_datasetÚmax_num_objÚnr   s       €r    r×   zDetectionTrainer.auto_batchø   s÷   ø€ õ ˜dœi°G¸UÐ3CÐDÑDÔDð 	[ÈÌ	Ø ×.Ò.¨t¬y¸Ô/AÈÐWYÐ.ÑZÔZˆMð	[ð 	[ð 	[ñ 	[ô 	[ð 	[ð 	[ð 	[ð 	[ð 	[ð 	[øøøð 	[ð 	[ð 	[ð 	[åÐNÐN¸Ô9MÐNÑNÔNÑNÔNÐQRÑRˆÝ�ÑÔˆØÝ‰wŒw×!Ò! +¸AÐ!Ñ>Ô>Ð>s   š)AÁAÁA)r   r   r   r   )r"   N)r#   r$   r%   r$   r&   r'   )r4   r   r"   )r5   r$   r6   r.   r7   r.   r%   r$   )r&   rG   rH   rG   )NNT)r   rœ   rš   rœ   r�   rž   )r&   rÀ   rÁ   r.   rH   rÂ   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r3   rF   rp   ru   ry   r‰   rŽ   r›   r¤   r«   r±   r¿   rÉ   rÐ   r×   Ú__classcell__)r   s   @r    r   r      s‡  ø€ € € € € ðð ð: 'È4Ðkoð 5ð 5ð 5ð 5ð 5ð 5ð 5ðsð sð sð sð sð
ð 
ð 
ð 
ð 
ð:ð ð ð ð@$ð $ð $ðð ð ð^ð ^ð ^ð
8ð 8ð 8ð
Tð Tð Tð*ð ð ð ð ð$
ð 
ð 
ðNð Nð Nð Nð Nð
ð 
ð 
ð
ð 
ð 
ð 
ðrð rð rð?ð ?ð ?ð ?ð ?ð ?ð ?ð ?ð ?r!   r   )!Ú
__future__r   rT   re   r   Útypingr   r˜   r@   r_   r   Úultralytics.datar   r   Úultralytics.engine.trainerr	   Úultralytics.modelsr
   Úultralytics.nn.tasksr   Úultralytics.utilsr   r   r   Úultralytics.utils.patchesr   Úultralytics.utils.plottingr   r   Úultralytics.utils.torch_utilsr   r   r   rS   r!   r    ú<module>rê      sb  ðð #Ð "Ð "Ð "Ð "Ð "à €€€Ø €€€Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð à Ð Ð Ð Ø €€€Ø Ð Ð Ð Ð Ð à AÐ AÐ AÐ AÐ AÐ AÐ AÐ AØ 2Ð 2Ð 2Ð 2Ð 2Ð 2Ø #Ð #Ð #Ð #Ð #Ð #Ø /Ð /Ð /Ð /Ð /Ð /Ø 7Ð 7Ð 7Ð 7Ð 7Ð 7Ð 7Ð 7Ð 7Ð 7Ø 6Ð 6Ð 6Ð 6Ð 6Ð 6Ø ?Ð ?Ð ?Ð ?Ð ?Ð ?Ð ?Ð ?Ø TÐ TÐ TÐ TÐ TÐ TÐ TÐ Tðk?ð k?ð k?ð k?ð k?�{ñ k?ô k?ð k?ð k?ð k?r!   