o
    Wh                     @   s   d dl mZmZmZmZmZ z(erJ ed du sJ daedZd dlZd dl	m
Z
 d dlZd dlmZ W n eeeefyE   dZY nw dded	ed
dfddZdddZdddZdddZdddZdddZerveeeedZdS i ZdS )    )LOGGERSETTINGSTESTS_RUNNINGcolorstrtorch_utilstensorboardTNzTensorBoard: )deepcopy)SummaryWriterscalarsstepreturnc                 C   s,   t r|  D ]\}}t ||| qdS dS )a  
    Log scalar values to TensorBoard.

    Args:
        scalars (dict): Dictionary of scalar values to log to TensorBoard. Keys are scalar names and values are the
            corresponding scalar values.
        step (int): Global step value to record with the scalar values. Used for x-axis in TensorBoard graphs.

    Examples:
        >>> # Log training metrics
        >>> metrics = {"loss": 0.5, "accuracy": 0.95}
        >>> _log_scalars(metrics, step=100)
    N)WRITERitems
add_scalar)r
   r   kv r   [/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/utils/callbacks/tensorboard.py_log_scalars   s
   r   c                 C   s  | j j}t|tr||fn|}t| j }tjddg|R |j	|j
d}t  tjdtd tjdtjjd z'| j  ttjjt| j|ddg  tt d W W d	   d	S  ty   z?tt| j}|  |jdd
}| D ]}t|drd|_d|_ q|| ttjj||ddg  tt d W n ty } zt!t d|  W Y d	}~nd	}~ww Y nw W d	   d	S 1 sw   Y  d	S )aJ  
    Log model graph to TensorBoard.

    This function attempts to visualize the model architecture in TensorBoard by tracing the model with a dummy input
    tensor. It first tries a simple method suitable for YOLO models, and if that fails, falls back to a more complex
    approach for models like RTDETR that may require special handling.

    Args:
        trainer (BaseTrainer): The trainer object containing the model to visualize. Must have attributes:
            - model: PyTorch model to visualize
            - args: Configuration arguments with 'imgsz' attribute

    Notes:
        This function requires TensorBoard integration to be enabled and the global WRITER to be initialized.
        It handles potential warnings from the PyTorch JIT tracer and attempts to gracefully handle different
        model architectures.
          )devicedtypeignore)categoryF)strictu#   model graph visualization added ✅N)verboseexportTtorchscriptz(TensorBoard graph visualization failure )"argsimgsz
isinstanceintnextmodel
parameterstorchzerosr   r   warningscatch_warningssimplefilterUserWarningjitTracerWarningevalr   	add_graphtracer   de_parallelr   infoPREFIX	Exceptionr   fusemoduleshasattrr   formatwarning)trainerr    pimr$   mer   r   r   _log_tensorboard_graph+   sD   

"
 "r?   c              
   C   sp   t r6zt t| jatt d| j d W dS  ty5 } ztt d|  W Y d}~dS d}~ww dS )z2Initialize TensorBoard logging with SummaryWriter.z!Start with 'tensorboard --logdir z!', view at http://localhost:6006/z=TensorBoard not initialized correctly, not logging this run. N)	r	   strsave_dirr   r   r2   r3   r4   r9   )r:   r>   r   r   r   on_pretrain_routine_start_   s   "rB   c                 C   s   t rt|  dS dS )zLog TensorBoard graph.N)r   r?   r:   r   r   r   on_train_startj   s   rD   c                 C   s2   t | j| jdd| jd  t | j| jd  dS )z6Logs scalar statistics at the end of a training epoch.train)prefixr   N)r   label_loss_itemstlossepochlrrC   r   r   r   on_train_epoch_endp   s   rK   c                 C   s   t | j| jd  dS )z,Logs epoch metrics at end of training epoch.r   N)r   metricsrI   rC   r   r   r   on_fit_epoch_endv   s   rM   )rB   rD   rM   rK   )r   )r   N)ultralytics.utilsr   r   r   r   r   r   r3   r(   copyr   r&   torch.utils.tensorboardr	   ImportErrorAssertionError	TypeErrorAttributeErrordictr"   r   r?   rB   rD   rK   rM   	callbacksr   r   r   r   <module>   s:   

4


