o
    xi[,                     @  s   d dl mZ d dlmZmZ d dlmZ d dlmZ zd dl	m
Z
 d dlmZmZ W n eyA   d dlm
Z
 d dlmZmZ Y nw d dlmZ d dlZd d	lmZ G d
d dZ				ddddZdS )    )annotations)AnyCallable)YOLO)BaseTrainer)RANK)	get_flopsget_num_params)ClassificationTrainerN)	telemetryc                   @  s   e Zd ZdZ				d'd(ddZd)ddZd)ddZd)ddZd)ddZd)ddZ	d)ddZ
d)dd Zd*d"d#Zed+d%d&ZdS ),WandbCallbacka  An internal YOLO model wrapper that tracks metrics, and logs models to Weights & Biases.

    Usage:
    ```python
    from wandb.integration.yolov8.yolov8 import WandbCallback

    model = YOLO("yolov8n.pt")
    wandb_logger = WandbCallback(
        model,
    )
    for event, callback_fn in wandb_logger.callbacks.items():
        model.add_callback(event, callback_fn)
    ```
    Nyolor   run_name
str | Noneprojecttagslist[str] | Noneresumekwargs
Any | NonereturnNonec                 K  s(   || _ || _|| _|| _|| _|| _dS )a  A utility class to manage wandb run and various callbacks for the ultralytics YOLOv8 framework.

        Args:
            yolo: A YOLOv8 model that's inherited from `:class:ultralytics.yolo.engine.model.YOLO`
            run_name, str: The name of the Weights & Biases run, defaults to an auto generated run_name if `trainer.args.name` is not defined.
            project, str: The name of the Weights & Biases project, defaults to `"YOLOv8"` if `trainer.args.project` is not defined.
            tags, List[str]: A list of tags to be added to the Weights & Biases run, defaults to `["YOLOv8"]`.
            resume, str: Whether to resume a previous run on Weights & Biases, defaults to `None`.
            **kwargs: Additional arguments to be passed to `wandb.init()`.
        N)r   r   r   r   r   r   )selfr   r   r   r   r   r    r   S/home/ubuntu/.local/lib/python3.10/site-packages/wandb/integration/yolov8/yolov8.py__init__$   s   
zWandbCallback.__init__trainerr   c                 C  s"  t jdu r8t jd| jr| jn|jj| jr| jn|jjpd| jr"| jndgt|j| j	r.| j	ndd| j
| _nt j| _| jdusCJ | jjddd | jjddddd	 | jjd
dddd	 | jjddddd	 | jjddddd	 tjt jd}d|j_W d   dS 1 sw   Y  dS )a'  Starts a new wandb run to track the training process and log to Weights & Biases.

        Args:
            trainer: A task trainer that's inherited from `:class:ultralytics.yolo.engine.trainer.BaseTrainer`
                    that contains the model training and optimization routine.
        NYOLOv8)namer   r   configr   epochT)hiddenztrain/*min)step_metric	step_syncsummaryzval/*z	metrics/*maxzlr/*last)runr   )wandbr(   initr   argsr   r   r   varsr   r   define_metricr   contextfeatureultralytics_yolov8)r   r   telr   r   r   on_pretrain_routine_start>   s<   



"z'WandbCallback.on_pretrain_routine_startc                 C  s8   | j d usJ | j jt|jtt|jdd d S )N   )zmodel/parameterszmodel/GFLOPs)r(   r%   updater	   modelroundr   r   r   r   r   r   on_pretrain_routine_endf   s   z%WandbCallback.on_pretrain_routine_endc                 C  s(   | j dusJ | j d|jd i dS )zJOn train epoch start we only log epoch number to the Weights & Biases run.Nr       )r(   logr    r7   r   r   r   on_train_epoch_starto   s   z"WandbCallback.on_train_epoch_startc                 C  sj   | j dusJ | j i |j|j|jdd|j t|ts3| j ddd |j	dD i dS dS )zFOn train epoch end we log all the metrics to the Weights & Biases run.Ntrain)prefixtrain_batch_imagesc                 S      g | ]}t jt||jd qS )captionr)   Imagestrstem.0
image_pathr   r   r   
<listcomp>       z4WandbCallback.on_train_epoch_end.<locals>.<listcomp>ztrain_batch*.jpg)
r(   r:   metricslabel_loss_itemstlosslr
isinstancer
   save_dirglobr7   r   r   r   on_train_epoch_endu   s$   

z WandbCallback.on_train_epoch_endc                   s   | j dusJ  jdkr/ fdddD }|d r|d n|d }|r/| j jdt|di  j jkrM| j jd	 jd id
d  j D  dS dS )z^On fit epoch end we log all the best metrics and model detail to Weights & Biases run summary.Nr   c                   s   g | ]	} j j|qS r   )	validatorspeedget)rG   keyr   r   r   rI      s    z2WandbCallback.on_fit_epoch_end.<locals>.<listcomp>)r9   	inferencer9   zmodel/speed(ms/img)r3   z
best/epochc                 S  s   i | ]
\}}d | |qS )zbest/r   )rG   rV   valr   r   r   
<dictcomp>   s    z2WandbCallback.on_fit_epoch_end.<locals>.<dictcomp>)	r(   r    r%   r4   r6   best_fitnessfitnessrK   items)r   r   speedsrT   r   rW   r   on_fit_epoch_end   s&   



zWandbCallback.on_fit_epoch_endc                 C  s   | j dusJ t|ts/| j dusJ | j dd |jdD dd |jjdD d |j r\| j dus;J | j j	t
|jd| j j d	|jj d
dd|jd  gd dS dS )zgOn train end we log all the media, including plots, images and best model artifact to Weights & Biases.Nc                 S  r?   r@   rB   rF   r   r   r   rI      rJ   z.WandbCallback.on_train_end.<locals>.<listcomp>z*.pngc                 S  r?   r@   rB   rF   r   r   r   rI      rJ   zval*.jpg)plots
val_imagesr5   _.ptbestepoch_r9   typer   aliases)r(   rO   r
   r:   rP   rQ   rS   rd   existslog_artifactrD   r   r+   taskr    r7   r   r   r   on_train_end   s*   



zWandbCallback.on_train_endc                 C  sP   | j dusJ | j jt|jd| j j d|jj ddd|jd  gd dS )	zBOn model save we log the model as an artifact to Weights & Biases.Nr5   rb   rc   r'   re   r9   rf   )r(   rj   rD   r'   r   r+   rk   r    r7   r   r   r   on_model_save   s   
zWandbCallback.on_model_save_trainerc                 C  s"   | j dusJ | j   d| _ dS )zCOn teardown, we finish the Weights & Biases run and set it to None.N)r(   finish)r   rn   r   r   r   teardown   s   

zWandbCallback.teardowndict[str, Callable]c              	   C  s&   | j | j| j| j| j| j| j| jdS )zgProperty contains all the relevant callbacks to add to the YOLO model for the Weights & Biases logging.r2   r8   r;   rR   r_   rl   rm   rp   rr   )r   r   r   r   	callbacks   s   zWandbCallback.callbacksNNNN)r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r   r   r   r   )rn   r   r   r   )r   rq   )__name__
__module____qualname____doc__r   r2   r8   r;   rR   r_   rl   rm   rp   propertyrs   r   r   r   r   r      s"    

(
	





r   r   r   r   r   r   r   r   r   r   r   r   c           	      K  sp   t jddd t jddd tdv r1t| f||||d|}|j D ]
\}}| || q$| S t d | S )a  A YOLO model wrapper that tracks metrics, and logs models to Weights & Biases.

    Args:
        yolo: A YOLOv8 model that's inherited from `:class:ultralytics.yolo.engine.model.YOLO`
        run_name, str: The name of the Weights & Biases run, defaults to an auto generated name if `trainer.args.name` is not defined.
        project, str: The name of the Weights & Biases project, defaults to `"YOLOv8"` if `trainer.args.project` is not defined.
        tags, List[str]: A list of tags to be added to the Weights & Biases run, defaults to `["YOLOv8"]`.
        resume, str: Whether to resume a previous run on Weights & Biases, defaults to `None`.
        **kwargs: Additional arguments to be passed to `wandb.init()`.

    Usage:
    ```python
    from wandb.integration.yolov8 import add_callbacks as add_wandb_callbacks

    model = YOLO("yolov8n.pt")
    add_wandb_callbacks(
        model,
    )
    model.train(
        data="coco128.yaml",
        epochs=3,
        imgsz=640,
    )
    ```
    a$  The wandb callback is currently in beta and is subject to change based on updates to `ultralytics yolov8`.
        The callback is tested and supported for ultralytics v8.0.43 and above.
        Please report any issues to https://github.com/wandb/wandb/issues with the tag `yolov8`.
        F)repeata  This wandb callback is no longer functional and would be deprecated in the near future.
        We recommend you to use the updated callback using `from wandb.integration.ultralytics import add_wandb_callback`.
        The updated callback is tested and supported for ultralytics 8.0.167 and above.
        You can refer to https://docs.wandb.ai/guides/integrations/ultralytics for the updated documentation.
        Please report any issues to https://github.com/wandb/wandb/issues with the tag `yolov8`.
        )r   )r   r   r   r   zThe RANK of the process to add the callbacks was neither 0 or -1.No Weights & Biases callbacks were added to this instance of the YOLO model.)r)   termwarnr   r   rs   r]   add_callback	termerror)	r   r   r   r   r   r   wandb_loggereventcallback_fnr   r   r   add_callbacks   s.   !
r   rt   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   )
__future__r   typingr   r   ultralytics.yolo.engine.modelr   ultralytics.yolo.engine.trainerr   ultralytics.yolo.utilsr   "ultralytics.yolo.utils.torch_utilsr   r	   ModuleNotFoundErrorultralytics.utilsultralytics.utils.torch_utils"ultralytics.yolo.v8.classify.trainr
   r)   wandb.sdk.libr   r   r   r   r   r   r   <module>   s*     O