
    |h                     j    d dl 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mZ  G d d	e      Zy
)    )copy)Optional)DetectionTrainer)RTDETRDetectionModel)RANKcolorstr   )RTDETRDatasetRTDETRValidatorc                   T    e Zd ZdZddee   dee   defdZddeded	ee	   fd
Z
d Zy)RTDETRTrainera  
    Trainer class for the RT-DETR model developed by Baidu for real-time object detection.

    This class extends the DetectionTrainer class for YOLO to adapt to the specific features and architecture of RT-DETR.
    The model leverages Vision Transformers and has capabilities like IoU-aware query selection and adaptable inference
    speed.

    Attributes:
        loss_names (tuple): Names of the loss components used for training.
        data (dict): Dataset configuration containing class count and other parameters.
        args (dict): Training arguments and hyperparameters.
        save_dir (Path): Directory to save training results.
        test_loader (DataLoader): DataLoader for validation/testing data.

    Methods:
        get_model: Initialize and return an RT-DETR model for object detection tasks.
        build_dataset: Build and return an RT-DETR dataset for training or validation.
        get_validator: Return a DetectionValidator suitable for RT-DETR model validation.

    Notes:
        - F.grid_sample used in RT-DETR does not support the `deterministic=True` argument.
        - AMP training can lead to NaN outputs and may produce errors during bipartite graph matching.

    Examples:
        >>> from ultralytics.models.rtdetr.train import RTDETRTrainer
        >>> args = dict(model="rtdetr-l.yaml", data="coco8.yaml", imgsz=640, epochs=3)
        >>> trainer = RTDETRTrainer(overrides=args)
        >>> trainer.train()
    Ncfgweightsverbosec                     t        || j                  d   | j                  d   |xr	 t        dk(        }|r|j                  |       |S )a`  
        Initialize and return an RT-DETR model for object detection tasks.

        Args:
            cfg (dict, optional): Model configuration.
            weights (str, optional): Path to pre-trained model weights.
            verbose (bool): Verbose logging if True.

        Returns:
            (RTDETRDetectionModel): Initialized model.
        ncchannels)r   chr   )r   datar   load)selfr   r   r   models        ^/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/train.py	get_modelzRTDETRTrainer.get_model,   sF     %STYYt_:AV`g`vlptvlvwJJw    img_pathmodebatchc                 f   t        || j                  j                  ||dk(  | j                  d| j                  j                  xs d| j                  j                  xs dt        | d      | j                  j                  | j                  |dk(  r| j                  j                        S d      S )a|  
        Build and return an RT-DETR dataset for training or validation.

        Args:
            img_path (str): Path to the folder containing images.
            mode (str): Dataset mode, either 'train' or 'val'.
            batch (int, optional): Batch size for rectangle training.

        Returns:
            (RTDETRDataset): Dataset object for the specific mode.
        trainFNz: g      ?)r   imgsz
batch_sizeaugmenthyprectcache
single_clsprefixclassesr   fraction)	r
   argsr"   r'   r(   r   r*   r   r+   )r   r   r   r   s       r   build_datasetzRTDETRTrainer.build_dataset=   s     ))//GO		))//)Tyy++4utfBK(II%%+/7?TYY''
 	
 AD
 	
r   c                 z    d| _         t        | j                  | j                  t	        | j
                              S )zBReturn a DetectionValidator suitable for RT-DETR model validation.)	giou_losscls_lossl1_loss)save_dirr,   )
loss_namesr   test_loaderr2   r   r,   )r   s    r   get_validatorzRTDETRTrainer.get_validatorX   s-    <t//$--dSWS\S\o^^r   )NNT)valN)__name__
__module____qualname____doc__r   dictstrboolr   intr-   r5    r   r   r   r      sN    <Xd^ Xc] \` "
c 
 
Xc] 
6_r   r   N)r   typingr   ultralytics.models.yolo.detectr   ultralytics.nn.tasksr   ultralytics.utilsr   r   r6   r
   r   r   r?   r   r   <module>rD      s*      ; 5 , /N_$ N_r   