o
    oipa                     @   s(  d Z ddlZddlmZ ddlmZ ddlmZmZm	Z	m
Z
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mZmZmZ dd
lmZ ddlmZ ddl m!Z!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z(m)Z) erddl*m+Z+ ddl,m-Z- ddl.m/Z/ edZ0G dd de!Z1dS )z5
Weights and Biases Logger
-------------------------
    N)	Namespace)Path)TYPE_CHECKINGAnyDictListLiteralMappingOptionalUnion)RequirementCache)Tensor)override)_add_prefix_convert_json_serializable_convert_params_sanitize_callable_params)_PATH)ModelCheckpoint)Loggerrank_zero_experiment)_scan_checkpoints)MisconfigurationException)rank_zero_onlyrank_zero_warn)ArtifactRunDisabledRunzwandb>=0.12.10c                       sL  e Zd ZdZdZ												dUdee ded	ee d
edee dee dee dee de	e
d ef de	d dedee deddf fddZdeeef fddZeede	d fddZ	 dVd!ejd"ee d#ed$eddf
d%d&Zeed'e	eeef ef ddfd(d)ZeedWd*eeef d+ee ddfd,d-Ze				dXd.ed/eee  d0eeee   d1ed+ee ddfd2d3Ze				dXd.ed/eee  d0eeee   d1ed+ee ddfd4d5ZedWd.ed6ee d+ee deddf
d7d8Z edWd.ed9ee d+ee deddf
d:d;Z!edWd.ed<ee d+ee deddf
d=d>Z"eedee fd?d@Z#eedee fdAdBZ$eedee fdCdDZ%edEe&ddfdFdGZ'e(e			 dYdHedee dIee dJee def
dKdLZ)dWdHedIee ddMfdNdOZ*eedPeddfdQdRZ+dEe&ddfdSdTZ,  Z-S )ZWandbLoggera   Log using `Weights and Biases <https://docs.wandb.ai/integrations/lightning>`_.

    **Installation and set-up**

    Install with pip:

    .. code-block:: bash

        pip install wandb

    Create a `WandbLogger` instance:

    .. code-block:: python

        from lightning.pytorch.loggers import WandbLogger

        wandb_logger = WandbLogger(project="MNIST")

    Pass the logger instance to the `Trainer`:

    .. code-block:: python

        trainer = Trainer(logger=wandb_logger)

    A new W&B run will be created when training starts if you have not created one manually before with `wandb.init()`.

    **Log metrics**

    Log from :class:`~lightning.pytorch.core.LightningModule`:

    .. code-block:: python

        class LitModule(LightningModule):
            def training_step(self, batch, batch_idx):
                self.log("train/loss", loss)

    Use directly wandb module:

    .. code-block:: python

        wandb.log({"train/loss": loss})

    **Log hyper-parameters**

    Save :class:`~lightning.pytorch.core.LightningModule` parameters:

    .. code-block:: python

        class LitModule(LightningModule):
            def __init__(self, *args, **kwarg):
                self.save_hyperparameters()

    Add other config parameters:

    .. code-block:: python

        # add one parameter
        wandb_logger.experiment.config["key"] = value

        # add multiple parameters
        wandb_logger.experiment.config.update({key1: val1, key2: val2})

        # use directly wandb module
        wandb.config["key"] = value
        wandb.config.update()

    **Log gradients, parameters and model topology**

    Call the `watch` method for automatically tracking gradients:

    .. code-block:: python

        # log gradients and model topology
        wandb_logger.watch(model)

        # log gradients, parameter histogram and model topology
        wandb_logger.watch(model, log="all")

        # change log frequency of gradients and parameters (100 steps by default)
        wandb_logger.watch(model, log_freq=500)

        # do not log graph (in case of errors)
        wandb_logger.watch(model, log_graph=False)

    The `watch` method adds hooks to the model which can be removed at the end of training:

    .. code-block:: python

        wandb_logger.experiment.unwatch(model)

    **Log model checkpoints**

    Log model checkpoints at the end of training:

    .. code-block:: python

        wandb_logger = WandbLogger(log_model=True)

    Log model checkpoints as they get created during training:

    .. code-block:: python

        wandb_logger = WandbLogger(log_model="all")

    Custom checkpointing can be set up through :class:`~lightning.pytorch.callbacks.ModelCheckpoint`:

    .. code-block:: python

        # log model only if `val_accuracy` increases
        wandb_logger = WandbLogger(log_model="all")
        checkpoint_callback = ModelCheckpoint(monitor="val_accuracy", mode="max")
        trainer = Trainer(logger=wandb_logger, callbacks=[checkpoint_callback])

    `latest` and `best` aliases are automatically set to easily retrieve a model checkpoint:

    .. code-block:: python

        # reference can be retrieved in artifacts panel
        # "VERSION" can be a version (ex: "v2") or an alias ("latest or "best")
        checkpoint_reference = "USER/PROJECT/MODEL-RUN_ID:VERSION"

        # download checkpoint locally (if not already cached)
        run = wandb.init(project="MNIST")
        artifact = run.use_artifact(checkpoint_reference, type="model")
        artifact_dir = artifact.download()

        # load checkpoint
        model = LitModule.load_from_checkpoint(Path(artifact_dir) / "model.ckpt")

    **Log media**

    Log text with:

    .. code-block:: python

        # using columns and data
        columns = ["input", "label", "prediction"]
        data = [["cheese", "english", "english"], ["fromage", "french", "spanish"]]
        wandb_logger.log_text(key="samples", columns=columns, data=data)

        # using a pandas DataFrame
        wandb_logger.log_text(key="samples", dataframe=my_dataframe)

    Log images with:

    .. code-block:: python

        # using tensors, numpy arrays or PIL images
        wandb_logger.log_image(key="samples", images=[img1, img2])

        # adding captions
        wandb_logger.log_image(key="samples", images=[img1, img2], caption=["tree", "person"])

        # using file path
        wandb_logger.log_image(key="samples", images=["img_1.jpg", "img_2.jpg"])

    More arguments can be passed for logging segmentation masks and bounding boxes. Refer to
    `Image Overlays documentation <https://docs.wandb.ai/guides/track/log/media#image-overlays>`_.

    **Log Tables**

    `W&B Tables <https://docs.wandb.ai/guides/tables/visualize-tables>`_ can be used to log,
    query and analyze tabular data.

    They support any type of media (text, image, video, audio, molecule, html, etc) and are great for storing,
    understanding and sharing any form of data, from datasets to model predictions.

    .. code-block:: python

        columns = ["caption", "image", "sound"]
        data = [["cheese", wandb.Image(img_1), wandb.Audio(snd_1)], ["wine", wandb.Image(img_2), wandb.Audio(snd_2)]]
        wandb_logger.log_table(key="samples", columns=columns, data=data)


    **Downloading and Using Artifacts**

    To download an artifact without starting a run, call the ``download_artifact``
    function on the class:

    .. code-block:: python

        from lightning.pytorch.loggers import WandbLogger

        artifact_dir = WandbLogger.download_artifact(artifact="path/to/artifact")

    To download an artifact and link it to an ongoing run call the ``download_artifact``
    function on the logger instance:

    .. code-block:: python

        class MyModule(LightningModule):
            def any_lightning_module_function_or_hook(self):
                self.logger.download_artifact(artifact="path/to/artifact")

    To link an artifact from a previous run you can use ``use_artifact`` function:

    .. code-block:: python

        from lightning.pytorch.loggers import WandbLogger

        wandb_logger = WandbLogger(project="my_project", name="my_run")
        wandb_logger.use_artifact(artifact="path/to/artifact")

    See Also:
        - `Demo in Google Colab <http://wandb.me/lightning>`__ with hyperparameter search and model logging
        - `W&B Documentation <https://docs.wandb.ai/integrations/lightning>`__

    Args:
        name: Display name for the run.
        save_dir: Path where data is saved.
        version: Sets the version, mainly used to resume a previous run.
        offline: Run offline (data can be streamed later to wandb servers).
        dir: Same as save_dir.
        id: Same as version.
        anonymous: Enables or explicitly disables anonymous logging.
        project: The name of the project to which this run will belong. If not set, the environment variable
            `WANDB_PROJECT` will be used as a fallback. If both are not set, it defaults to ``'lightning_logs'``.
        log_model: Log checkpoints created by :class:`~lightning.pytorch.callbacks.ModelCheckpoint`
            as W&B artifacts. `latest` and `best` aliases are automatically set.

            * if ``log_model == 'all'``, checkpoints are logged during training.
            * if ``log_model == True``, checkpoints are logged at the end of training, except when
              :paramref:`~lightning.pytorch.callbacks.ModelCheckpoint.save_top_k` ``== -1``
              which also logs every checkpoint during training.
            * if ``log_model == False`` (default), no checkpoint is logged.

        prefix: A string to put at the beginning of metric keys.
        experiment: WandB experiment object. Automatically set when creating a run.
        checkpoint_name: Name of the model checkpoint artifact being logged.
        \**kwargs: Arguments passed to :func:`wandb.init` like `entity`, `group`, `tags`, etc.

    Raises:
        ModuleNotFoundError:
            If required WandB package is not installed on the device.
        MisconfigurationException:
            If both ``log_model`` and ``offline`` is set to ``True``.

    -N.F namesave_dirversionofflinedirid	anonymousproject	log_modelall
experiment)r   r   Nprefixcheckpoint_namekwargsreturnc                    s  t sttt |r|	rtd|	 d| dt   || _|	| _|| _|
| _	i | _
d | _|d ur8t|}n	|d urAt|}|pItjdd}|||pO||pR|d|rWdnd d| _| jjdi | | jd| _| jd	| _| jd
| _| jd| _|| _d S )NzProviding log_model=z and offline=z is an invalid configuration since model checkpoints cannot be uploaded in offline mode.
Hint: Set `offline=False` to log your model.WANDB_PROJECTlightning_logsallow)r$   r+   r(   r)   resumer*   r+   r(   r$   r)    )_WANDB_AVAILABLEModuleNotFoundErrorstrr   super__init___offline
_log_model_prefix_experiment_logged_model_time_checkpoint_callbackosfspathenvironget_wandb_initupdate_project	_save_dir_name_id_checkpoint_name)selfr$   r%   r&   r'   r(   r)   r*   r+   r,   r.   r/   r0   r1   	__class__r7   S/home/ubuntu/.local/lib/python3.10/site-packages/lightning/pytorch/loggers/wandb.pyr<   $  s>   



zWandbLogger.__init__c                 C   sh   dd l }|d | j}| j }| jd ur.t| jdd |d< t| jdd |d< | jj|d< d |d< |S )Nr   servicer)   rL   
_attach_idrK   r@   )wandbrequirer.   __dict__copyr@   getattrr$   )rN   rT   _stater7   r7   rQ   __getstate___  s   


zWandbLogger.__getstate__)r   r   c                 C   s   ddl }ddlm} ddlm} | jdu rm| jrdtjd< t	| dd}|j
dur3td |j
| _| jS |durEt|d	rE||| _| jS |jdi | j| _t| j||frmt	| jd
drm| jd | jjdddd | jS )zActual wandb object. To use wandb features in your :class:`~lightning.pytorch.core.LightningModule` do the
        following.

        Example::

        .. code-block:: python

            self.logger.experiment.some_wandb_function()

        r   Nr   r   dryrun
WANDB_MODErS   zThere is a wandb run already in progress and newly created instances of `WandbLogger` will reuse this run. If this is not desired, call `wandb.finish()` before instantiating `WandbLogger`._attachdefine_metrictrainer/global_step*T)step_metric	step_syncr7   )rT   wandb.sdk.libr   wandb.wandb_runr   r@   r=   rC   rE   rX   runr   hasattrr^   initrG   
isinstancer_   )rN   rT   r   r   	attach_idr7   r7   rQ   r.   t  s.   


zWandbLogger.experiment	gradientsd   Tmodelloglog_freq	log_graphc                 C   s   | j j||||d d S )N)rn   ro   rp   )r.   watch)rN   rm   rn   ro   rp   r7   r7   rQ   rq     s   zWandbLogger.watchparamsc                 C   s.   t |}t|}t|}| jjj|dd d S )NT)allow_val_change)r   r   r   r.   configrH   )rN   rr   r7   r7   rQ   log_hyperparams  s   zWandbLogger.log_hyperparamsmetricsstepc                 C   sZ   t jdks	J dt|| j| j}|d ur%| jt|fi d|i d S | j| d S )Nr   z-experiment tried to log from global_rank != 0r`   )r   rankr   r?   LOGGER_JOIN_CHARr.   rn   dict)rN   rv   rw   r7   r7   rQ   log_metrics  s
    zWandbLogger.log_metricskeycolumnsdata	dataframec                 C   s,   ddl }||j|||di}| || dS )zLog a Table containing any object type (text, image, audio, video, molecule, html, etc).

        Can be defined either with `columns` and `data` or with `dataframe`.

        r   N)r}   r~   r   )rT   Tabler{   )rN   r|   r}   r~   r   rw   rT   rv   r7   r7   rQ   	log_table  s   zWandbLogger.log_tablec                 C   s   |  ||||| dS )zlLog text as a Table.

        Can be defined either with `columns` and `data` or with `dataframe`.

        N)r   )rN   r|   r}   r~   r   rw   r7   r7   rQ   log_text  s   zWandbLogger.log_textimagesc           
            t |tstdt| t|}  D ]\}}t||kr/td| dt| d| q fddt|D }ddl|fd	dt	||D i}	| 
|	| dS )
zLog images (tensors, numpy arrays, PIL Images or file paths).

        Optional kwargs are lists passed to each image (ex: caption, masks, boxes).

        z#Expected a list as "images", found 	Expected  items but only found  for c                        g | ]  fd dD qS )c                       i | ]	}||   qS r7   r7   .0kir1   r7   rQ   
<dictcomp>      z4WandbLogger.log_image.<locals>.<listcomp>.<dictcomp>r7   r   r1   r   rQ   
<listcomp>       z)WandbLogger.log_image.<locals>.<listcomp>r   Nc                    "   g | ]\}} j |fi |qS r7   )Image)r   imgkwargrT   r7   rQ   r        " ri   list	TypeErrortypelenitems
ValueErrorrangerT   zipr{   )
rN   r|   r   rw   r1   nr   v
kwarg_listrv   r7   r1   rT   rQ   	log_image  s   
zWandbLogger.log_imageaudiosc           
         r   )
a  Log audios (numpy arrays, or file paths).

        Args:
            key: The key to be used for logging the audio files
            audios: The list of audio file paths, or numpy arrays to be logged
            step: The step number to be used for logging the audio files
            \**kwargs: Optional kwargs are lists passed to each ``Wandb.Audio`` instance (ex: caption, sample_rate).

        Optional kwargs are lists passed to each audio (ex: caption, sample_rate).

        z#Expected a list as "audios", found r   r   r   c                    r   )c                    r   r7   r7   r   r   r7   rQ   r     r   z4WandbLogger.log_audio.<locals>.<listcomp>.<dictcomp>r7   r   r   r   rQ   r     r   z)WandbLogger.log_audio.<locals>.<listcomp>r   Nc                    r   r7   )Audio)r   audior   r   r7   rQ   r     r   r   )
rN   r|   r   rw   r1   r   r   r   r   rv   r7   r   rQ   	log_audio     
zWandbLogger.log_audiovideosc           
         r   )
a  Log videos (numpy arrays, or file paths).

        Args:
            key: The key to be used for logging the video files
            videos: The list of video file paths, or numpy arrays to be logged
            step: The step number to be used for logging the video files
            **kwargs: Optional kwargs are lists passed to each Wandb.Video instance (ex: caption, fps, format).

        Optional kwargs are lists passed to each video (ex: caption, fps, format).

        z#Expected a list as "videos", found r   r   r   c                    r   )c                    r   r7   r7   r   r   r7   rQ   r     r   z4WandbLogger.log_video.<locals>.<listcomp>.<dictcomp>r7   r   r   r   rQ   r     r   z)WandbLogger.log_video.<locals>.<listcomp>r   Nc                    r   r7   )Video)r   videor   r   r7   rQ   r   "  r   r   )
rN   r|   r   rw   r1   r   r   r   r   rv   r7   r   rQ   	log_video  r   zWandbLogger.log_videoc                 C      | j S )z`Gets the save directory.

        Returns:
            The path to the save directory.

        )rJ   rN   r7   r7   rQ   r%   %  s   	zWandbLogger.save_dirc                 C   r   )a  The project name of this experiment.

        Returns:
            The name of the project the current experiment belongs to. This name is not the same as `wandb.Run`'s
            name. To access wandb's internal experiment name, use ``logger.experiment.name`` instead.

        )rI   r   r7   r7   rQ   r$   0  s   
zWandbLogger.namec                 C   s   | j r| j jS | jS )zGets the id of the experiment.

        Returns:
            The id of the experiment if the experiment exists else the id given to the constructor.

        )r@   r)   rL   r   r7   r7   rQ   r&   <  s   
zWandbLogger.versioncheckpoint_callbackc                 C   sD   | j dks| j du r|jdkr| | d S | j du r || _d S d S )Nr-   T)r>   
save_top_k_scan_and_log_checkpointsrB   )rN   r   r7   r7   rQ   after_save_checkpointH  s
   

z!WandbLogger.after_save_checkpointartifactartifact_typeuse_artifactc                 C   s\   ddl }|jdur|r|j| } n| }|j| |d} |du r#dnt|}| j|dS )a  Downloads an artifact from the wandb server.

        Args:
            artifact: The path of the artifact to download.
            save_dir: The directory to save the artifact to.
            artifact_type: The type of artifact to download.
            use_artifact: Whether to add an edge between the artifact graph.

        Returns:
            The path to the downloaded artifact.

        r   Nr   )root)rT   rf   r   Apir   rC   rD   download)r   r%   r   r   rT   apir7   r7   rQ   download_artifactP  s   zWandbLogger.download_artifactr   c                 C   s   | j j||dS )a  Logs to the wandb dashboard that the mentioned artifact is used by the run.

        Args:
            artifact: The path of the artifact.
            artifact_type: The type of artifact being used.

        Returns:
            wandb Artifact object for the artifact.

        r   )r.   r   )rN   r   r   r7   r7   rQ   r   o  s   zWandbLogger.use_artifactstatusc                 C   s4   |dkrd S | j r| jd ur| | j  d S d S d S )Nsuccess)rB   r@   r   )rN   r   r7   r7   rQ   finalize|  s
   zWandbLogger.finalizec              	      s   dd l }t | j}|D ]W\}}}}dt|tr| n|dt|j jj	 fdddD i}| j
s:d| jj | _
|j| j
d|d	}	|	j|d
d | jkrSddgndg}
| jj|	|
d || j|< qd S )Nr   scoreoriginal_filenamec                    s"   i | ]}t  |r|t |qS r7   )rg   rX   r   r   r7   rQ   r     s    	
z9WandbLogger._scan_and_log_checkpoints.<locals>.<dictcomp>)monitormode	save_lastr   save_weights_only_every_n_train_stepszmodel-rm   )r$   r   metadataz
model.ckpt)r$   latestbest)aliases)rT   r   rA   ri   r   itemr   r$   rP   __name__rM   r.   r)   r   add_filebest_model_pathlog_artifact)rN   r   rT   checkpointstpstagr   r   r   r7   r   rQ   r     s"   
z%WandbLogger._scan_and_log_checkpoints)Nr"   NFNNNNFNr#   N)rk   rl   T)N)NNNN)NNT).r   
__module____qualname____doc__ry   r
   r:   r   boolr   r   r   r<   r   r[   propertyr   r.   nnModuleintrq   r   r   r   ru   r	   floatr{   r   r   r   r   r   r   r%   r$   r&   r   r   staticmethodr   r   r   r   __classcell__r7   r7   rO   rQ   r    2   s    p	
;,
&(	

***	

r    )2r   rC   argparser   pathlibr   typingr   r   r   r   r   r	   r
   r   torch.nnr    lightning_utilities.core.importsr   torchr   typing_extensionsr   !lightning.fabric.utilities.loggerr   r   r   r    lightning.fabric.utilities.typesr   ,lightning.pytorch.callbacks.model_checkpointr    lightning.pytorch.loggers.loggerr   r   #lightning.pytorch.loggers.utilitiesr   &lightning.pytorch.utilities.exceptionsr   %lightning.pytorch.utilities.rank_zeror   r   rT   r   rd   r   re   r   r8   r    r7   r7   r7   rQ   <module>   s,   (