§
    l¬¸j"  ã                  ó®   — d dl mZ d dlmZ d dl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mZ d d
lmZ d dlmZmZ  G d„ de
¦  «        ZdS )é    )Úannotations)Úcopy)ÚAnyN)ÚClassificationDatasetÚbuild_dataloader)ÚBaseTrainer)Úyolo)ÚClassificationModel)ÚDEFAULT_CFGÚRANK)Úplot_images)Úis_parallelÚtorch_distributed_zero_firstc                  óx   ‡ — e Zd ZdZeddfd"ˆ fd„Zd„ Zd#d$d„Zˆ fd„Zd%d&d„Z	d'd(d„Z
d)d„Zd*d„Zd„ Zd+d!„Zˆ xZS ),ÚClassificationTraineraæ  A trainer class extending BaseTrainer for training image classification models.

    This trainer handles the training process for image classification tasks, supporting both YOLO classification models
    and torchvision models with comprehensive dataset handling and validation.

    Attributes:
        model (ClassificationModel): The classification model to be trained.
        data (dict[str, Any]): Dictionary containing dataset information including class names and number of classes.
        loss_names (tuple): Names of the loss items, derived from the loss dict returned by the criterion.
        validator (ClassificationValidator): Validator instance for model evaluation.

    Methods:
        set_model_attributes: Set the model's class names from the loaded dataset.
        get_model: Return a modified PyTorch model configured for training.
        setup_model: Load, create or download model for classification.
        build_dataset: Create a ClassificationDataset instance.
        get_dataloader: Return PyTorch DataLoader with transforms for image preprocessing.
        preprocess_batch: Preprocess a batch of images and classes.
        progress_string: Return a formatted string showing training progress.
        get_validator: Return an instance of ClassificationValidator.
        final_eval: Evaluate trained model and save validation results.
        plot_training_samples: Plot training samples with their annotations.

    Examples:
        Initialize and train a classification model
        >>> from ultralytics.models.yolo.classify import ClassificationTrainer
        >>> args = dict(model="yolo26n-cls.pt", data="imagenet10", epochs=3)
        >>> trainer = ClassificationTrainer(overrides=args)
        >>> trainer.train()
    NÚ	overridesúdict[str, Any] | NoneÚ
_callbacksúdict | Nonec                ó”   •— |€i }d|d<   |                      d¦  «        €d|d<   t          ¦   «                              |||¦  «         dS )aŒ  Initialize a ClassificationTrainer object.

        Args:
            cfg (dict[str, Any], optional): Default configuration dictionary containing training parameters.
            overrides (dict[str, Any], optional): Dictionary of parameter overrides for the default configuration.
            _callbacks (dict, optional): Dictionary of callback functions to be executed during training.
        NÚclassifyÚtaskÚimgszéà   )ÚgetÚsuperÚ__init__)ÚselfÚcfgr   r   Ú	__class__s       €úv/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/ultralytics/models/yolo/classify/train.pyr   zClassificationTrainer.__init__3   sX   ø€ ð ÐØˆIØ&ˆ	�&ÑØ�=Š=˜Ñ!Ô!Ð)Ø!$ˆI�gÑÝ‰Œ×Ò˜˜i¨Ñ4Ô4Ð4Ð4Ð4ó    c                ó4   — | j         d         | j        _        dS )z9Set the YOLO model's class names from the loaded dataset.ÚnamesN)ÚdataÚmodelr$   ©r   s    r!   Úset_model_attributesz*ClassificationTrainer.set_model_attributesB   s   € àœ9 WÔ-ˆŒ
ÔÐÐr"   TÚverboseÚboolc                óð  — t          || j        d         | j        d         |o
t          dk    ¬¦  «        }|r|                     |¦  «         |                     ¦   «         D ]w}| j        j        du r+| j        s$t          |d¦  «        r| 	                    ¦   «          t          |t          j        j        ¦  «        r| j        j        r| j        j        |_        Œx|                     ¦   «         D ]	}d|_        Œ
|S )aˆ  Return a modified PyTorch model configured for training YOLO classification.

        Args:
            cfg (Any, optional): Model configuration.
            weights (Any, optional): Pre-trained model weights.
            verbose (bool, optional): Whether to display model information.

        Returns:
            (ClassificationModel): Configured PyTorch model for classification.
        ÚncÚchannelséÿÿÿÿ)r,   Úchr)   FÚreset_parametersT)r
   r%   r   ÚloadÚmodulesÚargsÚ
pretrainedÚresumeÚhasattrr0   Ú
isinstanceÚtorchÚnnÚDropoutÚdropoutÚpÚ
parametersÚrequires_grad)r   r   Úweightsr)   r&   Úmr<   s          r!   Ú	get_modelzClassificationTrainer.get_modelF   s÷   € õ $ C¨D¬I°d¬OÀÄ	È*Ô@UÐ_fÐ_uÕkoÐsuÒkuÐvÑvÔvˆØð 	 Ø�JŠJ�wÑÔÐà—’‘”ð 	(ð 	(ˆAØŒyÔ# uÐ,Ð,°T´[Ð,ÅWÈQÐPbÑEcÔEcÐ,Ø×"Ò"Ñ$Ô$Ð$Ý˜!�UœXÔ-Ñ.Ô.ð (°4´9Ô3Dð (Ø”iÔ'�”øØ×!Ò!Ñ#Ô#ð 	#ð 	#ˆAØ"ˆAŒOˆOØˆr"   c                óH  •— ddl }t          | j        ¦  «        |j        j        v r7 |j        j        | j                 | j        j        rdnd¬¦  «        | _        d}n t          ¦   «                              ¦   «         }t          j
        | j        | j        d         ¦  «         |S )z–Load, create or download model for classification tasks.

        Returns:
            (Any): Model checkpoint if applicable, otherwise None.
        r   NÚIMAGENET1K_V1)r?   r,   )ÚtorchvisionÚstrr&   ÚmodelsÚ__dict__r3   r4   r   Úsetup_modelr
   Úreshape_outputsr%   )r   rD   Úckptr    s      €r!   rH   z!ClassificationTrainer.setup_model^   sž   ø€ ð 	ÐÐÐåˆtŒz‰?Œ?˜kÔ0Ô9Ð9Ð9Ø@˜Ô+Ô4°T´ZÔ@Ø+/¬9Ô+?ÐI˜˜ÀTðñ ô ˆDŒJð ˆDˆDå‘7”7×&Ò&Ñ(Ô(ˆDÝÔ+¨D¬J¸¼	À$¼ÑHÔHÐHØˆr"   ÚtrainÚimg_pathrE   Úmodec                óv   — t          || j        |dk    |dk    rdn| j        j        | j        d         ¬¦  «        S )aŽ  Create a ClassificationDataset instance given an image path and mode.

        Args:
            img_path (str): Path to the dataset images.
            mode (str, optional): Dataset mode ('train', 'val', or 'test').
            batch (Any, optional): Batch information (unused in this implementation).

        Returns:
            (ClassificationDataset): Dataset for the specified mode.
        rK   r$   )ÚaugmentÚprefixr$   )r   r3   Úsplitr%   )r   rL   rM   Úbatchs       r!   Úbuild_datasetz#ClassificationTrainer.build_datasetp   sG   € õ %ØØŒIØ˜G’OØ" gšo˜o�7�7°4´9´?Ø”)˜GÔ$ð
ñ 
ô 
ð 	
r"   é   r   Údataset_pathÚ
batch_sizeÚintÚrankc                ó¾  — t          |¦  «        5  |                      ||¦  «        }ddd¦  «         n# 1 swxY w Y   |j        st          d|› d|› d�¦  «        ‚| j        j        o|dk    }t          ||| j        j        ||| j        ¬¦  «        }|dk    rFt          | j
        ¦  «        r|j        j        | j
        j        _        n|j        j        | j
        _        |S )aÇ  Return PyTorch DataLoader with transforms to preprocess images.

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

        Returns:
            (torch.utils.data.DataLoader): DataLoader for the specified dataset and mode.
        NzNo images found in 'z' split of zL. See https://docs.ultralytics.com/datasets/classify for cls dataset format.rK   )rX   Ú	drop_lastÚdevice)r   rS   ÚsamplesÚFileNotFoundErrorr3   Úcompiler   Úworkersr[   r   r&   ÚdatasetÚtorch_transformsÚmoduleÚ
transforms)r   rU   rV   rX   rM   r`   rZ   Úloaders           r!   Úget_dataloaderz$ClassificationTrainer.get_dataloaderƒ   sH  € õ *¨$Ñ/Ô/ð 	=ð 	=Ø×(Ò(¨°tÑ<Ô<ˆGð	=ð 	=ð 	=ñ 	=ô 	=ð 	=ð 	=ð 	=ð 	=ð 	=ð 	=øøøð 	=ð 	=ð 	=ð 	=ð Œð 	Ý#ð^ tð ^ð ^¸ð ^ð ^ð ^ñô ð ð
 ”IÔ%Ð9¨$°'ª/ˆ	Ý!Ø�Z ¤Ô!2¸ÈÐ[_Ô[fð
ñ 
ô 
ˆð �7Š?ˆ?Ý˜4œ:Ñ&Ô&ð HØ/5¬~Ô/N�”
Ô!Ô,Ð,à(.¬Ô(G�”
Ô%Øˆs   �3³7º7rR   údict[str, torch.Tensor]Úreturnc                óÊ   — |d                               | j        | j        j        dv¬¦  «        |d<   |d                               | j        | j        j        dv¬¦  «        |d<   |S )z)Preprocess a batch of images and classes.Úimg>   ÚcpuÚmps)Únon_blockingÚcls)Útor[   Útype)r   rR   s     r!   Úpreprocess_batchz&ClassificationTrainer.preprocess_batch¤   s[   € à˜U”|—’ t¤{ÀÄÔAQÐYgÐAg�ÑhÔhˆˆe‰Ø˜U”|—’ t¤{ÀÄÔAQÐYgÐAg�ÑhÔhˆˆe‰Øˆr"   c                ó^   — dddt          | j        ¦  «        z   z  z   ddg| j        ¢d‘d‘R z  S )z4Return a formatted string showing training progress.ú
z%11sé   ÚEpochÚGPU_memÚ	InstancesÚSize)ÚlenÚ
loss_namesr'   s    r!   Úprogress_stringz%ClassificationTrainer.progress_stringª   sX   € à�v ¥S¨¬Ñ%9Ô%9Ñ!9Ñ:Ñ:ØØð?
ð Œ_ð?
ð ð	?
ð
 ð?
ð ?
ñ 
ð 	
r"   c                óŠ   — t           j                             | j        | j        t          | j        ¦  «        | j        ¬¦  «        S )z=Return an instance of ClassificationValidator for validation.)r3   r   )r	   r   ÚClassificationValidatorÚtest_loaderÚsave_dirr   r3   Ú	callbacksr'   s    r!   Úget_validatorz#ClassificationTrainer.get_validator´   s9   € åŒ}×4Ò4ØÔ˜dœmµ$°t´y±/´/ÈdÌnð 5ñ 
ô 
ð 	
r"   Únic                óœ   — t          j        |d         j        d         ¦  «        |d<   t          || j        d|› d�z  | j        ¬¦  «         dS )zßPlot training samples with their annotations.

        Args:
            batch (dict[str, torch.Tensor]): Batch containing images and class labels.
            ni (int): Batch index used for naming the output file.
        ri   r   Ú	batch_idxÚtrain_batchz.jpg)ÚlabelsÚfnameÚon_plotN)r8   ÚarangeÚshaper   r~   r‡   )r   rR   r�   s      r!   Úplot_training_samplesz+ClassificationTrainer.plot_training_samplesº   sc   € õ #œ\¨%°¬,Ô*<¸QÔ*?Ñ@Ô@ˆˆkÑÝØØ”-Ð"8°Ð"8Ð"8Ð"8Ñ8Ø”Lð	
ñ 	
ô 	
ð 	
ð 	
ð 	
r"   )r   r   r   r   )NNT)r)   r*   )rK   N)rL   rE   rM   rE   )rT   r   rK   )rU   rE   rV   rW   rX   rW   rM   rE   )rR   rf   rg   rf   )rg   rE   )rR   rf   r�   rW   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r(   rA   rH   rS   re   rp   rz   r€   rŠ   Ú__classcell__)r    s   @r!   r   r      s  ø€ € € € € ðð ð> 'È4Ðkoð 5ð 5ð 5ð 5ð 5ð 5ð 5ð.ð .ð .ðð ð ð ð ð0ð ð ð ð ð$
ð 
ð 
ð 
ð 
ð&ð ð ð ð ðBð ð ð ð
ð 
ð 
ð 
ð
ð 
ð 
ð
ð 
ð 
ð 
ð 
ð 
ð 
ð 
r"   r   )Ú
__future__r   r   Útypingr   r8   Úultralytics.datar   r   Úultralytics.engine.trainerr   Úultralytics.modelsr	   Úultralytics.nn.tasksr
   Úultralytics.utilsr   r   Úultralytics.utils.plottingr   Úultralytics.utils.torch_utilsr   r   r   © r"   r!   ú<module>rš      s  ðð #Ð "Ð "Ð "Ð "Ð "à Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð à €€€à DÐ DÐ DÐ DÐ DÐ DÐ DÐ DØ 2Ð 2Ð 2Ð 2Ð 2Ð 2Ø #Ð #Ð #Ð #Ð #Ð #Ø 4Ð 4Ð 4Ð 4Ð 4Ð 4Ø /Ð /Ð /Ð /Ð /Ð /Ð /Ð /Ø 2Ð 2Ð 2Ð 2Ð 2Ð 2Ø SÐ SÐ SÐ SÐ SÐ SÐ SÐ Sðs
ð s
ð s
ð s
ð s
˜Kñ s
ô s
ð s
ð s
ð s
r"   