o
    xi                     @  s   d Z ddlmZ ddlZddlmZ ddlmZ zddlmZ W n e	y/   ddl
mZ Y nw ddlZddlmZ er@ddlZed	Zda		
			d"d#ddZ	d$d%d d!ZdS )&zwatch.    )annotationsN)Sequence)TYPE_CHECKING)Literal   )	telemetrywandb	gradients  Frun	wandb.Runmodels+torch.nn.Module | Sequence[torch.nn.Module]	criteriontorch.F | Nonelog0Literal['gradients', 'parameters', 'all'] | Nonelog_freqintidx
int | None	log_graphboolc                 C  s@  t  }d|j_W d   n1 sw   Y  td |dvr%td|dv }|dv }	t|tt	fs7|f}t
jjdd	d
}
|D ]}t||
jjsStdt| qAg }d}|du r^t}t|D ];\}}|| }td7 a|dkrwd| }|r| jj|||d |	r| jj|||d |r| jj|||d}|| qb|S )aR  Hooks into the given PyTorch model(s) to monitor gradients and the model's computational graph.

    This function can track parameters, gradients, or both during training. It should be
    extended to support arbitrary machine learning models in the future.

    Args:
        run (wandb.Run): The run object to log to.
        models (Union[torch.nn.Module, Sequence[torch.nn.Module]]):
            A single model or a sequence of models to be monitored.
        criterion (Optional[torch.F]):
            The loss function being optimized (optional).
        log (Optional[Literal["gradients", "parameters", "all"]]):
            Specifies whether to log "gradients", "parameters", or "all".
            Set to None to disable logging. (default="gradients")
        log_freq (int):
            Frequency (in batches) to log gradients and parameters. (default=1000)
        idx (Optional[int]):
            Index used when tracking multiple models with `wandb.watch`. (default=None)
         log_graph (bool):
            Whether to log the model's computational graph. (default=False)

    Returns:
        wandb.Graph:
            The graph object, which will be populated after the first backward pass.

    Raises:
        ValueError: If `wandb.init` has not been called.
        TypeError: If any of the models are not instances of `torch.nn.Module`.
    TNWatching>   Nallr	   
parametersz<log must be one of 'gradients', 'parameters', 'all', or None>   r   r   >   r   r	   torchz;wandb.watch only works with pytorch, couldn't import torch.)requiredz5Expected a pytorch model (torch.nn.Module). Received  r   r   graph_)prefixr   )	graph_idx)r   contextfeaturewatchloggerinfo
ValueError
isinstancetuplelistr   util
get_modulennModule	TypeErrortype_global_watch_idx	enumerate_torchadd_log_parameters_hookadd_log_gradients_hook
hook_torchappend)r   r   r   r   r   r   r   tellog_parameterslog_gradientsr   modelgraphsr    	local_idx
global_idxgraph r@   I/home/ubuntu/.local/lib/python3.10/site-packages/wandb/sdk/wandb_watch.py_watch   sZ   
(



rB   2torch.nn.Module | Sequence[torch.nn.Module] | NonereturnNonec                 C  sr   |r2t |ttfs|f}|D ]!}t|dst| d q|jD ]}| j| q!t	|d qdS | j
  dS )a  Remove pytorch model topology, gradient and parameter hooks.

    Args:
        run (wandb.Run):
            The run object to log to.
        models (torch.nn.Module | Sequence[torch.nn.Module]):
            Optional list of pytorch models that have had watch called on them
    _wandb_hook_namesz model has not been watchedN)r(   r)   r*   hasattrr   termwarnrF   r3   unhookdelattr
unhook_all)r   r   r;   namer@   r@   rA   _unwatch{   s   


rM   )Nr	   r
   NF)r   r   r   r   r   r   r   r   r   r   r   r   r   r   )N)r   r   r   rC   rD   rE   )__doc__
__future__r   loggingcollections.abcr   typingr   r   ImportErrortyping_extensionsr   libr   r   	getLoggerr%   r1   rB   rM   r@   r@   r@   rA   <module>   s0    
b