
    .h%                        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mZ d d
lmZ d dlmZmZmZ  G d de
      Zy)    )annotations)copy)AnyN)ClassificationDatasetbuild_dataloader)BaseTrainer)yolo)ClassificationModel)DEFAULT_CFGLOGGERRANK)plot_images)is_parallelstrip_optimizertorch_distributed_zero_firstc                       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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 (list[str]): Names of the loss functions used during training.
        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.
        label_loss_items: Return a loss dict with labelled training loss items.
        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="yolo11n-cls.pt", data="imagenet10", epochs=3)
        >>> trainer = ClassificationTrainer(overrides=args)
        >>> trainer.train()
    Nc                f    |i }d|d<   |j                  d      d|d<   t        | 	  |||       y)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 (list[Any], optional): List of callback functions to be executed during training.
        Nclassifytaskimgsz   )getsuper__init__)selfcfg	overrides
_callbacks	__class__s       d/var/www/html/ai-service/venv/lib/python3.12/site-packages/ultralytics/models/yolo/classify/train.pyr   zClassificationTrainer.__init__5   sD     I&	&==!)!$Igi4    c                @    | j                   d   | j                  _        y)z9Set the YOLO model's class names from the loaded dataset.namesN)datamodelr$   r   s    r!   set_model_attributesz*ClassificationTrainer.set_model_attributesE   s    99W-

r"   c                   t        || j                  d   | j                  d   |xr	 t        dk(        }|r|j                  |       |j	                         D ]  }| j
                  j                  st        |d      r|j                          t        |t        j                  j                        sZ| j
                  j                  sq| j
                  j                  |_         |j                         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*   chverbosereset_parametersT)r
   r%   r   loadmodulesargs
pretrainedhasattrr/   
isinstancetorchnnDropoutdropoutp
parametersrequires_grad)r   r   weightsr.   r&   mr:   s          r!   	get_modelzClassificationTrainer.get_modelI   s     $CDIIdO		*@U_f_ukosukuvJJw 	(A99''GA7I,J""$!UXX--.4993D3Dii''		(
 !!# 	#A"AO	#r"   c                p   ddl }t        | j                        |j                  j                  v rJ |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__r2   r3   r   setup_modelr
   reshape_outputsr%   )r   rB   ckptr    s      r!   rF   z!ClassificationTrainer.setup_modelb   s     	tzz?k00999@++44TZZ@+/99+?+?TDJ D7&(D++DJJ		$Hr"   c                :    t        || j                  |dk(  |      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.
        train)rootr2   augmentprefix)r   r2   )r   img_pathmodebatchs       r!   build_datasetz#ClassificationTrainer.build_datasetu   s     %(DT[Odhiir"   c                   t        |      5  | j                  ||      }ddd       t        || j                  j                  || j                  j
                        }|dk7  rkt        | j                        r1|j                  j                  | j                  j                  _        |S |j                  j                  | j                  _        |S # 1 sw Y   xY w)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.
        N)rank	drop_lastrJ   )r   rQ   r   r2   workerscompiler   r&   datasettorch_transformsmodule
transforms)r   dataset_path
batch_sizerS   rO   rW   loaders          r!   get_dataloaderz$ClassificationTrainer.get_dataloader   s     *$/ 	=((t<G	= "':tyy7H7Ht_c_h_h_p_pq7?4::&/5~~/N/N

!!,  )/(G(G

%	= 	=s   CCc                    |d   j                  | j                  | j                  j                  dk(        |d<   |d   j                  | j                  | j                  j                  dk(        |d<   |S )z)Preprocess a batch of images and classes.imgcuda)non_blockingcls)todevicetype)r   rP   s     r!   preprocess_batchz&ClassificationTrainer.preprocess_batch   sc    U|t{{AQAQU[A[\eU|t{{AQAQU[A[\er"   c                j    dddt        | j                        z   z  z   ddg| j                  dd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   sT    vS%9!9::?
 __?
 	?

 ?
 
 	
r"   c                    dg| _         t        j                  j                  | j                  | j
                  t        | j                        | j                        S )z=Return an instance of ClassificationValidator for validation.loss)r2   r   )	rp   r	   r   ClassificationValidatortest_loadersave_dirr   r2   	callbacksr'   s    r!   get_validatorz#ClassificationTrainer.get_validator   sF    !(}}44dmm$tyy/dnn 5 
 	
r"   c                    | j                   D cg c]	  }| d|  }}||S t        t        |      d      g}t        t	        ||            S c c}w )a  
        Return a loss dict with labelled training loss items tensor.

        Args:
            loss_items (torch.Tensor, optional): Loss tensor items.
            prefix (str, optional): Prefix to prepend to loss names.

        Returns:
            keys (list[str]): List of loss keys if loss_items is None.
            loss_dict (dict[str, float]): Dictionary of loss items if loss_items is provided.
        /   )rp   roundfloatdictzip)r   
loss_itemsrM   xkeyss        r!   label_loss_itemsz&ClassificationTrainer.label_loss_items   s[     *.9A6(!A399KE*-q12
Cj)**	 :s   Ac                
   | j                   | j                  fD ]  }|j                         st        |       || j                  u s.t	        j
                  d| d       | j                  j                  | j                  j                  _        | j                  j                  | j                  j                  _	        | j                  |      | _
        | j                  j                  dd       | j                  d        y)z3Evaluate trained model and save validation results.z
Validating z...)r&   fitnessNon_fit_epoch_end)lastbestexistsr   r   infor2   r%   	validatorplotsmetricspoprun_callbacks)r   fs     r!   
final_evalz ClassificationTrainer.final_eval   s    DII% 		;Axxz"		>KK-s# 67/3yy~~DNN'',04		DNN''-#'>>>#:DLLL$$Y5&&'9:		;r"   c                    t        j                  |d   j                  d         |d<   t        || j                  d| dz  | j
                         y)z
        Plot training samples with their annotations.

        Args:
            batch (dict[str, torch.Tensor]): Batch containing images and class labels.
            ni (int): Number of iterations.
        r`   r   	batch_idxtrain_batchz.jpg)labelsfnameon_plotN)r6   arangeshaper   rv   r   )r   rP   nis      r!   plot_training_samplesz+ClassificationTrainer.plot_training_samples   sM     #\\%,*<*<Q*?@k--Kt4"88LL	
r"   )r   zdict[str, Any] | None)NNT)r.   bool)rJ   N)rN   rC   rO   rC   )   r   rJ   )r[   rC   r\   intrS   r   rO   rC   )rP   dict[str, torch.Tensor]returnr   )r   rC   )NrJ   )r   ztorch.Tensor | NonerM   rC   )rP   r   r   r   )__name__
__module____qualname____doc__r   r   r(   r?   rF   rQ   r^   rg   rq   rx   r   r   r   __classcell__)r    s   @r!   r   r      sP    B '4\` 5 .2&j2

+$;
r"   r   )
__future__r   r   typingr   r6   ultralytics.datar   r   ultralytics.engine.trainerr   ultralytics.modelsr	   ultralytics.nn.tasksr
   ultralytics.utilsr   r   r   ultralytics.utils.plottingr   ultralytics.utils.torch_utilsr   r   r   r    r"   r!   <module>r      s<    #    D 2 # 4 7 7 2 d dL
K L
r"   