U
    9%ed                     @   s  d dl Z d dlZd dlZd dlZd dlZd dlmZmZ d dlm	Z	 d dl
mZmZmZmZ d dlmZ eeZejZdZeG dd dZeG d	d
 d
Ze Ze addejdddZdddddddddddddddddddddddddee ee ee ee ee ee ee eeeeeeeeeeeeeeeeeeeeeef f  dddZ dd Z!dd Z"dFddZ#dd Z$dZ%dZ&dd'e(e%e(e&g d Z)dd Z*d d! Z+d"d# Z,dGd$d%Z-dHd&d'Z.e j/d(d) Z0d*d+ Z1d,d- Z2d.d/ Z3G d0d1 d1ej4Z5e5 Z6d2d3 Z7e Z8d4d5 Z9d6d7 Z:d8d9 Z;d:d; Z<d<d= Z=d>d? Z>dId@dAZ?e /ddBdC Z@G dDdE dEZAd dlBZCd dlDmEZF dS )J    N)	dataclassfield)
__import__)DictOptionalSetUnion)WeakSetZ
TORCH_LOGSc                   @   s  e Zd ZU eedZeeef ed< ee	dZ
ee ed< ee	dZee ed< ee	dZee ed< ee	dZee ed< eedZeeef ed< ee	dZee ed< eedZeeejf ed	< d
d Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd ZdS )LogRegistrydefault_factorylog_alias_to_log_qnameartifact_log_qnameschild_log_qnamesartifact_namesvisible_artifactsartifact_descriptionsoff_by_default_artifact_namesartifact_log_formattersc                 C   s
   || j kS Nr   selfname r   W/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/torch/_logging/_internal.pyis_artifact7   s    zLogRegistry.is_artifactc                 C   s
   || j kS r   r   )r   aliasr   r   r   is_log:   s    zLogRegistry.is_logc                 C   s   || j |< d S r   r   )r   r   	log_qnamer   r   r   register_log>   s    zLogRegistry.register_logc                 C   sR   | j | |r| j| || j|< |r6| j| |d k	rNt|| j|< d S r   )r   addr   r   r   logging	Formatterr   )r   r   descriptionvisibleoff_by_default
log_formatr   r   r   register_artifact_nameB   s    
z"LogRegistry.register_artifact_namec                 C   s   | j | d S r   )r   r"   )r   artifact_log_qnamer   r   r   register_artifact_logU   s    z!LogRegistry.register_artifact_logc                 C   s   | j | d S r   )r   r"   )r   r    r   r   r   register_child_logX   s    zLogRegistry.register_child_logc                 C   s   t | j S r   )setr   valuesr   r   r   r   get_log_qnames[   s    zLogRegistry.get_log_qnamesc                 C   s
   t | jS r   )r-   r   r/   r   r   r   get_artifact_log_qnames^   s    z#LogRegistry.get_artifact_log_qnamesc                 C   s
   t | jS r   )r-   r   r/   r   r   r   get_child_log_qnamesa   s    z LogRegistry.get_child_log_qnamesc                 C   s
   || j kS r   )r   )r   Zartifact_qnamer   r   r   is_off_by_defaultd   s    zLogRegistry.is_off_by_defaultN)__name__
__module____qualname__r   dictr   r   str__annotations__r-   r   r   r   r   r   r   r   r   r#   r$   r   r   r!   r)   r+   r,   r0   r1   r2   r3   r   r   r   r   r
      s$   
r
   c                   @   sf   e Zd ZU eedZeeef ed< ee	dZ
ee ed< dd Zdd Zdd	 Zd
d Zdd ZdS )LogStater   log_qname_to_levelr   c                 C   s   | j | d S r   )r   r"   )r   artifact_namer   r   r   enable_artifactp   s    zLogState.enable_artifactc                 C   s
   || j kS r   r   r   r   r   r   is_artifact_enableds   s    zLogState.is_artifact_enabledc                 C   s   || j |< d S r   )r;   )r   r    	log_levelr   r   r   
enable_logv   s    zLogState.enable_logc                 C   s
   | j  S r   )r;   itemsr/   r   r   r   get_log_level_pairsy   s    zLogState.get_log_level_pairsc                 C   s   | j   | j  d S r   )r;   clearr   r/   r   r   r   rC   |   s    
zLogState.clearN)r4   r5   r6   r   r7   r;   r   r8   r9   r-   r   r   r=   r>   r@   rB   rC   r   r   r   r   r:   h   s   
r:   T)graph_breaks
recompilesdynamicguardstrace_sourceF)alldynamoaotrF   inductordistributedonnxbytecode
aot_graphsaot_joint_graph
ddp_graphsgraph
graph_coderD   graph_sizesrG   rE   rH   
trace_calloutput_codeschedule
perf_hintsonnx_diagnosticsmodulesc                    sn   t tjkrtd dS t   p&i   fdd}|| |||||||	|
||||||||||||||d dS )aB  
    Sets the log level for individual components and toggles individual log
    artifact types.

    .. warning:: This feature is a prototype and may have compatibility
        breaking changes in the future.

    .. note:: The ``TORCH_LOGS`` environment variable has complete precedence
        over this function, so if it was set, this function does nothing.

    A component is a set of related features in PyTorch. All of the log
    messages emitted from a given component have their own log levels. If the
    log level of a particular message has priority greater than or equal to its
    component's log level setting, it is emitted. Otherwise, it is supressed.
    This allows you to, for instance, silence large groups of log messages that
    are not relevant to you and increase verbosity of logs for components that
    are relevant. The expected log level values, ordered from highest to lowest
    priority, are:

        * ``logging.CRITICAL``
        * ``logging.ERROR``
        * ``logging.WARNING``
        * ``logging.INFO``
        * ``logging.DEBUG``
        * ``logging.NOTSET``

    See documentation for the Python ``logging`` module for more information on
    log levels: `<https://docs.python.org/3/library/logging.html#logging-levels>`_

    An artifact is a particular type of log message. Each artifact is assigned
    to a parent component. A component can emit many different kinds of
    artifacts. In general, an artifact is emitted if either its corresponding
    setting in the argument list below is turned on or if its parent component
    is set to a log level less than or equal to the log level of the artifact.

    Keyword args:
        all (:class:`Optional[int]`):
            The default log level for all components. Default: ``logging.WARN``

        dynamo (:class:`Optional[int]`):
            The log level for the TorchDynamo component. Default: ``logging.WARN``

        aot (:class:`Optional[int]`):
            The log level for the AOTAutograd component. Default: ``logging.WARN``

        inductor (:class:`Optional[int]`):
            The log level for the TorchInductor component. Default: ``logging.WARN``

        dynamic (:class:`Optional[int]`):
            The log level for dynamic shapes. Default: ``logging.WARN``

        distributed (:class:`Optional[int]`):
            Whether to log communication operations and other debug info from pytorch distributed components.
            Default: ``logging.WARN``

        onnx (:class:`Optional[int]`):
            The log level for the ONNX exporter component. Default: ``logging.WARN``

        bytecode (:class:`bool`):
            Whether to emit the original and generated bytecode from TorchDynamo.
            Default: ``False``

        aot_graphs (:class:`bool`):
            Whether to emit the graphs generated by AOTAutograd. Default: ``False``

        aot_joint_graph (:class:`bool`):
            Whether to emit the joint forward-backward graph generated by AOTAutograd. Default: ``False``

        ddp_graphs (:class:`bool`):
            Whether to emit graphs generated by DDPOptimizer. Default: ``False``

        graph (:class:`bool`):
            Whether to emit the graph captured by TorchDynamo in tabular format.
            Default: ``False``

        graph_code (:class:`bool`):
            Whether to emit the python source of the graph captured by TorchDynamo.
            Default: ``False``

        graph_breaks (:class:`bool`):
            Whether to emit the graph breaks encountered by TorchDynamo.
            Default: ``False``

        graph_sizes (:class:`bool`):
            Whether to emit tensor sizes of the graph captured by TorchDynamo.
            Default: ``False``

        guards (:class:`bool`):
            Whether to emit the guards generated by TorchDynamo for each compiled
            function. Default: ``False``

        recompiles (:class:`bool`):
            Whether to emit a guard failure reason and message every time
            TorchDynamo recompiles a function. Default: ``False``

        trace_source (:class:`bool`):
            Whether to emit when TorchDynamo begins tracing a new line. Default: ``False``

        trace_call (:class:`bool`):
            Whether to emit detailed line location when TorchDynamo creates an FX node
            corresponding to function call. Python 3.11+ only. Default: ``False``

        output_code (:class:`bool`):
            Whether to emit the TorchInductor output code. Default: ``False``

        schedule (:class:`bool`):
            Whether to emit the TorchInductor schedule. Default: ``False``

        perf_hints (:class:`bool`):
            Whether to emit the TorchInductor perf hints. Default: ``False``

        onnx_diagnostics (:class:`bool`):
            Whether to emit the ONNX exporter diagnostics in logging. Default: ``False``

        modules (dict):
            This argument provides an alternate way to specify the above log
            component and artifact settings, in the format of a keyword args
            dictionary given as a single argument. There are two cases
            where this is useful (1) if a new log component or artifact has
            been registered but a keyword argument for it has not been added
            to this function and (2) if the log level for an unregistered module
            needs to be set. This can be done by providing the fully-qualified module
            name as the key, with the log level as the value. Default: ``None``


    Example::

        >>> # xdoctest: +SKIP
        >>> import logging

        # The following changes the "dynamo" component to emit DEBUG-level
        # logs, and to emit "graph_code" artifacts.

        >>> torch._logging.set_logs(dynamo=logging.DEBUG, graph_code=True)

        # The following enables the logs for a different module

        >>> torch._logging.set_logs(modules={"unregistered.module.name": logging.DEBUG})
    zQUsing TORCH_LOGS environment variable for log settings, ignoring call to set_logsNc                     s\  |  dd }|rf|tjkrDtd| dddd tj D  tj D ]}|| krN|| |< qNnt}t	
|    D ]\}}|d kr|}t|rt|tstd| d| |rt| q~t|s|tjkr4|tjkrtd	| d
| dddd tj D  ttj||| q~|dkrBq~q~td| q~t  d S )NrI   z&Unrecognized log level for kwarg all: z, valid level values are: ,c                 S   s   g | ]}t |qS r   r8   .0kr   r   r   
<listcomp>D  s     z/set_logs.<locals>._set_logs.<locals>.<listcomp>z!Expected bool to enable artifact z, received zUnrecognized log level for log z: c                 S   s   g | ]}t |qS r   r]   r^   r   r   r   ra   ^  s     z6Unrecognized log or artifact name passed to set_logs: )popr#   _levelToName
ValueErrorjoinkeyslog_registryr   DEFAULT_LOG_LEVEL	itertoolschainrA   r   
isinstancebool	log_stater=   r   r   r@   get
_init_logs)kwargsZdefault_levelr   valr[   r   r   	_set_logs?  sF    
$

* 
zset_logs.<locals>._set_logs)rI   rJ   rK   rL   rF   rO   rP   rQ   rR   rM   rS   rT   rD   rU   rG   rE   rH   rV   rW   rX   rY   rN   rZ   )LOG_ENV_VARosenvironlogwarningrm   rC   )rI   rJ   rK   rF   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rD   rU   rG   rE   rH   rV   rW   rX   rY   rZ   r[   rs   r   rr   r   set_logs   sD     (
/ry   c                   C   s   dd t  D S )z3
    Returns: a list of all registered loggers
    c                 S   s   g | ]}t |qS r   )r#   	getLogger)r_   qnamer   r   r   ra     s     zget_loggers.<locals>.<listcomp>)rg   r0   r   r   r   r   get_loggers  s    r|   c                 C   s   t | | dS )z
    Enables a log to be controlled by the env var and user API with the setting_name
    Args:
        setting_name:  the shorthand name used in the env var and user API
        log_name:  the log name that the setting_name is associated with
    N)rg   r!   )setting_nameZlog_namer   r   r   r!     s    r!   c                 C   s   t | |||| dS )a  
    Enables an artifact to be controlled by the env var and user API with name
    Args:
        setting_name: the shorthand name used in the env var and user API
        description: A description of what this outputs
        visible: Whether it gets suggested to users by default
        off_by_default: whether this artifact should be logged when the ancestor loggers
            are enabled at level DEBUG
    N)rg   r)   )r}   r%   r&   r'   r(   r   r   r   register_artifact  s        r~   c                 C   s\   |t jkr(tdt| dt| d| d|  }t|}||_t | t| |S )NzArtifact name: z. not registered,please call register_artifact(z") in torch._logging.registrations.z.__)	rg   r   rd   reprr#   rz   r<   r+   configure_artifact_log)Zmodule_qnamer<   r{   rw   r   r   r   getArtifactLogger  s    


r   +-(|z?)c                 C   s4   t | jrd| _t| jr0| tj d| _d S NFT)	rg   r3   r<   	propagaterm   r>   setLevelr#   DEBUG)rw   r   r   r   r     s
    r   c                   C   s
   t dS )Nz$((\+|-)?[\w\.]+,\s*)*(\+|-)?[\w\.]+?)recompiler   r   r   r   _gen_settings_regex  s    r   c                 C   s   t t | d k	S r   )r   	fullmatchr   )settingsr   r   r   _validate_settings  s    r   c                    s~   ddd | rt j}nt j}| r&d}nd}dgtt j   fdd|D  }d	d
| }d}d| d| d| d}|S )N   c                 S   s$   t | |kst| d|t |    S )N )lenAssertionError)slengthr   r   r   pad_to  s    zhelp_message.<locals>.pad_tozAll registered namesz?Visible registered names (use TORCH_LOGS='+help' for full list)rI   c                    s$   g | ]} | d t j|  qS )	)rg   r   )r_   r   r   r   r   ra     s   z help_message.<locals>.<listcomp>z  z
  aD  
Examples:
  TORCH_LOGS="+dynamo,aot" will set the log level of TorchDynamo to
  logging.DEBUG and AOT to logging.INFO

  TORCH_LOGS="-dynamo,+inductor" will set the log level of TorchDynamo to
  logging.ERROR and TorchInductor to logging.DEBUG

  TORCH_LOGS="aot_graphs" will enable the aot_graphs artifact

  TORCH_LOGS="+dynamo,schedule" will enable set the log level of TorchDynamo
  to logging.DEBUG and enable the schedule artifact

  TORCH_LOGS="+some.random.module,schedule" will set the log level of
  some.random.module to logging.DEBUG and enable the schedule artifact
z
TORCH_LOGS Info
z


)r   )rg   r   r   listr   rf   re   )verboseZprinted_artifactsheadinglinesZsetting_infoZexamplesmsgr   r   r   help_message  s2    

r   c                 C   s:   d dgttj  ttj }d|  d| d}|S )Nz, rI   z
Invalid log settings: z, must be a comma separated list of fully
qualified module names, registered log names or registered artifact names.
For more info on various settings, try TORCH_LOGS="help"
Valid settings:
r   )re   r   rg   r   rf   r   )r   r   Zvalid_settingsr   r   r   r   _invalid_settings_err_msg	  s    r   c                 C   sb  | dkrt  S | dkr&ttddn| dkr<ttddt| sPtt| tdd| } | d}d	d
 }t }|D ]2}||\}}|dkrzt	
 D ]}||| qqz|D ]}||\}}t	|r|d k	stt	j| }||| qt	|r|| q|dkrqqt|rPt|s8t	|| n
t	| ||| qtt| q|S )N helpF)r   z+helpTz\s+r\   c                 S   sN   |  td}| td}| d tkr,tj}n| d tkr@tj}ntj}||fS )Nr   r   )replaceINCR_VERBOSITY_CHARDECR_VERBOSITY_CHARr#   r   ERRORINFO)r   Z
clean_namelevelr   r   r   get_name_level_pair(  s    z0_parse_log_settings.<locals>.get_name_level_pairrI   )r7   rd   r   r   r   r   subsplitr:   rg   r0   r@   r   r   r   r   r=   _is_valid_module_has_registered_parentr!   r,   )r   Z	log_namesr   rm   r   r   r    r   r   r   _parse_log_settings  sD    






r   c                 C   s*   zt |  W dS  tk
r$   Y dS X d S NTF)r   ImportError)r{   r   r   r   r   T  s
    r   c                  C   s"   t jtd } | d k	rt| ad S r   )ru   rv   rn   rt   r   rm   )Zlog_settingr   r   r   _update_log_state_from_env\  s    r   c                 C   s2   t | }t }|jr.|j|kr&dS |j}qdS r   )r#   rz   rg   r0   parentr   )r    Zcur_logZregistered_log_qnamesr   r   r   r   c  s    

r   c                   @   s   e Zd Zdd ZdS )TorchLogsFormatterc              
      s   t t|jdd }|d k	r<tj|d }|d k	r<||S | |_	| 
|| j|_|j	d}d|_t rt rdt  d|_d|_tjj  }d k	rd| d|_|j d|j d|j d	|j d
|j d
 d fdd|D S )Nr<   r   r   z[rankz]:z [][r   z: [c                 3   s   | ]}  d | V  qdS )r   Nr   )r_   lprefixr   r   	<genexpr>  s     z,TorchLogsFormatter.format.<locals>.<genexpr>)getattrr#   rz   r   rg   r   rn   format
getMessagemessage
formatTimedatefmtasctimer   Z
rankprefixdistZis_availableZis_initializedZget_rankZ	compileidtorchZ_guardsZCompileContextZcurrent_compile_id	levelnamere   )r   recordr<   Zartifact_formatterr   Z
compile_idr   r   r   r   r  s*     

,zTorchLogsFormatter.formatN)r4   r5   r6   r   r   r   r   r   r   q  s   r   c                 C   s.   t |  }|t |tj || d S r   )_track_handlersetFormatterDEFAULT_FORMATTERr   r#   r   
addHandler)Zcreate_handler_fnrw   Zdebug_handlerr   r   r   _setup_handlers  s    

r   c                 C   s   t |  | S r   )handlersr"   handlerr   r   r   r     s    
r   c                 C   s   | t kS r   )r   r   r   r   r   _is_torch_handler  s    r   c                 C   s(   dd | j D }|D ]}| | qd S )Nc                 S   s   g | ]}t |r|qS r   )r   )r_   r   r   r   r   ra     s      z#_clear_handlers.<locals>.<listcomp>)r   removeHandler)rw   Z	to_remover   r   r   r   _clear_handlers  s    r   c                  C   sl   t  D ](} t| }|tj d|_t| qt	t 
 t  D ] }t|}|tj d|_qFd S r   )rg   r0   r#   rz   r   WARNINGr   r   ri   rj   r1   r2   NOTSET)r    rw   r*   r   r   r   _reset_logs  s    

 
r   c                   C   s   t S r   rm   r   r   r   r   _get_log_state  s    r   c                 C   s   | a d S r   r   )stater   r   r   _set_log_state  s    r   c                    s   t   t  t D ]\}}t|}|| qt D ]4}t|}t	tj
|  d k	r:t	 fdd| q:t D ]}t|}t| qxd S )Nc                      s
   t  S r   )r#   FileHandlerr   log_file_namer   r   <lambda>      z_init_logs.<locals>.<lambda>)r   r   rm   rB   r#   rz   r   rg   r0   r   StreamHandlerr1   r   )r   r    r   rw   r*   r   r   r   ro     s&    



ro   c                 O   s   | j || dS )a  
    This function is similar to `logger.warning()`, but will emit the warning with the same message only once
    Note: The cache is for the function arguments, so 2 different callers using the same arguments will hit the cache.
    The assumption here is that all warning messages are unique across the code. If they aren't then need to switch to
    another type of cache that includes the caller frame information in the hashing function.
    N)rx   )Z
logger_objargsrp   r   r   r   warning_once  s    r   c                   @   s   e Zd Zdd Zdd ZdS )
LazyStringc                 O   s   || _ || _|| _d S r   funcr   rp   )r   r   r   rp   r   r   r   __init__  s    zLazyString.__init__c                 C   s   | j | j| jS r   r   r/   r   r   r   __str__  s    zLazyString.__str__N)r4   r5   r6   r   r   r   r   r   r   r     s   r   )FFN)F)F)N)G	functoolsri   r#   ru   r   dataclassesr   r   	importlibr   typingr   r   r   r   weakrefr	   rz   r4   rw   WARNrh   rt   r
   r:   rg   rm   r   ZDEFAULT_LOGGINGintrl   r8   ry   r|   r!   r~   r   r   r   re   escapeZVERBOSITY_REGEXr   r   r   r   r   	lru_cacher   r   r   r   r$   r   r   r   r   r   r   r   r   r   r   ro   r   r   Ztorch._guardsr   Ztorch.distributedrM   r   r   r   r   r   <module>   s   
V |     

1

:



