o
    oi2(                     @   s   d Z ddlZddlmZ ddlmZmZmZmZ 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 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 ddlmZ ddl m!Z! ddl"m#Z#m$Z$ G dd deeZdS )z'
TensorBoard Logger
------------------
    N)	Namespace)AnyDictOptionalUnion)Tensor)override)_TENSORBOARD_AVAILABLE)TensorBoardLogger)_is_dir)_convert_params)_PATH)ModelCheckpoint)save_hparams_to_yaml)Logger)_OMEGACONF_AVAILABLE)rank_zero_onlyrank_zero_warnc                       sr  e Zd ZdZdZ						d,ded	ee d
eee	ef  de
de
dedee def fddZeedef fddZeedefddZeedefddZee	d-deeeef ef deeeef  ddf fddZee	d-dddee ddfd d!Zeed. fd"d#Zeed$eddf fd%d&Zed'eddfd(d)Zede	fd*d+Z  ZS )/r
   aR	  Log to local or remote file system in `TensorBoard <https://www.tensorflow.org/tensorboard>`_ format.

    Implemented using :class:`~tensorboardX.SummaryWriter`. Logs are saved to
    ``os.path.join(save_dir, name, version)``. This is the default logger in Lightning, it comes
    preinstalled.

    This logger supports logging to remote filesystems via ``fsspec``. Make sure you have it installed
    and you don't have tensorflow (otherwise it will use tf.io.gfile instead of fsspec).

    Example:

    .. testcode::
        :skipif: not _TENSORBOARD_AVAILABLE or not _TENSORBOARDX_AVAILABLE

        from lightning.pytorch import Trainer
        from lightning.pytorch.loggers import TensorBoardLogger

        logger = TensorBoardLogger("tb_logs", name="my_model")
        trainer = Trainer(logger=logger)

    Args:
        save_dir: Save directory
        name: Experiment name. Defaults to ``'default'``. If it is the empty string then no per-experiment
            subdirectory is used.
        version: Experiment version. If version is not specified the logger inspects the save
            directory for existing versions, then automatically assigns the next available version.
            If it is a string then it is used as the run-specific subdirectory name,
            otherwise ``'version_${version}'`` is used.
        log_graph: Adds the computational graph to tensorboard. This requires that
            the user has defined the `self.example_input_array` attribute in their
            model.
        default_hp_metric: Enables a placeholder metric with key `hp_metric` when `log_hyperparams` is
            called without a metric (otherwise calls to log_hyperparams without a metric are ignored).
        prefix: A string to put at the beginning of metric keys.
        sub_dir: Sub-directory to group TensorBoard logs. If a sub_dir argument is passed
            then logs are saved in ``/save_dir/name/version/sub_dir/``. Defaults to ``None`` in which
            logs are saved in ``/save_dir/name/version/``.
        \**kwargs: Additional arguments used by :class:`tensorboardX.SummaryWriter` can be passed as keyword
            arguments in this logger. To automatically flush to disk, `max_queue` sets the size
            of the queue for pending logs before flushing. `flush_secs` determines how many seconds
            elapses before flushing.
    zhparams.yamllightning_logsNFT save_dirnameversion	log_graphdefault_hp_metricprefixsub_dirkwargsc           	   	      sN   t  jd||||||d| |rtstdtt  |o t| _i | _d S )N)root_dirr   r   r   r   r   zPYou set `TensorBoardLogger(log_graph=True)` but `tensorboard` is not available.
 )super__init__r	   r   str
_log_graphhparams)	selfr   r   r   r   r   r   r   r   	__class__r   Y/home/ubuntu/.local/lib/python3.10/site-packages/lightning/pytorch/loggers/tensorboard.pyr!   U   s$   	

zTensorBoardLogger.__init__returnc                    s   t jt j| jS )zParent directory for all tensorboard checkpoint subdirectories.

        If the experiment name parameter is an empty string, no experiment subdirectory is used and the checkpoint will
        be saved in "save_dir/version"

        )ospathjoinr    r   r   r%   r&   r   r(   r   q   s   	zTensorBoardLogger.root_dirc                 C   sf   t | jtr	| jnd| j }tj| j|}t | jtr%tj|| j}tj|}tj	|}|S )zThe directory for this run's tensorboard checkpoint.

        By default, it is named ``'version_${self.version}'`` but it can be overridden by passing a string value for the
        constructor's version parameter instead of ``None`` or an int.

        version_)

isinstancer   r"   r*   r+   r,   r   r   
expandvars
expanduser)r%   r   log_dirr   r   r(   r2   |   s   
zTensorBoardLogger.log_dirc                 C   s   | j S )zGets the save directory where the TensorBoard experiments are saved.

        Returns:
            The local path to the save directory where the TensorBoard experiments are saved.

        )	_root_dirr-   r   r   r(   r      s   	zTensorBoardLogger.save_dirparamsmetricsc                    sX   t r
ddlm}m} t|}t rt||r|| j|| _n| j| t	 j
||dS )a  Record hyperparameters. TensorBoard logs with and without saved hyperparameters are incompatible, the
        hyperparameters are then not displayed in the TensorBoard. Please delete or move the previously saved logs to
        display the new ones with hyperparameters.

        Args:
            params: a dictionary-like container with the hyperparameters
            metrics: Dictionary with metric names as keys and measured quantities as values

        r   )	Container	OmegaConf)r4   r5   )r   	omegaconfr6   r7   r   r/   merger$   updater    log_hyperparams)r%   r4   r5   r6   r7   r&   r   r(   r;      s   z!TensorBoardLogger.log_hyperparamsmodelzpl.LightningModuleinput_arrayc                 C   s   | j sd S |d u r|jn|}|d u rtd d S t|ttfs+tdt| d d S ||}||}t	j
j  | j|| W d    d S 1 sNw   Y  d S )NzCould not log computational graph to TensorBoard: The `model.example_input_array` attribute is not set or `input_array` was not given.zlCould not log computational graph to TensorBoard: The `input_array` or `model.example_input_array` has type z which can't be traced by TensorBoard. Make the input array a tuple representing the positional arguments to the model's `forward()` implementation.)r#   example_input_arrayr   r/   r   tupletype_on_before_batch_transfer_apply_batch_transfer_handlerplcoremodule_jit_is_scripting
experiment	add_graph)r%   r<   r=   r   r   r(   r      s$   

"zTensorBoardLogger.log_graphc                    sP   t    | j}tj|| j}t| j|r$| j	|s&t
|| j d S d S d S N)r    saver2   r*   r+   r,   NAME_HPARAMS_FILEr   _fsisfiler   r$   )r%   dir_pathhparams_filer&   r   r(   rJ      s   
zTensorBoardLogger.savestatusc                    s$   t  | |dkr|   d S d S )Nsuccess)r    finalizerJ   )r%   rP   r&   r   r(   rR      s   zTensorBoardLogger.finalizecheckpoint_callbackc                 C   s   dS )zCalled after model checkpoint callback saves a new checkpoint.

        Args:
            checkpoint_callback: the model checkpoint callback instance

        Nr   )r%   rS   r   r   r(   after_save_checkpoint   s   z'TensorBoardLogger.after_save_checkpointc                 C   s   | j }z| j|}W n
 ty   Y dS w g }|D ]-}|d }tj|}t| j|rG|drG|	dd 
dd}| rG|t| qt|dkrPdS t|d S )Nr   r   r.   _   /r   )r   rL   listdirOSErrorr*   r+   basenamer   
startswithsplitreplaceisdigitappendintlenmax)r%   r   listdir_infoexisting_versionslistingdbndir_verr   r   r(   _get_next_version   s$   z#TensorBoardLogger._get_next_version)r   NFTr   NrI   )r)   N)__name__
__module____qualname____doc__rK   r   r   r"   r   r`   boolr   r!   propertyr   r   r2   r   r   r   r   r;   r   r   rJ   rR   r   rT   ri   __classcell__r   r   r&   r(   r
   '   s    +				r
   )%rm   r*   argparser   typingr   r   r   r   torchr   typing_extensionsr   lightning.pytorchpytorchrC   $lightning.fabric.loggers.tensorboardr	   r
   FabricTensorBoardLogger#lightning.fabric.utilities.cloud_ior   !lightning.fabric.utilities.loggerr    lightning.fabric.utilities.typesr   lightning.pytorch.callbacksr   lightning.pytorch.core.savingr    lightning.pytorch.loggers.loggerr   #lightning.pytorch.utilities.importsr   %lightning.pytorch.utilities.rank_zeror   r   r   r   r   r(   <module>   s$   