a
    d(                     @   s  d Z ddl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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 ddlmZ ddlmZ ddlmZ ddlm Z m!Z! e"e#Z$erddl%m&Z&m'Z' esesddgZ(G dd deeZdS )z'
TensorBoard Logger
------------------
    N)	Namespace)AnyDictOptionalUnion)Tensor)_TENSORBOARD_AVAILABLE_TENSORBOARDX_AVAILABLE)TensorBoardLogger)_convert_params)_PATH)ModelCheckpoint)save_hparams_to_yaml)Logger)_OMEGACONF_AVAILABLE)rank_zero_onlyrank_zero_warn)	Container	OmegaConfr
   zTensorBoardLogger.*c                
       s(  e Zd ZdZdZd#eee eee	ef  e
e
eee ed fd	d
Zeed fddZeedddZeedddZed$eeeef ef eeeef  dd fddZed%dee ddddZedd fddZeedd fddZedddd Ze	dd!d"Z  ZS )&r
   a	  
    Log to local 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.

    Example:

    .. testcode::

        from pytorch_lightning import Trainer
        from pytorch_lightning.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.

    Example:
        >>> import shutil, tempfile
        >>> tmp = tempfile.mkdtemp()
        >>> tbl = TensorBoardLogger(tmp)
        >>> tbl.log_hyperparams({"epochs": 5, "optimizer": "Adam"})
        >>> tbl.log_metrics({"acc": 0.75})
        >>> tbl.log_metrics({"acc": 0.9})
        >>> tbl.finalize("success")
        >>> shutil.rmtree(tmp)
    zhparams.yamllightning_logsNFT )save_dirnameversion	log_graphdefault_hp_metricprefixsub_dirkwargsc           	   	      sD   t  jf ||||||d| |r0ts0td |o6t| _i | _d S )N)root_dirr   r   r   r   r   zOYou set `TensorBoardLogger(log_graph=True)` but `tensorboard` is not available.)super__init__r   r   
_log_graphhparams)	selfr   r   r   r   r   r   r   r   	__class__ n/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/pytorch_lightning/loggers/tensorboard.pyr!   c   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   |   s    zTensorBoardLogger.root_dirc                 C   sf   t | jtr| jn
d| j }tj| j|}t | jtrJt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   strr*   r+   r,   r   r   
expandvars
expanduser)r$   r   log_dirr'   r'   r(   r3      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.
        )Z	_root_dirr-   r'   r'   r(   r      s    zTensorBoardLogger.save_dir)paramsmetricsr)   c                    sD   t |}tr(t|tr(t| 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
        )r4   r5   )
r   r   r/   r   r   merger#   updater    log_hyperparams)r$   r4   r5   r%   r'   r(   r8      s
    z!TensorBoardLogger.log_hyperparamszpl.LightningModule)modelinput_arrayr)   c                 C   s   | j s
d S |d u r|jn|}|d u r.td nrt|ttfsRtdt| d nN||}||}t	j
j  | j|| W d    n1 s0    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"   Zexample_input_arrayr   r/   r   tupletypeZ_on_before_batch_transferZ_apply_batch_transfer_handlerplcoremoduleZ_jit_is_scriptingZ
experimentZ	add_graph)r$   r9   r:   r'   r'   r(   r      s"    

zTensorBoardLogger.log_graphc                    sH   t    | j}tj|| j}| j|rD| j	|sDt
|| j d S )N)r    saver3   r*   r+   r,   NAME_HPARAMS_FILE_fsisdirisfiler   r#   )r$   Zdir_pathZhparams_filer%   r'   r(   r@      s
    
zTensorBoardLogger.save)statusr)   c                    s    t  | |dkr|   d S )Nsuccess)r    finalizer@   )r$   rE   r%   r'   r(   rG      s    zTensorBoardLogger.finalize)checkpoint_callbackr)   c                 C   s   dS )zCalled after model checkpoint callback saves a new checkpoint.

        Args:
            checkpoint_callback: the model checkpoint callback instance
        Nr'   )r$   rH   r'   r'   r(   after_save_checkpoint   s    z'TensorBoardLogger.after_save_checkpointc                 C   s   | j }z| j|}W n  ty6   td| Y dS 0 g }|D ]R}|d }tj|}| j	|r@|
dr@|dd dd}|t| q@t|dkrdS t|d S )	NzMissing logger folder: %sr   r   r.   _   /r   )r   rB   listdirOSErrorlogwarningr*   r+   basenamerC   
startswithsplitreplaceappendintlenmax)r$   r   Zlistdir_infoZexisting_versionslistingdZbnZdir_verr'   r'   r(   _get_next_version   s     z#TensorBoardLogger._get_next_version)r   NFTr   N)N)N)__name__
__module____qualname____doc__rA   r   r   r0   r   rV   boolr   r!   propertyr   r3   r   r   r   r   r8   r   r   r@   rG   r   rI   r[   __classcell__r'   r'   r%   r(   r
   /   sL   1        ))r_   loggingr*   argparser   typingr   r   r   r   Ztorchr   Zpytorch_lightningr=   Z$lightning_fabric.loggers.tensorboardr   r	   r
   ZFabricTensorBoardLoggerZ!lightning_fabric.utilities.loggerr   Z lightning_fabric.utilities.typesr   Zpytorch_lightning.callbacksr   Zpytorch_lightning.core.savingr   Z pytorch_lightning.loggers.loggerr   Z#pytorch_lightning.utilities.importsr   Z%pytorch_lightning.utilities.rank_zeror   r   	getLoggerr\   rO   Z	omegaconfr   r   Z__doctest_skip__r'   r'   r'   r(   <module>   s*   
