
    gm                        d dl 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	m
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mZ g Z e            re                    ej                    e            re                    ej                    e            re                    ej                    e            re                    ej                    e            re                    ej                     e            re                    ej!                    e            re                    ej"                    ee#          Z$d Z%d	 Z& G d
 d          Z' G d de'          Z( G d de'          Z) G d de'          Z* G d de'          Z+ G d de'          Z, G d de'          Z- G d de'          Z.e+e*e,e(e)e-e.dZ/	 ddee
e0ee'f                  de
e0ej1        f         fdZ2dS )    Nwraps)AnyDictListOptionalUnion   )
get_logger)PartialState)	
LoggerTypeis_aim_availableis_clearml_availableis_comet_ml_availableis_dvclive_availableis_mlflow_availableis_tensorboard_availableis_wandb_availablelistifyc                 <     t                      fd            }|S )a  
    Decorator to selectively run the decorated function on the main process only based on the `main_process_only`
    attribute in a class.

    Checks at function execution rather than initialization time, not triggering the initialization of the
    `PartialState`.
    c                     t          | dd          r+ t                                                    | g|R i |S  | g|R i |S )Nmain_process_onlyF)getattrr   on_main_process)selfargskwargsfunctions      O/var/www/html/ai-engine/env/lib/python3.11/site-packages/accelerate/tracking.pyexecute_on_main_processz0on_main_process.<locals>.execute_on_main_processL   sj    4,e44 	3;<>>11(;;DR4RRR6RRR8D242226222    r   )r   r    s   ` r   r   r   C   s6     8__3 3 3 3 _3 #"r!   c                      t           S )z@Returns a list of all supported available trackers in the system)_available_trackers r!   r   get_available_trackersr%   V   s    r!   c                   L    e Zd ZdZdZddZdefdZdedee	         fdZ
d	 Zd
S )GeneralTrackera`  
    A base Tracker class to be used for all logging integration implementations.

    Each function should take in `**kwargs` that will automatically be passed in from a base dictionary provided to
    [`Accelerator`].

    Should implement `name`, `requires_logging_directory`, and `tracker` properties such that:

    `name` (`str`): String representation of the tracker class name, such as "TensorBoard" `requires_logging_directory`
    (`bool`): Whether the logger requires a directory to store their logs. `tracker` (`object`): Should return internal
    tracking mechanism used by a tracker class (such as the `run` for wandb)

    Implementations can also include a `main_process_only` (`bool`) attribute to toggle if relevent logging, init, and
    other functions should occur on the main process or across all processes (by default will use `True`)
    TFc                 <   |sd}t          | d          s|dz  }t          | d          st          |          dk    r|dz  }|dz  }dt          |           vrt          |          dk    r|dz  }|d	z  }t          |          dk    rt          d
|           d S d S )N namez`name`requires_logging_directoryr   z, z`requires_logging_directory`trackerz	`tracker`zThe implementation for this tracker class is missing the following required attributes. Please define them in the class definition: )hasattrlendirNotImplementedError)r   _blankerrs      r   __init__zGeneralTracker.__init__n   s     	C4((  x4!=>> 6s88a<<4KC55 D		))s88a<<4KC{"3xx!||)   	 	 |r!   valuesc                     dS )a  
        Logs `values` as hyperparameters for the run. Implementations should use the experiment configuration
        functionality of a tracking API.

        Args:
            values (Dictionary `str` to `bool`, `str`, `float` or `int`):
                Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`,
                `str`, `float`, `int`, or `None`.
        Nr$   r   r4   s     r   store_init_configurationz'GeneralTracker.store_init_configuration   s	     	r!   stepc                     dS )a  
        Logs `values` to the current run. Base `log` implementations of a tracking API should go in here, along with
        special behavior for the `step parameter.

        Args:
            values (Dictionary `str` to `str`, `float`, or `int`):
                Values to be logged as key-value pairs. The values need to have type `str`, `float`, or `int`.
            step (`int`, *optional*):
                The run step. If included, the log will be affiliated with this step.
        Nr$   r   r4   r8   r   s       r   logzGeneralTracker.log   s	     	r!   c                     dS )z
        Should run any finalizing functions within the tracking API. If the API should not have one, just don't
        overwrite that method.
        Nr$   r   s    r   finishzGeneralTracker.finish   s	    
 	r!   N)F)__name__
__module____qualname____doc__r   r3   dictr7   r   intr;   r>   r$   r!   r   r'   r'   [   s              ,
t 
 
 
 
$ hsm        r!   r'   c                        e Zd ZdZdZdZededeee	j
        f         f fd            Zed             Zedefd	            Zeddedee         fd            Zededee         fd            Zed             Z xZS )TensorBoardTrackera  
    A `Tracker` class that supports `tensorboard`. Should be initialized at the start of your script.

    Args:
        run_name (`str`):
            The name of the experiment run
        logging_dir (`str`, `os.PathLike`):
            Location for TensorBoard logs to be stored.
        **kwargs (additional keyword arguments, *optional*):
            Additional key word arguments passed along to the `tensorboard.SummaryWriter.__init__` method.
    tensorboardTrun_namelogging_dirc                    	 ddl m} n# t          $ r dd l}Y nw xY wt	                                                       || _        t          j        	                    ||          | _
         |j        | j
        fi || _        t                              d| j         d| j
                    t                              d           d S )Nr   )rG   z Initialized TensorBoard project z logging to aMake sure to log any initial configurations with `self.store_init_configuration` before training!)torch.utilsrG   ModuleNotFoundErrortensorboardXsuperr3   rH   ospathjoinrI   SummaryWriterwriterloggerdebug)r   rH   rI   r   rG   	__class__s        r   r3   zTensorBoardTracker.__init__   s    	////////" 	/ 	/ 	/......	/ 7<<X>>/k/0@KKFKKeeeSWSceefffo	
 	
 	
 	
 	
s   
 c                     | j         S NrT   r=   s    r   r,   zTensorBoardTracker.tracker   
    {r!   r4   c                 |   | j                             |i            | j                                          t          j                    }t          j                            | j        t          |                    }t	          j	        |d           t          t          j                            |d          d          5 }	 t          j        ||           n3# t          j        j        $ r t                              d            w xY w	 ddd           n# 1 swxY w Y   t                              d           dS )	a  
        Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment. Stores the
        hyperparameters in a yaml file for future use.

        Args:
            values (Dictionary `str` to `bool`, `str`, `float` or `int`):
                Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`,
                `str`, `float`, `int`, or `None`.
        )metric_dictT)exist_okzhparams.ymlwz-Serialization to store hyperparameters failedNzQStored initial configuration hyperparameters to TensorBoard and hparams yaml file)rT   add_hparamsflushtimerP   rQ   rR   rI   strmakedirsopenyamldumprepresenterRepresenterErrorrU   errorrV   )r   r4   project_run_namedir_nameoutfiles        r   r7   z+TensorBoardTracker.store_init_configuration   sX    	B7779;;7<< 0#6F2G2GHH
Ht,,,,"',,x77== 		&'****#4   LMMM +	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	hiiiiis*   ?DCD0DDDDNr8   c                    t          |          }|                                D ]\  }}t          |t          t          f          r | j        j        ||fd|i| 8t          |t                    r | j        j        ||fd|i| dt          |t                    r | j        j
        ||fd|i| | j                                         t                              d           dS )a  
        Logs `values` to the current run.

        Args:
            values (Dictionary `str` to `str`, `float`, `int` or `dict` of `str` to `float`/`int`):
                Values to be logged as key-value pairs. The values need to have type `str`, `float`, `int` or `dict` of
                `str` to `float`/`int`.
            step (`int`, *optional*):
                The run step. If included, the log will be affiliated with this step.
            kwargs:
                Additional key word arguments passed along to either `SummaryWriter.add_scaler`,
                `SummaryWriter.add_text`, or `SummaryWriter.add_scalers` method based on the contents of `values`.
        global_stepz"Successfully logged to TensorBoardN)r   items
isinstancerD   floatrT   
add_scalarrc   add_textrC   add_scalarsra   rU   rV   r   r4   r8   r   kvs         r   r;   zTensorBoardTracker.log   s	    LLNN 	J 	JDAq!c5\** J&&q!HHHHHHHAs## J$$QFFtFvFFFFAt$$ J''1II$I&III9:::::r!   c                     |                                 D ]\  }} | j        j        ||fd|i| t                              d           dS )a  
        Logs `images` to the current run.

        Args:
            values (Dictionary `str` to `List` of `np.ndarray` or `PIL.Image`):
                Values to be logged as key-value pairs. The values need to have type `List` of `np.ndarray` or
            step (`int`, *optional*):
                The run step. If included, the log will be affiliated with this step.
            kwargs:
                Additional key word arguments passed along to the `SummaryWriter.add_image` method.
        ro   z)Successfully logged images to TensorBoardN)rp   rT   
add_imagesrU   rV   rv   s         r   
log_imageszTensorBoardTracker.log_images   sa     LLNN 	E 	EDAq"DK"1aDDTDVDDDD@AAAAAr!   c                 l    | j                                          t                              d           dS )z-
        Closes `TensorBoard` writer
        zTensorBoard writer closedN)rT   closerU   rV   r=   s    r   r>   zTensorBoardTracker.finish  s1    
 	011111r!   rY   )r?   r@   rA   rB   r*   r+   r   rc   r	   rP   PathLiker3   propertyr,   rC   r7   r   rD   r;   r{   r>   __classcell__rW   s   @r   rF   rF      sI       
 
 D!%
 
5bk9I3J 
 
 
 
 
 _
   X jt j j j _j. ; ;$ ;hsm ; ; ; _;2 B BXc] B B B _B  2 2 _2 2 2 2 2r!   rF   c                   N    e Zd ZdZdZdZdZedef fd            Z	e
d             Zedefd            Zedded
ee         fd            Zedded
ee         fd            Ze	 	 	 	 ddedee         deee                  ded
ee         f
d            Zed             Z xZS )WandBTrackeraF  
    A `Tracker` class that supports `wandb`. Should be initialized at the start of your script.

    Args:
        run_name (`str`):
            The name of the experiment run.
        **kwargs (additional keyword arguments, *optional*):
            Additional key word arguments passed along to the `wandb.init` method.
    wandbFrH   c                    t                                                       || _        dd l} |j        dd| j        i|| _        t                              d| j                    t                              d           d S )Nr   projectzInitialized WandB project rK   r$   )rO   r3   rH   r   initrunrU   rV   )r   rH   r   r   rW   s       r   r3   zWandBTracker.__init__#  s     5:>>dm>v>>A$-AABBBo	
 	
 	
 	
 	
r!   c                     | j         S rY   )r   r=   s    r   r,   zWandBTracker.tracker0  s	    xr!   r4   c                 z    ddl }|j                            |d           t                              d           dS )u  
        Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment.

        Args:
            values (Dictionary `str` to `bool`, `str`, `float` or `int`):
                Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`,
                `str`, `float`, `int`, or `None`.
        r   NT)allow_val_changez5Stored initial configuration hyperparameters to WandB)r   configupdaterU   rV   )r   r4   r   s      r   r7   z%WandBTracker.store_init_configuration4  sA     	FT:::LMMMMMr!   Nr8   c                 d     | j         j        |fd|i| t                              d           dS )a,  
        Logs `values` to the current run.

        Args:
            values (Dictionary `str` to `str`, `float`, `int` or `dict` of `str` to `float`/`int`):
                Values to be logged as key-value pairs. The values need to have type `str`, `float`, `int` or `dict` of
                `str` to `float`/`int`.
            step (`int`, *optional*):
                The run step. If included, the log will be affiliated with this step.
            kwargs:
                Additional key word arguments passed along to the `wandb.log` method.
        r8   zSuccessfully logged to WandBN)r   r;   rU   rV   r:   s       r   r;   zWandBTracker.logC  s>     	V11$1&111344444r!   c                     ddl |                                D ]#\  }} | j        |fd|D             ifd|i| $t                              d           dS )a  
        Logs `images` to the current run.

        Args:
            values (Dictionary `str` to `List` of `np.ndarray` or `PIL.Image`):
                Values to be logged as key-value pairs. The values need to have type `List` of `np.ndarray` or
            step (`int`, *optional*):
                The run step. If included, the log will be affiliated with this step.
            kwargs:
                Additional key word arguments passed along to the `wandb.log` method.
        r   Nc                 :    g | ]}                     |          S r$   )Image).0imager   s     r   
<listcomp>z+WandBTracker.log_images.<locals>.<listcomp>d  s%    <<<%++e,,<<<r!   r8   z#Successfully logged images to WandB)r   rp   r;   rU   rV   )r   r4   r8   r   rw   rx   r   s         @r   r{   zWandBTracker.log_imagesT  s     	LLNN 	T 	TDAqDHa<<<<!<<<=SSDSFSSSS:;;;;;r!   
table_namecolumnsdata	dataframec                 b    ddl }||                    |||          i} | j        |fd|i| dS )a  
        Log a Table containing any object type (text, image, audio, video, molecule, html, etc). Can be defined either
        with `columns` and `data` or with `dataframe`.

        Args:
            table_name (`str`):
                The name to give to the logged table on the wandb workspace
            columns (list of `str`, *optional*):
                The name of the columns on the table
            data (List of List of Any data type, *optional*):
                The data to be logged in the table
            dataframe (Any data type, *optional*):
                The data to be logged in the table
            step (`int`, *optional*):
                The run step. If included, the log will be affiliated with this step.
        r   N)r   r   r   r8   )r   Tabler;   )	r   r   r   r   r   r8   r   r   r4   s	            r   	log_tablezWandBTracker.log_tableg  sO    4 	ekk'PYkZZ[--d-f-----r!   c                 l    | j                                          t                              d           dS )z'
        Closes `wandb` writer
        zWandB run closedN)r   r>   rU   rV   r=   s    r   r>   zWandBTracker.finish  s/    
 	'(((((r!   rY   NNNN)r?   r@   rA   rB   r*   r+   r   r   rc   r3   r   r,   rC   r7   r   rD   r;   r{   r   r   r   r>   r   r   s   @r   r   r     s         D!&

 

 

 

 

 

 _

   X Nt N N N _N 5 5$ 5hsm 5 5 5 _5  < < <Xc] < < < _<$  " $". .. c. 49o	.
 . sm. . . _.< ) ) _) ) ) ) )r!   r   c                        e Zd ZdZdZdZedef fd            Ze	d             Z
edefd            Zedded
ee         fd            Zed             Z xZS )CometMLTrackera  
    A `Tracker` class that supports `comet_ml`. Should be initialized at the start of your script.

    API keys must be stored in a Comet config file.

    Args:
        run_name (`str`):
            The name of the experiment run.
        **kwargs (additional keyword arguments, *optional*):
            Additional key word arguments passed along to the `Experiment.__init__` method.
    comet_mlFrH   c                     t                                                       || _        ddlm}  |dd|i|| _        t                              d| j                    t                              d           d S )Nr   )
Experimentproject_namezInitialized CometML project rK   r$   )rO   r3   rH   r   r   rT   rU   rV   )r   rH   r   r   rW   s       r   r3   zCometMLTracker.__init__  s     '''''' jAAhA&AACDMCCDDDo	
 	
 	
 	
 	
r!   c                     | j         S rY   rZ   r=   s    r   r,   zCometMLTracker.tracker  r[   r!   r4   c                 n    | j                             |           t                              d           dS )r   z7Stored initial configuration hyperparameters to CometMLN)rT   log_parametersrU   rV   r6   s     r   r7   z'CometMLTracker.store_init_configuration  s3     	""6***NOOOOOr!   Nr8   c                    || j                             |           |                                D ]\  }}t          |t          t
          f          r | j         j        ||fd|i| 8t          |t                    r | j         j        ||fi | bt          |t                    r | j         j
        |fd|i| t                              d           dS )a  
        Logs `values` to the current run.

        Args:
            values (Dictionary `str` to `str`, `float`, `int` or `dict` of `str` to `float`/`int`):
                Values to be logged as key-value pairs. The values need to have type `str`, `float`, `int` or `dict` of
                `str` to `float`/`int`.
            step (`int`, *optional*):
                The run step. If included, the log will be affiliated with this step.
            kwargs:
                Additional key word arguments passed along to either `Experiment.log_metric`, `Experiment.log_other`,
                or `Experiment.log_metrics` method based on the contents of `values`.
        Nr8   zSuccessfully logged to CometML)rT   set_steprp   rq   rD   rr   
log_metricrc   	log_otherrC   log_metricsrU   rV   rv   s         r   r;   zCometMLTracker.log  s     K  &&&LLNN 	@ 	@DAq!c5\** @&&q!AA$A&AAAAAs## @%%a55f5555At$$ @''??????566666r!   c                 l    | j                                          t                              d           dS )z*
        Closes `comet-ml` writer
        zCometML run closedN)rT   endrU   rV   r=   s    r   r>   zCometMLTracker.finish  s/    
 	)*****r!   rY   )r?   r@   rA   rB   r*   r+   r   rc   r3   r   r,   rC   r7   r   rD   r;   r>   r   r   s   @r   r   r     s        
 
 D!&

 

 

 

 

 

 _

   X 
Pt 
P 
P 
P _
P 7 7$ 7hsm 7 7 7 _72 + + _+ + + + +r!   r   c                   $   e Zd ZdZdZdZeddedee	ee
j        f                  fd            Zed             Zed	efd
            Zed	edee         fd            Zedd	edee         deeeef                  fd            Zed             ZdS )
AimTrackeraF  
    A `Tracker` class that supports `aim`. Should be initialized at the start of your script.

    Args:
        run_name (`str`):
            The name of the experiment run.
        **kwargs (additional keyword arguments, *optional*):
            Additional key word arguments passed along to the `Run.__init__` method.
    aimT.rH   rI   c                     || _         ddlm}  |dd|i|| _        | j         | j        _        t
                              d| j                     t
                              d           d S )Nr   )RunrepozInitialized Aim project rK   r$   )rH   r   r   rT   r*   rU   rV   )r   rH   rI   r   r   s        r   r3   zAimTracker.__init__  s     c55{5f55=???@@@o	
 	
 	
 	
 	
r!   c                     | j         S rY   rZ   r=   s    r   r,   zAimTracker.tracker  r[   r!   r4   c                     || j         d<   dS )
        Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment.

        Args:
            values (`dict`):
                Values to be stored as initial hyperparameters as key-value pairs.
        hparamsNrZ   r6   s     r   r7   z#AimTracker.store_init_configuration  s     "(Ir!   r8   c                 f    |                                 D ]\  }} | j        j        |f||d| dS )a}  
        Logs `values` to the current run.

        Args:
            values (`dict`):
                Values to be logged as key-value pairs.
            step (`int`, *optional*):
                The run step. If included, the log will be affiliated with this step.
            kwargs:
                Additional key word arguments passed along to the `Run.track` method.
        r*   r8   N)rp   rT   track)r   r4   r8   r   keyvalues         r   r;   zAimTracker.log
  sT     !,,.. 	D 	DJCDKeC#DCCFCCCC	D 	Dr!   Nr   c                 0   ddl }i }i }|,|                    di           }|                    di           }|                                D ]J\  }}t          |t                    r|\  }	}
n|d}
}	 |j        |	fd|
i|} | j        j        |f||d| KdS )a  
        Logs `images` to the current run.

        Args:
            values (`Dict[str, Union[np.ndarray, PIL.Image, Tuple[np.ndarray, str], Tuple[PIL.Image, str]]]`):
                Values to be logged as key-value pairs. The values need to have type `np.ndarray` or PIL.Image. If a
                tuple is provided, the first element should be the image and the second element should be the caption.
            step (`int`, *optional*):
                The run step. If included, the log will be affiliated with this step.
            kwargs (`Dict[str, dict]`):
                Additional key word arguments passed along to the `Run.Image` and `Run.track` method specified by the
                keys `aim_image` and `track`, respectively.
        r   N	aim_imager   r)   captionr   )r   getrp   rq   tupler   rT   r   )r   r4   r8   r   r   aim_image_kwtrack_kwr   r   imgr   r   s               r   r{   zAimTracker.log_images  s     	


!::k266Lzz'2..H ,,.. 	J 	JJC%'' )$WW$bW!	#GGwG,GGIDKiIcIIIIII	J 	Jr!   c                 8    | j                                          dS )z%
        Closes `aim` writer
        N)rT   r}   r=   s    r   r>   zAimTracker.finish;  s    
 	r!   )r   NN)r?   r@   rA   rB   r*   r+   r   rc   r   r	   rP   r~   r3   r   r,   rC   r7   rD   r;   r   r{   r>   r$   r!   r   r   r     sZ         D!%

 

 

8E#r{BR<S3T 

 

 

 _

   X (t ( ( ( _( D$ Dhsm D D D _D  J J JXc] J8TXY\^bYbTcKd J J J _J>   _  r!   r   c                   T   e Zd ZdZdZdZe	 	 	 	 	 	 	 ddedee	ee
j        f                  dee         dee	eeef         ef                  d	ee         d
ee         dee         fd            Zed             Zedefd            Zededee         fd            Zed             ZdS )MLflowTrackeru  
    A `Tracker` class that supports `mlflow`. Should be initialized at the start of your script.

    Args:
        experiment_name (`str`, *optional*):
            Name of the experiment. Environment variable MLFLOW_EXPERIMENT_NAME has priority over this argument.
        logging_dir (`str` or `os.PathLike`, defaults to `"."`):
            Location for mlflow logs to be stored.
        run_id (`str`, *optional*):
            If specified, get the run with the specified UUID and log parameters and metrics under that run. The run’s
            end time is unset and its status is set to running, but the run’s other attributes (source_version,
            source_type, etc.) are not changed. Environment variable MLFLOW_RUN_ID has priority over this argument.
        tags (`Dict[str, str]`, *optional*):
            An optional `dict` of `str` keys and values, or a `str` dump from a `dict`, to set as tags on the run. If a
            run is being resumed, these tags are set on the resumed run. If a new run is being created, these tags are
            set on the new run. Environment variable MLFLOW_TAGS has priority over this argument.
        nested_run (`bool`, *optional*, defaults to `False`):
            Controls whether run is nested in parent run. True creates a nested run. Environment variable
            MLFLOW_NESTED_RUN has priority over this argument.
        run_name (`str`, *optional*):
            Name of new run (stored as a mlflow.runName tag). Used only when `run_id` is unspecified.
        description (`str`, *optional*):
            An optional string that populates the description box of the run. If a run is being resumed, the
            description is set on the resumed run. If a new run is being created, the description is set on the new
            run.
    mlflowFNexperiment_namerI   run_idtags
nested_runrH   descriptionc                    t           j                            d|          }t           j                            d|          }t           j                            d|          }t          |t                    rt          j        |          }t           j                            d|          }dd l}|                    d| d          }	t          |	          dk    r;t          |	          d	k    rt                              d
           |	d         j        }
n|                    |||          }
|                    ||
||||          | _        t                              d|            t                              d           d S )NMLFLOW_EXPERIMENT_NAMEMLFLOW_RUN_IDMLFLOW_TAGSMLFLOW_NESTED_RUNr   zname = '')filter_stringr
   z?Multiple experiments with the same name found. Using first one.)r*   artifact_locationr   )r   experiment_idrH   nestedr   r   zInitialized mlflow experiment rK   )rP   environr   rq   rc   jsonloadsr   search_experimentsr.   rU   warningr   create_experiment	start_run
active_runrV   )r   r   rI   r   r   r   rH   r   r   expsr   s              r   r3   zMLflowTracker.__init__b  sx    *..)A?SS88z~~mT22dC   	$:d##DZ^^$7DD
((7T/7T7T7T(UUt99q==4yy1}}`aaa G1MM"44$"- 5  M !**'# + 
 
 	GoGGHHHo	
 	
 	
 	
 	
r!   c                     | j         S rY   )r   r=   s    r   r,   zMLflowTracker.tracker  s
    r!   r4   c           
      t   ddl }t          |                                          D ]j\  }}t          t	          |                    |j        j        j        k    r6t          	                    d| d| d|j        j        j         d           ||= kt          |                                          }t          dt          |          |j        j        j                  D ]>}|                    t          ||||j        j        j        z                                 ?t                              d           dS )r   r   Nz,Accelerate is attempting to log a value of "z" for key "zJ" as a parameter. MLflow's log_param() only accepts values no longer than z) characters so we dropped this attribute.z6Stored initial configuration hyperparameters to MLflow)r   listrp   r.   rc   utils
validationMAX_PARAM_VAL_LENGTHrU   warning_oncerangeMAX_PARAMS_TAGS_PER_BATCH
log_paramsrC   rV   )r   r4   r   r*   r   values_listis          r   r7   z&MLflowTracker.store_init_configuration  sD    	// 	! 	!KD%3u::!8!MMM##_5 _ _UY _ _GM|G^Gs_ _ _   4L6<<>>** q#k**FL,C,]^^ 	l 	lAd;q1v|7N7h3h/h#ijjkkkkMNNNNNr!   r8   c           
      N   i }|                                 D ]X\  }}t          |t          t          f          r|||<   't                              d| dt          |           d| d           Yddl}|                    ||           t          	                    d           dS )	a  
        Logs `values` to the current run.

        Args:
            values (`dict`):
                Values to be logged as key-value pairs.
            step (`int`, *optional*):
                The run step. If included, the log will be affiliated with this step.
        z/MLflowTracker is attempting to log a value of "
" of type 
 for key "zc" as a metric. MLflow's log_metric() only accepts float and int types so we dropped this attribute.r   N)r8   zSuccessfully logged to mlflow)
rp   rq   rD   rr   rU   r   typer   r   rV   )r   r4   r8   metricsrw   rx   r   s          r   r;   zMLflowTracker.log  s     LLNN 	 	DAq!c5\** 

##ka k kSWXYSZSZ k kfg k k k    	7...455555r!   c                 6    ddl }|                                 dS )z,
        End the active MLflow run.
        r   N)r   end_run)r   r   s     r   r>   zMLflowTracker.finish  s#    
 	r!   )NNNNFNN)r?   r@   rA   rB   r*   r+   r   rc   r   r	   rP   r~   r   r   boolr3   r   r,   rC   r7   rD   r;   r>   r$   r!   r   r   r   C  sv        6 D!&  $9= $59%*"&%),
 ,
,
 eC$456,
 	,

 uT#s(^S012,
 TN,
 3-,
 c],
 ,
 ,
 _,
\   X Ot O O O _O6 6$ 6hsm 6 6 6 _60   _  r!   r   c                   x   e Zd ZdZdZdZeddefd            Ze	d             Z
edefd	            Zeddeeeeef         f         d
ee         fd            Zedded
ee         fd            Ze	 	 	 	 ddedee         deee                  ded
ee         f
d            Zed             Zed             ZdS )ClearMLTrackera  
    A `Tracker` class that supports `clearml`. Should be initialized at the start of your script.

    Args:
        run_name (`str`, *optional*):
            Name of the experiment. Environment variables `CLEARML_PROJECT` and `CLEARML_TASK` have priority over this
            argument.
        **kwargs (additional keyword arguments, *optional*):
            Kwargs passed along to the `Task.__init__` method.
    clearmlFNrH   c                 `   ddl m} |                                }d| _        |rd| _        || _        d S |                    dt          j                            d|                     |                    dt          j                            d|                      |j	        d	i || _        d S )
Nr   )TaskFTr   CLEARML_PROJECT	task_nameCLEARML_TASKr$   )
r   r   current_task_initialized_externallytask
setdefaultrP   r   r   r   )r   rH   r   r   r   s        r   r3   zClearMLTracker.__init__  s          ((**',$ 	+/D($DIF."*..9JH*U*UVVV+rz~~nh'O'OPPPDI''''			r!   c                     | j         S rY   )r  r=   s    r   r,   zClearMLTracker.tracker  
    yr!   r4   c                 6    | j                             |          S )z
        Connect configuration dictionary to the Task object. Should be run at the beginning of your experiment.

        Args:
            values (`dict`):
                Values to be stored as initial hyperparameters as key-value pairs.
        )r  connect_configurationr6   s     r   r7   z'ClearMLTracker.store_init_configuration  s     y..v666r!   r8   c           
         | j                                         }|                                D ]\  }}t          |t          t
          f          s2t                              d| dt          |           d| d           S| |j	        d||d| ft                              |          \  }} |j        d||||d| dS )	a  
        Logs `values` dictionary to the current run. The dictionary keys must be strings. The dictionary values must be
        ints or floats

        Args:
            values (`Dict[str, Union[int, float]]`):
                Values to be logged as key-value pairs. If the key starts with 'eval_'/'test_'/'train_', the value will
                be reported under the 'eval'/'test'/'train' series and the respective prefix will be removed.
                Otherwise, the value will be reported under the 'train' series, and no prefix will be removed.
            step (`int`, *optional*):
                If specified, the values will be reported as scalars, with the iteration number equal to `step`.
                Otherwise they will be reported as single values.
            kwargs:
                Additional key word arguments passed along to the `clearml.Logger.report_single_value` or
                `clearml.Logger.report_scalar` methods.
        z-Accelerator is attempting to log a value of "r   r   zn" as a scalar. This invocation of ClearML logger's  report_scalar() is incorrect so we dropped this attribute.N)r*   r   )titleseriesr   	iterationr$   )r  r   rp   rq   rD   rr   rU   r   r   report_single_valuer   _get_title_seriesreport_scalar	r   r4   r8   r   clearml_loggerrw   rx   r	  r
  s	            r   r;   zClearMLTracker.log  s   $ --//LLNN 	h 	hDAqa#u.. ##AA A%)!WWA A89A A A   |22MMMfMMM*<<Q??ME6(N(guV1X\gg`fgggg	h 	hr!   c           	          | j                                         }|                                D ]4\  }}t                              |          \  }} |j        d||||d| 5dS )a  
        Logs `images` to the current run.

        Args:
            values (`Dict[str, List[Union[np.ndarray, PIL.Image]]`):
                Values to be logged as key-value pairs. The values need to have type `List` of `np.ndarray` or
            step (`int`, *optional*):
                The run step. If included, the log will be affiliated with this step.
            kwargs:
                Additional key word arguments passed along to the `clearml.Logger.report_image` method.
        )r	  r
  r  r   Nr$   )r  r   rp   r   r  report_imager  s	            r   r{   zClearMLTracker.log_images#  s     --//LLNN 	g 	gDAq*<<Q??ME6'N'feFdZ[ff_effff	g 	gr!   r   r   r   r   c                     |}||t          d          |r|g|z   n|}t                              |          \  }}	 | j                                        j        d||	||d| dS )ar  
        Log a Table to the task. Can be defined eitherwith `columns` and `data` or with `dataframe`.

        Args:
            table_name (`str`):
                The name of the table
            columns (list of `str`, *optional*):
                The name of the columns on the table
            data (List of List of Any data type, *optional*):
                The data to be logged in the table. If `columns` is not specified, then the first entry in data will be
                the name of the columns of the table
            dataframe (Any data type, *optional*):
                The data to be logged in the table
            step (`int`, *optional*):
                The run step. If included, the log will be affiliated with this step.
            kwargs:
                Additional key word arguments passed along to the `clearml.Logger.report_table` method.
        NzW`ClearMLTracker.log_table` requires that `data` to be supplied if `dataframe` is `None`)r	  r
  
table_plotr  r$   )
ValueErrorr   r  r  r   report_table)
r   r   r   r   r   r8   r   	to_reportr	  r
  s
             r   r   zClearMLTracker.log_table5  s    8 	| m   -4=	D((I&88DDv+	+w%S\hlwwpvwwwwwr!   c                 \    | j         r"| j        s| j                                          dS dS dS )z
        Close the ClearML task. If the task was initialized externally (e.g. by manually calling `Task.init`), this
        function is a noop
        N)r  r  r}   r=   s    r   r>   zClearMLTracker.finish[  sD     9 	T9 	IOO	 	 	 	r!   c                     dD ]8}|                      |dz             r| t          |          dz   d          |fc S 9| dfS )N)evaltesttrain_r
   r  )
startswithr.   )r*   prefixs     r   r  z ClearMLTracker._get_title_seriesd  s^    / 	7 	7Fv|,, 7CKK!O--.66667W}r!   rY   r   )r?   r@   rA   rB   r*   r+   r   rc   r3   r   r,   rC   r7   r   r	   rD   rr   r   r;   r{   r   r   r   r>   staticmethodr  r$   r!   r   r   r     s       	 	 D!&( ( ( ( ( _(   X 7t 7 7 7 _7 h h$sE#u*$556 hhsm h h h _hB g g gXc] g g g _g"  " $"#x #x#x c#x 49o	#x
 #x sm#x #x #x _#xJ   _   \  r!   r   c                        e Zd ZdZdZdZeddee         dee	         f fd            Z
ed             Zed	efd
            Zedd	edee         fd            Zed             Z xZS )DVCLiveTrackera5  
    A `Tracker` class that supports `dvclive`. Should be initialized at the start of your script.

    Args:
        run_name (`str`, *optional*):
            Ignored for dvclive. See `kwargs` instead.
        kwargs:
            Additional key word arguments passed along to [`dvclive.Live()`](https://dvc.org/doc/dvclive/live).

    Example:

    ```py
    from accelerate import Accelerator

    accelerator = Accelerator(log_with="dvclive")
    accelerator.init_trackers(project_name="my_project", init_kwargs={"dvclive": {"dir": "my_directory"}})
    ```
    dvcliveFNrH   livec                 v    ddl m} t                                                       ||n |di || _        d S )Nr   )Liver$   )r#  r&  rO   r3   r$  )r   rH   r$  r   r&  rW   s        r   r3   zDVCLiveTracker.__init__  sK           ,DD$$....			r!   c                     | j         S rY   )r$  r=   s    r   r,   zDVCLiveTracker.tracker  r  r!   r4   c                 :    | j                             |           dS )a  
        Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment. Stores the
        hyperparameters in a yaml file for future use.

        Args:
            values (Dictionary `str` to `bool`, `str`, `float`, `int`, or a List or Dict of those types):
                Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`,
                `str`, `float`, or `int`.
        N)r$  r   r6   s     r   r7   z'DVCLiveTracker.store_init_configuration  s      		V$$$$$r!   r8   c           
      J   ddl m} ||| j        _        |                                D ]`\  }}|                    |          r | j        j        ||fi | /t                              d| dt          |           d| d           a| j        
                                 dS )a  
        Logs `values` to the current run.

        Args:
            values (Dictionary `str` to `str`, `float`, or `int`):
                Values to be logged as key-value pairs. The values need to have type `str`, `float`, or `int`.
            step (`int`, *optional*):
                The run step. If included, the log will be affiliated with this step.
            kwargs:
                Additional key word arguments passed along to `dvclive.Live.log_metric()`.
        r   )MetricNz)Accelerator attempted to log a value of "r   r   zh" as a scalar. This invocation of DVCLive's Live.log_metric() is incorrect so we dropped this attribute.)dvclive.plotsr*  r$  r8   rp   	could_logr   rU   r   r   	next_step)r   r4   r8   r   r*  rw   rx   s          r   r;   zDVCLiveTracker.log  s     	)(((((!DINLLNN 		 		DAq"" $	$Q44V4444##AA A%)!WWA A89A A A    		r!   c                 8    | j                                          dS )z*
        Closes `dvclive.Live()`.
        N)r$  r   r=   s    r   r>   zDVCLiveTracker.finish  s    
 		r!   r   rY   )r?   r@   rA   rB   r*   r+   r   r   rc   r   r3   r   r,   rC   r7   rD   r;   r>   r   r   s   @r   r"  r"  l  s        & D!&A A# AXc] A A A A A _A   X 
%t 
% 
% 
% _
%  $ hsm    _8   _    r!   r"  )r   r   r   rG   r   r   r#  log_withrI   c                    g }| kt          | t          t          f          s| g} d| v st          j        | v rd | D             t                      z   }n| D ]}|t          vrHt          t          |          t                    s&t          d| dt          j                               t          t          |          t                    r|
                    |           t          |          }||vrz|t                      v rLt          t          |                   }|j        r|t          d| d          |
                    |           t                              d| d	           |S )
a9  
    Takes in a list of potential tracker types and checks that:
        - The tracker wanted is available in that environment
        - Filters out repeats of tracker types
        - If `all` is in `log_with`, will return all trackers in the environment
        - If a tracker requires a `logging_dir`, ensures that `logging_dir` is not `None`

    Args:
        log_with (list of `str`, [`~utils.LoggerType`] or [`~tracking.GeneralTracker`], *optional*):
            A list of loggers to be setup for experiment tracking. Should be one or several of:

            - `"all"`
            - `"tensorboard"`
            - `"wandb"`
            - `"comet_ml"`
            - `"mlflow"`
            - `"dvclive"`
            If `"all"` is selected, will pick up all available trackers in the environment and initialize them. Can
            also accept implementations of `GeneralTracker` for custom trackers, and can be combined with `"all"`.
        logging_dir (`str`, `os.PathLike`, *optional*):
            A path to a directory for storing logs of locally-compatible loggers.
    Nallc                 V    g | ]&}t          t          |          t                    $|'S r$   )
issubclassr   r'   )r   os     r   r   z#filter_trackers.<locals>.<listcomp>  s-    RRRQja..Q.QRqRRRr!   z Unsupported logging capability: z. Choose between zLogging with `z+` requires a `logging_dir` to be passed in.zTried adding logger z+, but package is unavailable in the system.)rq   r   r   r   ALLr%   r3  r   r'   r  appendLOGGER_TYPE_TO_CLASSrc   r+   rU   rV   )r/  rI   loggerslog_typetracker_inits        r   filter_trackersr;    s   4 G(T5M22 	" zHH
( : :RR(RRRUkUmUmmGG$ w w:--jhQ_6`6`-$%v%v%vcmcrctct%v%vwwwd8nnn== wNN8,,,,)(33Hw..#'='?'???+?H+NL+F &#.#6*4(n(n(n(n+& +& %& $NN84444"LL)u)u)u)uvvvNr!   rY   )3r   rP   rb   	functoolsr   typingr   r   r   r   r	   rf   loggingr   stater   r   r   r   r   r   r   r   r   r   r   r#   r6  TENSORBOARDWANDBCOMETMLAIMMLFLOWCLEARMLDVCLIVEr?   rU   r   r%   r'   rF   r   r   r   r   r   r"  r7  rc   r~   r;  r$   r!   r   <module>rG     sT  $  				        3 3 3 3 3 3 3 3 3 3 3 3 3 3             
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
   7z5666 1z/000 3z1222 /z~... 2z0111 3z1222 3z1222	H		# # #&  
G G G G G G G GTl2 l2 l2 l2 l2 l2 l2 l2^x) x) x) x) x)> x) x) x)vN+ N+ N+ N+ N+^ N+ N+ N+b` ` ` ` ` ` ` `FN N N N NN N N NbU U U U U^ U U UpQ Q Q Q Q^ Q Q Qj %   ,04 45j.89:4sBK'(4 4 4 4 4 4r!   