o
    hxY                    @  s  U d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZ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$ 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/ dd
l0m1Z1m2Z2 ddl3Z3ddl4Z3ddl5Z3ddl6m7  m8Z9 ddl3m:Z: ddl;m<Z<m=Z=m>Z>m?Z? ddl@mAZA ddlBmCZCmDZD ddlEmFZFmGZGmHZH ddlImJZJ ddlKmLZLmMZMmNZNmOZOmPZP ddlQmRZRmSZS ddlTmUZU ddlVmWZW ddlXmYZYmZZZ ddl[m\Z\ ej]rFddl^m_Z_m`Z`maZambZbmcZc zddldZeW n efyX   dZeY nw zMddlgZ3ddlhmiZj ddlEmkZk ddlgmlZl ddlmmnZn eereeeejoeejpeejqfZrdesd< eeejeejoejjoeejpejjpeejqejjqiZtndZri ZtddlumvZvmwZwmxZx W n
 eyy   Y nw e.d Zze3j{j|j}Z~e3j{j|jZe3j{j|jZeej!Zd!esd"< i Zd#esd$< d%Zd&Zd'e d(ZeeZi Zd)esd*< eeZd+esd,< e ZG d-d. d.e
jZG d/d0 d0Zd8d7d8Zdad9d:d;Zd9d<d=Zdad:d@dAZd;dBdCZd9dDdEZdFesdG< dHesdI< d<dJdKZd=dLdMZG dNdO dOe
jZG dPdQ dQZe#		R						Rd>d?dbdcZe-d@dAdgdhZe-	Rd@dBdkdhZdCdDdldhZejd9dmdnZe3je3je3jfe3je3je3jfe3je3je3jfe3je3jfe3je3jfe3je3jfe3je3je3jfe3je3je3jfe3je3je3jfe3je3jfi
ZG dodp dpZe Zdqdr Zd9dsdtZdudv Zdwdx ZÐdEdydzZĐdFd|d}ZŐdGddZƐdHddZdd Zdd ZG dd dZe-dIddZe-dJddZe-dKddZdd Zejdkr=ejejejej.ejejfZdd Zdd Zdd Zdd Zdd Zdd ZejejejejejejdZdddddddZdd Zdd Zdd Zdd Zdd Zdd Ze%ddd ZdLddZdd ZdMddZdMddĄZdZejG ddǄ dǃZdZejedɍadesd< dNdd΄ZdOddЄZdOdd҄ZdPddۄZeCed܍ZeDed܍ZdQdd߄Zd9ddZdRddZG dd dZdadesd< dSddZe#	R	RdTdUddZejG dd dZG dd deʃZ e  e _dd ZddddZdd ZdVddZe#dd Zd d Zd@ddZdd Z	dd Z
dd	 Ze%ddWddZdd ZdXddZdd Ze%ddd Zeeeeeeedejejeje3je3je3je3je3je3je3j{jj e3j!j"hZ#desd< eZ rddl$Z$e#%e$j&j 	 dd Z'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+ Z0ei 1 Z2d,esd-< ei 3 Z4d.esd/< ee" 3 Z5d.esd0< ee6dZ7d1esd2< ee6e8dZ9d1esd3< e7j:Z;e<j=Z>e?j=Z@d4d5 eAe?jB3 e"jB3 D ZCeDj=ZEd6d5 eDjB3 D ZFd7d5 eGjB3 D ZHeGjIZJd8d5 ejB3 D ZKd9d: ZLd;d< ZMd=d> ZNd?d@ ZOdAdB ZPeQZRdYdDdEZSdFdG ZTe?jIZUdHdI ZVdJdK ZWdLdM ZXdNdO ZYd@dPdQZZdRdS Z[dTdU Z\dEdVdWZ]dEdXdYZ^dZZ_dd[l`maZa d\d] ZbdZd`daZcdRdbd[dddeZddfdg Zedhdi Zfdjdk ZgddRdldRdmdRdRejhdRdRf
d\dodpZidqdr Zjej#dsdt Zkeʃ ZleeGZmduesdv< g Zndwesdx< eʃ Zoe%ddydz Zpd{d| Zqd]d}d~Zrdd Zsdd Ztd@ddZuev Zwdd Zxe#dd Zydd Zzdd Z{dd Z|d^ddZ}dd Z~d_ddZd`ddZdaddZd@dbddZG dd de
jZdcddZddddZdd Zdd ZddgZddgZg dZee e Zdd Z	R	R	RdeddZ	R	R	RdeddZdd Zdd ZG dd dZdÐdĄ ZG dŐdƄ dƃZG dǐdȄ dȃZdɐdʄ Zdːd̄ Zd͐d΄ ZdϐdЄ Zdѐd҄ ZdӐdԄ Zdfd֐dׄZejG dؐdل dكZdgdܐd݄ZdhddZdd Zdd Zdd Zdd ZdiddZdd Zdd Zdd Zej#djddZdd Zdd ZG dd de3j{j|Zdkd dZdd Zdd ZG dd dZe Zdesd	< dXd
dZdd Zej#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"d# Zd$d% Zd&d' Zi Zd(esd)< d*d+ Zd,d- ZG d.d/ d/ZÐdld2d3ZĐd4ZŐd
esd5< d6d7 ZdS (m  a  
Utility functions and classes used throughout the TorchDynamo system.

This module contains a collection of helper utilities used by various parts of Dynamo for:
- Performance metrics collection and reporting
- Compilation timing and debugging
- Graph manipulation and tensor operations
- Runtime guards and checks
- Common data structure operations
- Testing and development tools

This is an internal module that provides shared functionality used across the Dynamo codebase.
    )annotationsN)CounterOrderedDict)contextmanager)is_dataclass)	lru_cache)MethodWrapperType)	AnyCallablecastClassVarGenericOptionaloverloadTypeVarUnion)LiteralTypeIs)fx)_instruction_counter_len_torch_function_stack_pop_torch_function_stack_push_on_torch_function_stack)enable_python_dispatcher)MetricsContextRuntimeMetricsContext)	CompileIdSourceTracingContext)is_sparse_compressed)justknobs_checklog_chromium_event_internallog_compilation_eventrecord_chromium_event_internalsignpost_event)_format_graph_codelazy_format_graph_code)_WaitCounter)LazyModuleMixin)
has_tritonhas_triton_package)RemovableHandle)	GeneratorIterableIteratorKeysView
ValuesView)detect_fake_mode
LazyString   )configztuple[types.ModuleType, ...]NP_SUPPORTED_MODULES )
FakeTensoris_fakemaybe_get_fake_modeTz*collections.defaultdict[str, Counter[str]]countersdict[str, Any]optimus_scuba_logzAhttps://pytorch.org/docs/main/torch.compiler_troubleshooting.htmlz;https://pytorch.org/docs/main/torch.compiler_nn_module.htmlzSee z& for more information and limitations.zdict[str, list[float]]compilation_time_metricsdict[str, float]cumulative_time_spent_nsc                   @     e Zd ZdZdZdZdS )ReInplaceTriggerr4         N)__name__
__module____qualname__AUTO_FUNC_V1AUTO_FUNC_V2
TRITON_OPSr7   r7   r7   g/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/torch/_dynamo/utils.pyrC          rC   c                   @  sl   e Zd ZU eeZded< edddZ	edd
dZ
edd Zedd Zedd Zedd ZdS )ReinplaceCountersz!collections.defaultdict[str, int]_valuestriggerrC   bytesintc                 C  s*   |dkr| j d|j   |7  < d S d S Nr   missed_bytes_)rO   name)clsrP   rQ   r7   r7   rL   add_missed_bytes   s   z"ReinplaceCounters.add_missed_bytescountc                 C  s(   |dkr| j d|   |7  < d S d S Nr   missed_tensors_)rO   )rV   rP   rX   r7   r7   rL   add_missed_opportunities   s   z*ReinplaceCounters.add_missed_opportunitiesc                 C  s   | j   d S N)rO   clearrV   r7   r7   rL   r]      s   zReinplaceCounters.clearc                 C  s*   d}t D ]}|| jd| d7 }q|S rY   )rC   rO   getrV   sumrP   r7   r7   rL   get_total_missed   s   z"ReinplaceCounters.get_total_missedc                 C  s,   d}t D ]}|| jd|j d7 }q|S rS   )rC   rO   r_   rU   r`   r7   r7   rL   get_total_missed_bytes   s   z(ReinplaceCounters.get_total_missed_bytesc                 C  s   | j rtdd| j  d S d S )Ninductorreinplace_counters)rO   r$   r^   r7   r7   rL   log   s   zReinplaceCounters.logN)rP   rC   rQ   rR   )rP   rC   rX   rR   )rF   rG   rH   collectionsdefaultdictrR   rO   __annotations__classmethodrW   r[   r]   rb   rc   rf   r7   r7   r7   rL   rN      s   
 


rN   rows3Union[list[tuple[str, object]], list[list[object]]]headers!Union[tuple[str, ...], list[str]]returnstrc              
   C  sJ   zdd l }|j | |dW S  ty$   ddd t|g| D  Y S w )Nr   rm   
c                 s  s     | ]}d  tt|V  qdS ), N)joinmaprp   ).0rowr7   r7   rL   	<genexpr>       
ztabulate.<locals>.<genexpr>)tabulateImportErrorrt   	itertoolschain)rk   rm   rz   r7   r7   rL   rz      s   
rz   Nonec                   C  s   t d a d S Nr4   )
curr_framer7   r7   r7   rL   increment_frame      r   c                   C  s   t   t  dad S Nr   )rA   r]   r?   r   r7   r7   r7   rL   reset_frame_count   s   r   cntrR   c                 C  s   t | 7 a d S r\   )op_count)r   r7   r7   rL   increment_op_count   r   r   c                  C  sB   i } t  D ]
\}}|d | |< q| dd| dd | d< | S )N    eAentire_frame_compiler   entire_backward_compiletotal_wall_time)rA   itemsr_   )total_by_keyphasetimingr7   r7   rL   calculate_time_spent   s   
r   c                  C  sB   t  } d}|  D ]\}}| d| dt|d }q	t| d S )NzTIMING: :   )r   r   roundprint)r   outkeyvaluer7   r7   rL   print_time_report  s
   r   r   _METRICS_CONTEXTr   _RUNTIME_METRICS_CONTEXTc                   C     t S r\   )r   r7   r7   r7   rL   get_metrics_context0     r   c                   C  r   r\   )r   r7   r7   r7   rL   get_runtime_metrics_context4  r   r   c                   @  s   e Zd ZdZdZdZdZdS )CompileEventLogLevelz
    Enum that loosely corresponds with a "log level" of a given event.

    CHROMIUM_EVENT: Logs only to tlparse.
    COMPILE_EVENT: Logs to tlparse + PT2 Compile Events
    COMPILATION_METRIC: Logs to tlparse, PT2 Compile Events, and dynamo_compile
    r4   rD   rE   N)rF   rG   rH   __doc__CHROMIUMPT2_COMPILECOMPILATION_METRICr7   r7   r7   rL   r   8  s
    r   c                   @  s   e Zd ZdZedejfd,ddZe	d-d.ddZe	d-d/ddZ	ed0ddZ
edejfd1ddZed2ddZeejfd3d d!Zed4d"d#Zed4d$d%Zed-d5d&d'Ze	d6d7d(d)Zed4d*d+ZdS )8CompileEventLoggera  
    Helper class for representing adding metadata(i.e. columns) to various compile events.
    Use CompileEventLogger to add event data to:
    - Chromium events
    - PT2 Compile Events
    - CompilationMetrics

    This should be used in conjunction with dynamo_timed() and metrics contexts, which create
    timed spans and events. CompileEventLogger uses three log levels (described in CompileEventLogLevel),
    where each log level logs to all sources below it in the hierarchy.

    Example usages:
    - I want to log to an existing chromium event within dynamo timed:
    with dynamo_timed("my_event"):
        CompileEventLogger.chromium("my_event", foo=bar)

    - I want to log my event to both chromium + pt2_compile_events:
    with dynamo_timed("my_event", log_pt2_compile_event=True):
        CompileEventLogger.pt2_compile("my_event", foo=bar)

    - I want to add information to dynamo events and dynamo_compile
        CompileEventLogger.compilation_metric(foo=bar)
    N
event_namerp   metadatar=   time_nsOptional[int]	log_levelr   c                 C  sR   |d u rt  }t }|tjkrd}n|tjkrd}ntd|| ||| d S )NFTzjCannot log instant event at COMPILATION_METRIC level. Please choose one of CHROMIUM_EVENT or COMPILE_EVENT)timer   get_chromium_event_loggerr   r   r   RuntimeErrorlog_instant_event)r   r   r   r   chromium_loglog_pt2_compile_eventr7   r7   rL   r   _  s   

z$CompileEventLogger.log_instant_eventF	overwriteboolobjectc                 K  s   t  }| }|tjkr|j| fi | dS |tjkr4| }| |vr)td| |j| fi | dS |tjks;J | }| |krGtdt	 }|
 sRtd||| |j| fi | dS )z
        Centralized API for adding data to various events
        Log an event to a toplevel "dynamo" event or metrics context
        depending on log level.
        zError: specified log level PT2_COMPILE, but the event %s is not logged to pt2_compile_events. Make sure the event is active and you passed log_pt2_compile_event=True to dynamo_timedzLog level is COMPILATION_METRIC, but event_name isn't the toplevel event. CompilationMetrics must be logged to the toplevel event. Consider using `log_toplevel_event_data` directly.z[No metrics context is in progress. Please only call this function within a metrics context.N)r   get_pt2_compile_substackr   r   add_event_datar   r   r   get_outermost_eventr   in_progressupdate)r   r   r   r   r   pt2_compile_substack	top_eventmetrics_contextr7   r7   rL   add_datau  s2   

zCompileEventLogger.add_datac                 K  s4   t   }|du rtdtj|| |fi | dS )zC
        Syntactic sugar for logging to the toplevel event
        NzWNo toplevel event active. Please only call this function within a dynamo_timed context.)r   r   r   r   r   )r   r   r   r   r7   r7   rL   add_toplevel  s   
zCompileEventLogger.add_toplevelr   r   rR   c                 C     t  }|tjks|tjkr|| || dS |tjksJ | }| |kr)tdt }|	 s4td||| || || dS )z:
        Increments an existing field, or adds it
        zLog level is COMPILATION_METRIC, but event_name isn't the toplevel event. CompilationMetrics must be logged to the toplevel event. Consider using `increment_toplevel` directly.hNo metrics context is in progress. Please only call this function within a metrics context/dynamo_timed.N)
r   r   r   r   	incrementr   r   r   r   r   r   r   r   r   r   r   r   r7   r7   rL   r     "   

zCompileEventLogger.incrementr4   c                 C  2   t  }| }|du rtdt||| | dS )zX
        Increments a value on the toplevel metric. By default, logs to metric.
        N_No toplevel event active. Please only call this function within a metrics context/dynamo_timed.)r   r   r   r   r   r   r   r   r   r   r7   r7   rL   increment_toplevel  s   	z%CompileEventLogger.increment_toplevelr	   c                 C  r   )zl
        Add metadata <value> to a set of values with key <key>. Creates a set if it doesn't exist.
        zLog level is COMPILATION_METRIC, but event_name isn't the toplevel event. CompilationMetrics must be logged to the toplevel event. Consider using `add_to_set_metric` directly.r   N)
r   r   r   r   
add_to_setr   r   r   r   r   r   r7   r7   rL   r     r   zCompileEventLogger.add_to_setc                 C  r   )z
        Same as add to set, just does it automatically to the toplevel event instead of having to explicitly name it.
        Defaults to COMPILATION_METRIC log level.
        Nr   )r   r   r   r   r   r   r7   r7   rL   add_to_set_toplevel   s   
z&CompileEventLogger.add_to_set_toplevelc                 K     t j| tjfddi| dS )z
        Add <metadata> to <event_name> in chromium. Each key/value of metadata will appear in the chromium trace.
        <event_name> should be the name of a timed event span passed to `dynamo_timed`.
        r   FN)r   r   r   r   r   r   r7   r7   rL   chromium  s   
zCompileEventLogger.chromiumc                 K  r   )a  
        Add <metadata> to <event_name> in chromium and PT2 Compile Events.
        Each key/value of metadata will appear in the chromium trace. Each kwarg name becomes
        a column in PT2 Compile Events, with the corresponding kwarg value.
        <event_name> should be the name of a timed event span passed to `dynamo_timed`,
        with log_to_pt2_compile_events=True.
        r   FN)r   r   r   r   r   r7   r7   rL   pt2_compile  s   	
zCompileEventLogger.pt2_compilec                 K  s   t jtj| fi | dS )a6  
        Add <metadata> to the CompilationMetrics context. Also logs to PT2 Compile Events
        and chromium.
        Each key/value of metadata will appear in the chromium trace. Each kwarg name becomes
        a column in PT2 Compile Events and Dynamo Compile, with the corresponding kwarg value.
        N)r   r   r   r   )r   r   r7   r7   rL   compilation_metric+  s
   
z%CompileEventLogger.compilation_metricc                 C  s   t | ||tj dS )z
        Log an instant event to chromium logs with name <event_name> at time <time_ns>. The `args` field in
        Perfetto will point to metadata. <time_ns> should be a value obtained from time.time_ns().
        N)r   r   r   r   )r   r   r   r7   r7   rL   instant7  s   
zCompileEventLogger.instantc                 K  s   t  }|j| fi | dS )z
        Adds to an existing pt2_compile event, but silently returns if the event doesn't exist.
        This function is syntactic sugar for chromium_event_logger().try_add_event_data.
        N)r   try_add_event_data)r   r   r   r7   r7   rL   try_add_pt2_compileC  s   z&CompileEventLogger.try_add_pt2_compile)r   rp   r   r=   r   r   r   r   F)r   rp   r   r   r   r   r   r   )r   r   r   r   r   r   )r   rp   r   r   r   rp   r   rR   )r   rp   r   rR   r   r   )r   rp   r   r   r   rp   r   r	   )r   rp   r   r	   r   r   )r   rp   r   r   )r   r   r   r   r\   )r   rp   r   r=   r   r   )rF   rG   rH   r   staticmethodr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r7   r7   r7   rL   r   F  sD    -	r   Fr   
phase_nameOptional[str]r   r   r   Optional[dict[str, object]]dynamo_compile_column_us dynamo_compile_runtime_column_us
compile_idOptional[CompileId]
is_forwardOptional[bool]log_waitcounterGenerator[Any, None, None]c	                 c  sl   |dur| dsJ |du s|du sJ |r|}	| }
n| }	d}
| tvr)g t| < i }|r2|| |
r;|d|
i |durG|d| i t }t }||	|||| ztj	|  d* |rt
d|    dV  W d   n1 s{w   Y  ndV  W d   n1 sw   Y  W t }|| }t|  |d  ||	|i ||| |rt }| r|||d  t|	  |7  < |rt j||d |d	|d
d t|	  |7  < dS dS t }|| }t|  |d  ||	|i ||| |rt }| r|||d  t|	  |7  < |r5t j||d |d	|d
d t|	  |7  < w )aO  
    dynamo_timed is a context manager
    By wrapping a function in dynamo_timed, we can get a few things:

    1) Optionally log timings to pt2_compile_events.
    2) Optionally log timings to CompilationMetrics (dynamo_compile).
    3) Optionally log chromium events.
    4) Optionally increment a WaitCounter.
    5) Store a record in compilation_time_metrics
       For example:

        def _foo(...):
            with dynamo_timed("_foo"):
                ...

        Would show up as an entry in our timing dict:
        OrderedDict([('_foo', [0.083690, 0.23949, 3.1425e-05])])
        This is extremely useful for granular debugging.

    Although it is tempting to use dynamo_timed as a decorator, please do not.
    In its decorator form it makes cProfile traces less useful as dynamo_timed
    suddenly becomes a bottleneck for lots of function calls (as only one parent
    pointer is recorded).

    Params:
    - key: key into compile_time_metrics. If phase_name is not provided, this is
      also the event name used for pt2_compile_events logs and chromium events.
    - phase_name: Optional override for the event name.
    - log_pt2_compile_event: Whether to log a pt2 compile event internally.
    - metadata: Extra metadata to put in pt2_compile_events.
    - dynamo_compile_column_us: If provided, updates the specified CompilationMetrics
      field to be logged to dyname_compile column. We expect all columns to be _us;
      therefore, the field name must end with "_us".
    - dynamo_compile_runtime_column_us: Like 'dynamo_compile_column_us', but should
      be used for those columns captured outside of a compile context, e.g.,
      runtime autotuning.
    - compile_id: In the typical case, this parameter should not be needed. Use to
      supply the compile_id for those cases where we want to log a compile_id where
      it's not naturally available, e.g., for runtime autotuning.
    - is_forward: Optionally set an is_forward field for those logging destinations
      that support it.
    - log_waitcounter: If set, we'll log a waitcounter of the form "pytorch.dynamo_timed.{key}"
    N_usfn_nameis_backwardz (dynamo_timed)zpytorch.dynamo_timed.r     T)r   
is_runtimer   )extra)endswithr?   r   r   r   r   log_event_starttorchprofilerrecord_functionr'   guardappendlog_event_endr   r   r   rA   r   )r   r   r   r   r   r   r   r   r   r   r   event_metadatar   start_nsend_nstime_spent_nsr   r7   r7   rL   dynamo_timedM  s   9

	
	r   reprLiteral['str']	aggregatec                 C     d S r\   r7   r   r   r7   r7   rL   compile_times  r   r   Literal['csv']tuple[list[str], list[object]]c                 C  r   r\   r7   r   r7   r7   rL   r        c                   s|   dd f fdd	| dkr#fddt D }d}|t|d	d
7 }|S | dkr<fddt  D }tt  }||fS dS )a  
    Get metrics about torchdynamo frontend/backend compilation times.

    Accumulates information from functions tagged with `dynamo_timed`.

    repr='str' returns a printable string for user interaction, and 'csv'
    returns headers, rows which can be logged for output

    aggregate causes values from multiple compilations (e.g. split graphs)
    to be accumulated into one value.  If false, expect more than one value
    per metric.
    c                 S     | S r\   r7   xr7   r7   rL   <lambda>      zcompile_times.<locals>.<lambda>c                   s     r|t | S dt|| S )Nrs   )ra   rt   ru   )valuesitem_fn)r   r7   rL   fmt_fn  s   zcompile_times.<locals>.fmt_fnrp   c                   s$   g | ]}| t | d d dfqS )c                 S     | dS )Nz.4fr7   r   r7   r7   rL   r         *compile_times.<locals>.<listcomp>.<lambda>r   )r?   rv   kr  r7   rL   
<listcomp>  s    z!compile_times.<locals>.<listcomp>z!TorchDynamo compilation metrics:
)FunctionzRuntimes (s)rq   csvc                   s   g | ]
} |d d dqS )c                 S  r  )Nz.6fr7   r   r7   r7   rL   r     r  r  r  r7   )rv   vr  r7   rL   r	    s    N)r?   rz   r   listkeys)r   r   rk   r   r   rm   r7   )r   r  rL   r     s   

c                   C  s   t tddd d S )Nrp   Tr   )rf   infor   r7   r7   r7   rL   dump_compile_times     r  c                   @  s*   e Zd ZddddZdd	 ZdddZdS )DuplicateWarningChecker   maxsizerR   ro   r~   c                 C  s   || _ |   d S r\   )r  reset)selfr  r7   r7   rL   __init__  s   z DuplicateWarningChecker.__init__c                 C  s   t  | _d S r\   )r   setr  r7   r7   rL   r       zDuplicateWarningChecker.resetr   !Union[str, tuple[object, object]]r   c                 C  sd   || j v r| j j|dd tjsdS dS d | j |< t| j | jkr0| j jdd t| j | jks!dS )NT)lastF)r  move_to_endr5   verboselenr  popitemr  r   r7   r7   rL   add  s   

zDuplicateWarningChecker.addN)r  )r  rR   ro   r~   )r   r  ro   r   )rF   rG   rH   r  r  r"  r7   r7   r7   rL   r    s    r  c                  C  s$   t jdddk} | rt S t S )NTORCH_COMPILE_DEBUG01)osenvironr_   add_file_handler
contextlib	ExitStack)compile_debugr7   r7   rL   setup_compile_debug%  s   r,  c                   C     t   d S r\   )graph_break_dup_warning_checkerr  r7   r7   r7   rL   reset_graph_break_dup_checker.  r  r/  c                    sf   t jt d} t j| dd tt j| d td  t	
 }| fdd |S )NtorchdynamoTexist_okz	debug.logztorch._dynamoc                     
     S r\   removeHandlerr7   log_file_handlerloggerr7   rL   r   ;     
 z"add_file_handler.<locals>.<lambda>)r&  pathrt   get_debug_dirmakedirsloggingFileHandler	getLogger
addHandlerr)  r*  callback)log_path	exitstackr7   r6  rL   r(  2  s   

r(  c                    sV   t  } tjd ur)ttj tjj	 D ]
  |  fdd q| S | S )Nc                     r3  r\   r4  r7   r6  r7   rL   r   E  r9  z setup_log_file.<locals>.<lambda>)r)  r*  r5   log_file_namer=  r>  r   _logging	_internalget_loggersr@  rA  )rC  r7   r6  rL   setup_log_file?  s   

rH  c                 C  s(   t   d|j dt| j d|j dS )Nz/error_recordings/_z.rec)r;  co_nametyperF   co_firstlineno)exccoder7   r7   rL   gen_record_file_nameK  s   rO  filenamec                 C  s   z9t j| rtd|  W d S t jt j| dd t| d}|| W d    W d S 1 s2w   Y  W d S  t	yI   t
d|  Y d S w )Nz9Unable to write execution record %s; file already exists.Tr1  wbz#Unable to write execution record %s)r&  r:  existsrf   warningr<  dirnameopendump	Exception	exception)rP  exec_recordfr7   r7   rL   write_record_to_fileP  s   
&r[  gfx.Graphc                 C  s&   d}| j D ]}d|jv r|d7 }q|S )Nr   callr4   )nodesop)r\  cnr7   r7   rL   count_calls^  s   

rc  r   c                 C  r   r\   r7   r   r7   r7   rL   identityf  r   rd  c                 C  s6   zt |  W dS  ty   Y dS  ty   Y dS w NTF)hash	TypeError
ValueErrorr   r7   r7   rL   hashablej  s   ri  c                  O  r   r\   r7   argskwargsr7   r7   rL   nothingu  r   rm  c                   @  sJ   e Zd ZdZdd Zdd ZdddZd	d
 Zdd Zdd Z	dd Z
dS )ExactWeakKeyDictionaryz\Similar to weakref.WeakKeyDictionary, but use `is`/`id` rather than `==` to compare equalityc                 C  s   i | _ i | _d S r\   r   refsr  r7   r7   rL   r  |  s   
zExactWeakKeyDictionary.__init__c                 C  s   | j t| S r\   )r   idr!  r7   r7   rL   __getitem__     z"ExactWeakKeyDictionary.__getitem__Nc                 C  s   | j t||S r\   )r   r_   rq  )r  r   defaultr7   r7   rL   r_        zExactWeakKeyDictionary.getc                 C  s   t || jv S r\   )rq  r   r!  r7   r7   rL   __contains__  rs  z#ExactWeakKeyDictionary.__contains__c                   s<   t |  jvrt| fddj < |j < d S )Nc                   r3  r\   )
_remove_id)refidxr  r7   rL   r     r9  z4ExactWeakKeyDictionary.__setitem__.<locals>.<lambda>)rq  rp  weakrefrx  r   )r  r   r   r7   ry  rL   __setitem__  s   
z"ExactWeakKeyDictionary.__setitem__c                 C  s,   || j v r	| j |= || jv r| j|= d S d S r\   ro  )r  rz  r7   r7   rL   rw    s
   

z!ExactWeakKeyDictionary._remove_idc                 C  s   | j   | j  d S r\   )rp  r]   r   r  r7   r7   rL   r]     s   
zExactWeakKeyDictionary.clearr\   )rF   rG   rH   r   r  rr  r_   rv  r|  rw  r]   r7   r7   r7   rL   rn  y  s    
rn  objr   allowed_typestype[T]	TypeIs[T]c                 C  r   r\   r7   r}  r~  r7   r7   rL   istype  r   r  )tuple[type[list[T]], type[tuple[T, ...]]]c                 C  r   r\   r7   r  r7   r7   rL   r    r   Iterable[type]c                 C  r   r\   r7   r  r7   r7   rL   r    r   c                 C  s(   t |tttfrt| |v S t| |u S )zisinstance() without subclasses)
isinstancetupler  r  rK  r  r7   r7   rL   r    s   rE      c                 C  s.   t jdkrt| trdS t| tjp| tju S )Nr  T)sysversion_infor  _builtin_final_typing_classestyping_Finalr   r   r7   r7   rL   	is_typing  s   	r  c              
   C  s2   t sdS t| t jt jt jt jt jt jt jt j	fS NF)
npr  int8int16int32int64uint8uint16uint32uint64r  r7   r7   rL   is_numpy_int_type  s   r  c                 C  s   t sdS t| t jt jt jfS r  )r  r  float16float32float64r  r7   r7   rL   is_numpy_float_type  s   r  c                 C  s   t | tjott| dS )N__wrapped__)r  	functools_lru_cache_wrapperis_functioninspectgetattr_staticr  r7   r7   rL   is_lru_cache_wrapped_function  s   
r  c                 C  s   t | pt| tjjtjjfS r\   )r  r  r   _opsOpOverloadPacket
OpOverloadr  r7   r7   rL   is_function_or_wrapper  s   
r  c                 C  s   t | tjtjtjtjfS r\   )r  typesFunctionTypeBuiltinFunctionTypeMethodDescriptorTypeWrapperDescriptorTyper  r7   r7   rL   r    s   r  )__eq____ne____lt____le____gt____ge__z==z!=<z<=>z>=c                 C  s   t | tjtjtjtjtjfS r\   )r  r  GetSetDescriptorTyper  r  MemberDescriptorTyper   r  r7   r7   rL   is_wrapper_or_member_descriptor  s   r  c                 C  s   t | d S r   ) unwrap_with_attr_name_if_wrapper)fnr7   r7   rL   unwrap_if_wrapper)  r  r  c                 C  s<   t | rt| ddrt| d| } d}| |fS d }| |fS )N_torchdynamo_inlineF)r  r  r  )r  	attr_namer7   r7   rL   r  -  s   r  c                 C  s   t sdS t| t jS r  )r  r  ndarrayr  r7   r7   rL   is_numpy_ndarray8  s   r  c                 C  s.   t jt jjgtjR }|t jjf }t| |S )zCheck of obj is a tensor)	r   Tensornn	Parameterr5   traceable_tensor_subclasses_subclassesr8   r  )r}  tensor_listr7   r7   rL   istensor?  s   
r  c                 C  s
   t | tS r\   )r  r(   )modr7   r7   rL   is_lazy_moduleJ     
r  r  c                  G  s   t |   d S r\   )r   rk  r7   r7   rL   
print_onceN  r   r  c                   s6   |   fdd}|j durt|j dksJ |j d S )zNSome black magic to create a cell object that usually only exists in a closurec                         S r\   r7   r7   r   r7   rL   rZ  W  r   zmake_cell.<locals>.fNr4   r   )__closure__r  )valrZ  r7   r   rL   	make_cellS  s   
r  c                 C  s   zt dd | D }dd | D }||fW S  tyM } z*ddlm} ddlm} |dd	||   d
|t|   dg |d W Y d }~d S d }~ww )Nc                 s      | ]}|  V  qd S r\   as_proxyrv   argr7   r7   rL   rx   `      z$proxy_args_kwargs.<locals>.<genexpr>c                 S  s   i | ]	\}}||  qS r7   r  )rv   r   r  r7   r7   rL   
<dictcomp>a  s    z%proxy_args_kwargs.<locals>.<dictcomp>r4   unimplemented_v2)typestrz&Failed to convert args/kwargs to proxyzcall_function args: r   z7Missing `as_proxy()` implementation for some arg/kwarg.gb_typecontextexplanationhintsfrom_exc)	r  r   NotImplementedErrorrM  r  variables.baser  r  r   )rk  rl  
proxy_argsproxy_kwargser  r  r7   r7   rL   proxy_args_kwargs^  s    
r  r  Optional[float]r   c                 C     | d u rd S t | d S Nr   rR   r  r7   r7   rL   	to_int_msp     r  c                 C  r  )Ni@B r  r  r7   r7   rL   	to_int_usv  r  r  rE   c                   @  s  e Zd ZU dZded< dZded< dZded< dZded< dZded< dZ	ded	< dZ
ded
< dZded< dZded< dZded< dZded< dZded< dZded< dZded< dZded< dZded< dZded< dZded< dZded< dZded< dZded< dZded< dZded< dZded< dZded< dZded < dZded!< dZded"< dZ ded#< dZ!ded$< dZ"ded%< dZ#ded&< dZ$ded'< dZ%ded(< dZ&ded)< dZ'ded*< dZ(ded+< dZ)ded,< dZ*ded-< dZ+ded.< dZ,ded/< dZ-ded0< dZ.ded1< dZ/ded2< dZ0ded3< dZ1ded4< dZ2ded5< dZ3ded6< dZ4ded7< dZ5ded8< dZ6ded9< dZ7ded:< dZ8ded;< dZ9ded<< dZ:ded=< dZ;ded>< e<Z=d?ed@< dZ>dedA< dZ?dedB< dZ@dedC< dZAdedD< dZBdedE< dZCdedF< dZDdedG< dZEdedH< dZFdedI< dZGdJedK< dZHdedL< dMZIdedN< dZJdedO< dZKdedP< dZLdedQ< dZMdedR< dZNdedS< dZOdedT< dZPdedU< dZQdedV< dZRdedW< dZSdedX< eTd]d[d\ZUdS )^CompilationMetricsNr   r   	frame_keyrJ  co_filenamer   rL  
cache_sizeaccumulated_cache_sizeguard_countshape_env_guard_countgraph_op_countgraph_node_countgraph_input_countr  
start_timeentire_frame_compile_time_sbackend_compile_time_sinductor_compile_time_scode_gen_time_s	fail_typefail_reasonfail_user_frame_filenamefail_user_frame_linenozOptional[set[str]]non_compliant_opscompliant_custom_opsrestart_reasonsdynamo_time_before_restart_sr   has_guarded_coderemote_cache_time_saved_sstructured_logging_overhead_sconfig_suppress_errors config_inline_inbuilt_nn_modulesspecialize_floatdynamo_configr   num_triton_bundles!remote_fx_graph_cache_get_time_ms!remote_fx_graph_cache_put_time_msstart_time_usduration_us!dynamo_cumulative_compile_time_us'aot_autograd_cumulative_compile_time_us#inductor_cumulative_compile_time_us,inductor_code_gen_cumulative_compile_time_ustriton_compile_time_usruntime_cudagraphify_time_usruntime_triton_autotune_time_us%dynamo_compile_time_before_restart_uscuda_synchronize_time_us distributed_ephemeral_timeout_usstructured_logging_overhead_us!remote_fx_graph_cache_get_time_us!remote_fx_graph_cache_put_time_us#backward_cumulative_compile_time_usend_time_uspre_grad_pass_time_uspost_grad_pass_time_usjoint_graph_pass_time_usrR   log_format_versioninductor_configremote_cache_version"inductor_fx_remote_cache_hit_count#inductor_fx_remote_cache_miss_count%inductor_fx_remote_cache_backend_type!inductor_fx_remote_cache_hit_keys"inductor_fx_remote_cache_miss_keyscuda_versiontriton_versionzOptional[dict[str, bool]]feature_usagecompile_time_autotune_time_usFr   
gc_time_ustensorify_float_attempttensorify_float_successtensorify_float_failureguard_latency_usrecompile_reasonnum_graph_breakstriton_kernel_compile_times_usir_countcudagraph_skip_reasonmetricsr=   c           	      C  s  ddd}ddd}d dd}d dd}|| d|| d|| d|| d|| d|| d|| d|| d|| dd	}i ||}|| d|d< || d|d< || d|d< | d}|ryt|nd|d< | d!i |S )"z
        Factory method to create a CompilationMetrics from a dict of fields.
        Includes the logic to add legacy fields and any pre-processing, e.g.,
        we transform some fields to comma-separated strings for scuba logging.
        metricr   ro   r  c                 S  s   | d ur| d S d S )Ng    .Ar7   r;  r7   r7   rL   us_to_s     z*CompilationMetrics.create.<locals>.us_to_sc                 S  s   | d ur| d S d S r  r7   r<  r7   r7   rL   us_to_ms  r>  z+CompilationMetrics.create.<locals>.us_to_msOptional[Any]r   c                   sD   ddd | d u rd S t | ttfsdS d fd	d
t| D S )Nitemr	   ro   rp   c                 S  s    zt | W S  ty   Y dS w N	<unknown>)rp   rW  )rA  r7   r7   rL   safe_str  s
   
zFCompilationMetrics.create.<locals>.collection_to_str.<locals>.safe_strrC  ,c                 3      | ]} |V  qd S r\   r7   )rv   rA  rD  r7   rL   rx     r  zGCompilationMetrics.create.<locals>.collection_to_str.<locals>.<genexpr>)rA  r	   ro   rp   )r  r  r  rt   sortedr<  r7   rG  rL   collection_to_str  s   
z4CompilationMetrics.create.<locals>.collection_to_strc                 S  s2   | d u rd S zt t| W S  ty   Y dS w rB  )jsondumpsr  rW  r<  r7   r7   rL   collection_to_json_str  s   z9CompilationMetrics.create.<locals>.collection_to_json_strr  r  r  r  r  r  r  r  r  )	r  r  r  r  r  r  r  r  r  r*  r+  r7  r   N)r;  r   ro   r  )r;  r   ro   r   )r;  r@  ro   r   r7   )r_   rp   )	rV   r:  r=  r?  rI  rL  legacy_metricsall_metricsr   r7   r7   rL   create  sV   




zCompilationMetrics.create)r:  r=   )VrF   rG   rH   r   ri   r  rJ  r  rL  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r	  r
  r  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r!  r"  r#  LOG_FORMAT_VERSIONr$  r%  r&  r'  r(  r)  r*  r+  r,  r-  r.  r/  r   r0  r1  r2  r3  r4  r5  r6  r7  r8  r9  rj   rO  r7   r7   r7   rL   r    s   
 r  @   maxlenz%collections.deque[CompilationMetrics]_compilation_metricsra  c                 C  s,  t  }| }|sdS |jdi d|d| jd| jd| jd| jd| jd| jd	| j	d
| j
d| jd| jd| jd| jd| jd| jd| jd| jdurYt| jndd| jdurft| jndd| jdurst| jndd| jd| jd| j dS d| jd| jd| j dS )a  
    These are the common fields in CompilationMetrics that existed before
    metrics_context, and aren't set by MetricsContext.set(). We add the subset
    of them that make sense in `dynamo`/toplevel events in PT2 Compile Events
    directly.

    If you're tempted to add to this list, consider using CompileEventLogger.compilation_metric()
    instead, which will automatically also add it to tlparse and PT2 Compile Events.
    TODO: Get rid of this function and replace it with CompileEventLogger directly instead.
    Nr   r  rJ  r  rL  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r7   )r   r   r   r  rJ  r  rL  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  )ra  event_loggerr   r7   r7   rL   #add_compilation_metrics_to_chromium1  s   
	






rV  c                  C  s$   ddd} | t  }tj|ddS )	Ndr=   ro   c                   s   h d  fdd|   D S )N>   r  base_dirrepro_afterrepro_levelTYPE_CHECKINGrD  debug_dir_rootrepro_tolerancerepro_forward_only_custom_ops_profile_save_config_ignorerepro_ignore_non_fpignore_logger_methodslog_compilation_metricssame_two_models_use_fp64r  reorderable_logging_functions)_autograd_backward_strict_mode_banned_ops+inject_BUILD_SET_unimplemented_TESTING_ONLYc                   s0   i | ]\}}| vr|t |trt|n|qS r7   )r  r  rH  )rv   r   r   	blocklistr7   rL   r  y  s
    zJ_get_dynamo_config_for_logging.<locals>.clean_for_json.<locals>.<dictcomp>)r   rW  r7   rh  rL   clean_for_jsonb  s   
z6_get_dynamo_config_for_logging.<locals>.clean_for_jsonT)	sort_keys)rW  r=   ro   r=   )r5   get_config_copyrJ  rK  )rk  config_dictr7   r7   rL   _get_dynamo_config_for_logginga  s   
ro  c                  C  s   G dd dt j} t }d}tjjrtjj nd}|dur]z2| D ]\}}t|t	s1|
| t|tr<t|||< q#|D ]}||= q?t j|| ddd}W |S  ty\   d}Y |S w |S )zN
    Method to parse and scrub uninteresting configs from inductor config
    c                      s   e Zd Z fddZ  ZS )zA_scrubbed_inductor_config_for_logging.<locals>.TypeSafeSerializerc                   s$   zt  |W S  ty   Y dS w )NzValue is not JSON serializable)superrt  rW  )r  o	__class__r7   rL   rt    s
   zI_scrubbed_inductor_config_for_logging.<locals>.TypeSafeSerializer.default)rF   rG   rH   rt  __classcell__r7   r7   rr  rL   TypeSafeSerializer  s    ru  NT)rV   skipkeysrl  z(Inductor Config is not JSON serializable)rJ  JSONEncoderr  r   	_inductorr5   rm  r   r  rp   r"  r  rK  rW  )ru  keys_to_scrubinductor_conf_strinductor_config_copyr   r  r7   r7   rL   %_scrubbed_inductor_config_for_logging  s6   


	r|  start_time_nsend_time_nsr:  exc_typeOptional[type[BaseException]]	exc_valueOptional[BaseException]c                   sD  t jj r zddlm} |}d}W n ty   d }d }Y nw d }d }|d}|s1t jj	
 }|| d |d ||  d |rB|jnd |rIt|nd tt j t t t jjt r]tjnd||d}	ti |	| t  d}
 jd	u r|d
|
 }
 jdu r|
d }
t jj|
 fddd	|d t  tj rt!  d S d S )Nr   )REMOTE_CACHE_VERSION_ManifoldCacher   r    )r   r  r   r  r  r  r  r  r%  r,  r-  r&  r)  compilation_metricsFbwd_T_runtimec                     s   dd t   D S )Nc                 S  s(   i | ]\}}|t |trt|n|qS r7   )r  r  r  )rv   r  r  r7   r7   rL   r    s    z@record_compilation_metrics.<locals>.<lambda>.<locals>.<dictcomp>)dataclassesasdictr   r7   r  r7   rL   r     s    z,record_compilation_metrics.<locals>.<lambda>)record_logging_overheadr   )"r   rx  utils should_use_remote_fx_graph_cachetorch._inductor.fb.remote_cacher  ModuleNotFoundErrorr_   _guardsCompileContextcurrent_compile_idrH   rp   r  rE  get_structured_logging_overheadro  r|  versioncudar)   triton__version__r  rO  rT  r   r   r   trace_structuredrV  r5   rc  r"   )r}  r~  r:  r  r  r  r&  r)  r   common_metricsrU   r7   r  rL   record_compilation_metrics  s^   





r  )on_exitnew_sizec                 C  s6   t t| krt  t t| kstjt| d}|ad S )NrR  )r  rT  popleftrg   deque)r  	new_dequer7   r7   rL   set_compilation_metrics_limit  s
   r  c                   C  r-  r\   )rT  r]   r7   r7   r7   rL   clear_compilation_metrics	  r   r  list[CompilationMetrics]c                   C  s   t tS r\   )r  rT  r7   r7   r7   rL   get_compilation_metrics  s   r  c                   @  s   e Zd ZdZd4ddZd5ddZd	d
 Zd6ddZdd Zd7ddZ	d7ddZ
d8ddZd9ddZ		 d:d;d'd(Zd<d)d*Z	 d=d>d,d-Z	 d=d?d0d1Z	 	d@dAd2d3Zd S )BChromiumEventLoggera  Logs chromium events to structured logs. tlparse will concatenate these into a perfetto UI link.

    See https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview#heading=h.yr4qxyxotyw for
    a specification of the Chromium Event JSON format.
    ro   	list[str]c                 C  $   t | jdr
| jjS g | j_| jjS )z]
        The main event stack, with every chromium event.
        Logged to tlparse.
        stack)hasattrtlsr  r  r7   r7   rL   	get_stack     zChromiumEventLogger.get_stackr   c                 C  s   |   }|r
|d S dS )zv
        Get the outermost event name (i.e. the longest running event)
        or None if the stack is empty.
        r   N)r  )r  r  r7   r7   rL   r   $  s   z'ChromiumEventLogger.get_outermost_eventc                 C  r  )zq
        A smaller subset of the main stack that gets used to log
        PT2 Compile Events internally.
        r   )r  r  r   r  r7   r7   rL   r   ,  r  z,ChromiumEventLogger.get_pt2_compile_substackr=   c                 C  s   t | jds
i | j_| jjS )N
event_data)r  r  r  r  r7   r7   rL   get_event_data7  s   z"ChromiumEventLogger.get_event_datac                 C  s*   t  | _tt | _td| j d S )Nz*ChromiumEventLogger initialized with id %s)		threadinglocalr  rp   uuiduuid4id_rf   r  r  r7   r7   rL   r  <  s   
zChromiumEventLogger.__init__r   rp   r~   c                 K  s&   ||   vrdS | j|fi | dS )zd
        Same as add_event_data, but will silently not log if the event isn't in the stack.
        N)r  r   )r  r   rl  r7   r7   rL   r   E  s   z&ChromiumEventLogger.try_add_event_datac                 K  sT   ||   vrtdt| d|    d|  }||vr!i ||< || | dS )zz
        Adds additional metadata info to an in-progress event
        This metadata is recorded in the END event
        Event  not in q. Cannot add metadata to events that aren't in progress. Please make sure the event has started and hasn't ended.N)r  r   r   r  r   )r  r   rl  r  r7   r7   rL   r   M  s   	z"ChromiumEventLogger.add_event_datar   r   rR   c                 C  sr   ||   vrtdt| d|    d|  }||vr!i ||< ||| vr-d|| |< || |  |7  < dS )zK
        Increment an integer event data field by the given amount
        r  r  r  r   N)r  r   r   r  r  r   r   r   r  r7   r7   rL   r   a  s   zChromiumEventLogger.incrementr	   c                 C  sr   ||   vrtdt| d|    d|  }||vr!i ||< ||| vr.t || |< || | | dS )zR
        Add a value to a set within a event_name's metadata if it exists
        r  r  r  N)r  r   r   r  r  r"  r  r7   r7   rL   r   s  s   	zChromiumEventLogger.add_to_setFNr   r   r   r   r   r   c                 C  sf   |pt jj }t||d< | ||d| |  | | j|fi | |r1| 	 | dS dS )a  
        Logs the start of a single event.
        :param str event_name Name of event to appear in trace
        :param time_ns Timestamp in nanoseconds
        :param metadata: Any extra metadata associated with this event
        :param log_pt2_compile_event: If True, log to pt2_compile_events
        :param compile_id: Explicit compile_id (rather than using the current context)
        r   BN)
r   r  r  r  rp   _log_timed_eventr  r   r   r   r  r   r   r   r   r   r7   r7   rL   r     s   z#ChromiumEventLogger.log_event_startc                 C  s4   |   }|  }|  |  |  }|  d S r\   )r  r   r]   r  )r  r  substackr  r7   r7   rL   r    s   zChromiumEventLogger.resetr}  c                   s   |pt jj }t||d< |  } |v r|  }| = ni }|| |  |d|}	 fdd}
|  } |vrBt	
d dS |
| |r\|  }|
| t|	|| j| |  |  dS )a&  
        Logs the end of a single event. This function should only be
        called after log_event_start with the same event_name.
        :param event_name: Name of event to appear in trace
        :param time_ns: Timestamp in nanoseconds
        :param metadata: Any extra metadata associated with this event
        :param start_time_ns: The start time timestamp in nanoseconds
        :param log_pt_compile_event: If True, log to pt2_compile_events
        :param compile_id: Explicit compile_id (rather than using the current context)
        r   Ec                   s2    | d krt d |    | d ksd S d S )Nz>ChromiumEventLogger: Detected overlapping events, fixing stack)rf   rS  pop)r  r   r7   rL   	pop_stack  s   z4ChromiumEventLogger.log_event_end.<locals>.pop_stackz7ChromiumEventLogger: Start event not in stack, ignoringN)r   r  r  r  rp   r  r   r  r  rf   rS  r   r!   r  r  )r  r   r   r   r}  r   r   all_event_datar   eventr  event_stackr   r7   r  rL   r     s8   



z!ChromiumEventLogger.log_event_endr   Optional[dict[str, Any]]c                   s@   ||d ||dddd t jjd fddddd	 t   S )
za
        Logs a timed event in chromium format. See log_event_start, log_event_end, etc.
        r   r   r   )rU   tsrk  phcattidpidchromium_eventc                     r  r\   r7   r7   r  r7   rL   r     r   z6ChromiumEventLogger._log_timed_event.<locals>.<lambda>F
payload_fnsuppress_contextexpect_trace_id)r   rE  r  r#   )r  r   r   r   r   r7   r  rL   r    s    

z$ChromiumEventLogger._log_timed_eventc              	     sz   |du ri }t tjj }||d< ||d |dddddd tjjd	 fd
dddd |r;t |  | j	| dS dS )aZ  
        Log an instant event with no associated duration.
        :param str event_name: Name of event to appear in trace
        :param int time_ns Timestamp in nanoseconds
        :param Optional[Dict[str, Any]] metadata: Any extra metadata associated with this event
        :param str cname optional color for the arrow in the trace
        Nr   r   ir   r   p)rU   r  rk  r  r  r  r  sr  c                     r  r\   r7   r7   r  r7   rL   r   7  r   z7ChromiumEventLogger.log_instant_event.<locals>.<lambda>FTr  )
rp   r   r  r  r  rE  r  r!   r   r  r  r7   r  rL   r     s0   
z%ChromiumEventLogger.log_instant_event)ro   r  ro   r   )ro   r=   )r   rp   ro   r~   )r   rp   r   rp   r   rR   )r   rp   r   rp   r   r	   FN)r   rp   r   rR   r   r=   r   r   r   r   ro   r~   ro   r~   r\   )r   rp   r   rR   r   r=   r}  rR   r   r   r   r   ro   r~   )
r   rp   r   rR   r   rp   r   r  ro   r=   r  )
r   rp   r   rR   r   r  r   r   ro   r~   )rF   rG   rH   r   r  r   r   r  r  r   r   r   r   r   r  r   r  r   r7   r7   r7   rL   r    s,    



	



N!r  zOptional[ChromiumEventLogger]CHROMIUM_EVENT_LOGc                   C  s   t d u rt a t S r\   )r  r  r7   r7   r7   rL   r   E  s   r   r   reset_event_log_on_exitc                 c  sz    t  }t }|| |i | zdV  W || t i || |r(|  dS dS || t i || |r<|  w w )z
    Context manager that creates a chromium start and end event. Chromium event
    logging is integrated with dynamo_timed, so you probably want to use that
    instead. Use this context manager only if you want to avoid dynamo_timed.
    N)r   r   r   r   r   r  )r   r  r   chromium_event_logchromium_start_timer7   r7   rL   chromium_event_timedL  s>   
r  c                   @  s6   e Zd ZU dZded< ded< dd Zedd	 Zd
S )CleanupHookz,Remove a global variable when hook is calledr=   scoperp   rU   c                 G  s$   t d urt  jd8  _| j| j= d S r   )CleanupManagerrX   r  rU   r  rk  r7   r7   rL   __call__t  s   zCleanupHook.__call__c                 C  s,   || vsJ t  jd7  _|| |< t| |S r   )r  rX   r  )r  rU   r  r7   r7   rL   rO  z  s   
zCleanupHook.createN)rF   rG   rH   r   ri   r  r   rO  r7   r7   r7   rL   r  m  s   
 r  c                      s*   e Zd ZU dZded<  fddZ  ZS )r  r   zClassVar[CleanupManager]instancec                   s&   | j | D ]}|  qt | d S r\   )r   rp  rw  )r  rz  hookrr  r7   rL   rw    s   zCleanupManager._remove_id)rF   rG   rH   rX   ri   rw  rt  r7   r7   rr  rL   r    s   
 r  c                 C  s0   |   | j}| jr| jdur| j  |_|S )z!Clone the tensor and its gradientN)clonerequires_grad_requires_gradis_leafgradr   yr7   r7   rL   clone_tensor  s   r  dtypec             	     s.  t | r| S  fdd}t  | jjdkr"|| W  d   S | jtju rCtj||  || 	 | j
|  dW  d   S t| r|| jtjtjhv rY|  }|  }n|  }|  }tj||||||  | j
| jdW  d   S tdd t|  |  D }| jrt|d	 f| }ntj|d	  p| j| jd
}|  |  d	 |   }||  |  | z"| | !  | j"r|#| j$ | j"r| j%durt&| j% d|_%W n t'y   ||  Y W  d   S w t(| dr| j)* |_)|W  d   S 1 sw   Y  dS )zcopy while preserving stridesc                   sV   t | }| jr|| j | jr| jd urt| j d|_t| dr)| j	 |_|S )Nr  _dynamo_dynamic_indices)
r   r  r  r  r  r  clone_inputr  r  copyr  r  r7   rL   torch_clone  s   

z clone_input.<locals>.torch_clonexlaN)is_coalesced)layoutc                 s  s     | ]\}}|d  | V  qdS )r4   Nr7   )rv   shapestrider7   r7   rL   rx     ry   zclone_input.<locals>.<genexpr>    )r  devicer  r  )+r9   r   no_gradr  rK  r  
sparse_coosparse_coo_tensor_indicesrO   r  r  r   
sparse_csr
sparse_bsrcrow_indicescol_indicesccol_indicesrow_indicessparse_compressed_tensorr   ra   zipsizer  is_quantizedempty_quantizedemptyr  data_ptrelement_sizeas_strided_copy_r  r  r  r  r  r  r   r  r  r  )r   r  r  compressed_indicesplain_indicesneeded_sizeresultcache_line_offsetr7   r  rL   r    sp   






/&r  c                 C  s   t | tu r3t| }| D ]"\}}t|trt|||< qt|tjs*J t |t|||< q|S t	| }t
t|D ]}t|| tjrOt|| ||< q=|S r\   )rK  dictr   r  r  clone_inputsr   r  r  r  ranger  )example_inputsresr   r   r  r7   r7   rL   r    s   
r  r  torch.Tensorc              
   C  sV   z|    W d S  ty* } zddlm} tddt| }|d| |d }~ww )Nr4   )	SkipFramez\(.*r  z(torch.compile cannot be run in context: )r  r   rM  r  resubr   )r  r  r  functorch_subclass_namer7   r7   rL   skip_frame_if_in_functorch_mode  s   r  c                  c  s^   t jj} t jjj}| 4 |  ! t t j }t	| t j
 r+t t j
 }W d    n1 s5w   Y  W d    n1 sDw   Y  z6d V  W t jj " t j| t j
 rnt j
| W d    d S W d    d S 1 syw   Y  d S t jj   t j| t j
 rt j
| W d    w W d    w 1 sw   Y  w r\   )r   _C_DisableFuncTorchr  _python_dispatch_disable_current_modesr  randomget_rng_stater  r  is_availableset_rng_state)disable_functorchdisable_current_modes	rng_statecuda_rng_stater7   r7   rL   preserve_rng_state  s6   

 
0
r'  c                 C  s&   t | tjjjtjjjtjjtjjfS r\   )	r  r   jit_traceTopLevelTracedModule_scriptRecursiveScriptModuleScriptFunctionScriptModule)model0r7   r7   rL   is_jit_model  s   r0  c                 C  sx   t | r| S ztj| |W S  ty;   z	tj| W  Y S  ty:   |r-td n	td Y Y d S Y Y d S w w )Nz	jit errorz0Both torch.jit.trace and torch.jit.script failed)	r0  r   r(  tracerW  scriptrf   rX  error)modelr  r  r7   r7   rL   torchscript  s    r5  c              	   C  s&   zt | W S  ttfy   Y d S w r\   )r  getfilerg  OSErrorr}  r7   r7   rL   r6  1  s
   r6  c                 C     t t| S )zLTest if an object is a namedtuple or a torch.return_types.* quasi-namedtuple)is_namedtuple_clsrK  r8  r7   r7   rL   is_namedtuple8  r   r;  c                   s   zTt  trFt dd}|dv rW dS tt ddtrItt ddrLtdd  jD }|tfkr6W dS |rOt fd	d|D rRW dS W d
S W d
S W d
S W d
S W d
S  ty^   Y d
S w )zhTest if an object is a namedtuple or a (torch.return_types|torch.autograd.forward_ad).* quasi-namedtuplerG   N)torch.return_typesztorch.autograd.forward_adT_fields_makec                 s  s    | ]	}|t ur|V  qd S r\   )r   rv   tr7   r7   rL   rx   H      z$is_namedtuple_cls.<locals>.<genexpr>c                 3  s$    | ]}t |o j|ju V  qd S r\   )r:  __new__r?  r^   r7   rL   rx   L  s    

F)
issubclassr  getattrr  callable	__bases__anyrg  )rV   modulebasesr7   r^   rL   r:  =  s:   


	r:  tuple[str, ...]c                 C  s   | t u rdS t| tsJ t| dr| jS tjG dd d}| jdks&J | t|t	| j
}i }t|D ]}|d dkrNtt|||rNt||j||< q6t|| j
ksXJ tt||jdS )	zIGet the fields of a namedtuple or a torch.return_types.* quasi-namedtuple)startstopstepr=  c                   @  s   e Zd ZU ded< dS )z!namedtuple_fields.<locals>.MarkerrR   indexNrF   rG   rH   ri   r7   r7   r7   rL   Markerf  s   
 rP  r<  r   rI  )r   )slicerC  r  r  r=  r  	dataclassrG   ru   r  n_fieldsdirr  rD  rN  r  rH  r_   )rV   rP  r}  fieldsrU   r7   r7   rL   namedtuple_fields[  s    
rV  c                   s   t  , t t j t j rt t j  dd t| 	 | 
 D W d    n1 s3w   Y   fdd}|S )Nc                 S  s   g | ]}||j t|fqS r7   )_versionr   r  )rv   paramr7   r7   rL   r	  z      z%checkpoint_params.<locals>.<listcomp>c                    st   t  , t j t j rt j  D ]\} }}| j|kr'| | qW d    d S 1 s3w   Y  d S r\   )r   r  r  r"  r  r!  rW  r
  )rX  r  original_valuer&  r%  saved_stater7   rL   restore  s   



"z"checkpoint_params.<locals>.restore)r   r  r  r  r   r  r!  r|   r}   
parametersbuffers)gmr]  r7   r[  rL   checkpoint_paramsu  s   

		ra  c                 C  sh   t j r
t jj}nt}|  t  t d t	 }t
|D ]	}| | }|  q t	 }||| fS )Ni9  )r   r  r!  synchronizerm  gccollectmanual_seedr   perf_counterr  )r4  r  timesrb  t0rI  r  t1r7   r7   rL   timed  s   


rj  c                 C  s    t dd t|| dD S )Nc                 s  s    | ]}|j V  qd S r\   )is_cudarv   r   r7   r7   rL   rx     s    z check_is_cuda.<locals>.<genexpr>T)allr|   r}   r^  )r`  r  r7   r7   rL   check_is_cuda  s    rn  r  c                 C  sn   | dksJ dd t | D }t|dd  |d d  }tdd| dd| d}d	|  d
|_|S )Nr4   c                 S  s   g | ]}d | qS r  r7   rv   r  r7   r7   rL   r	        z rot_n_helper.<locals>.<listcomp>r  zlambda rE  z: ()rot__helper)r  reversedevalrt   rF   )rb  varsrotatedr  r7   r7   rL   rot_n_helper  s   "rx  z	set[type]common_constant_typesc                 C  sH   t | ttfrttt| S t| tjt	t
jtjtjfp#t | tthB S r\   )r  r  	frozensetrm  ru   is_safe_constantr  enumEnumrK  r   Sizer  _GenericAliasr  GenericAliasry  rQ  r  r7   r7   rL   r{    s    	r{  c                   C  s   ddhS Nr   r4   r7   r7   r7   r7   rL   common_constants  s   r  c                 C  s(   t | tjtjfot | jtjjjj S r\   )	r  r   SymBoolSymIntnodenestedrF  
nested_intNestedIntNoder  r7   r7   rL   is_torch_sym  s   r  c                 C  sj   ddl m} t j o4|   p4|  otj	 p4| 
 o&tj	 p4||p4td o4| t v S )Nr4   )is_from_defaultsz5pytorch/dynamo:enable_unspecialize_zero_one_plain_int)sourcer  r   r_   #force_unspec_int_unbacked_size_likeguard_sourceis_localis_specialized_nn_moduler5   allow_unspec_int_on_nn_module"is_unspecialized_builtin_nn_moduler    r  )r   r  r  r7   r7   rL   is_int_specialization_case  s   	
r  c                 C  s   ddl m}m}m} t| |r3|  s3|  }|  }t|p.t	j
 o.t|tu o.t|| }|s3| S t| |r?||  S | S )Nr4   )ConstantVariableLazyVariableTrackerSymNodeVariable)	variablesr  r  r  r  is_realizedoriginal_sourcerZ  r  r5   specialize_intrK  rR   r  rO  evaluate_expr)r  r  r  r  r  r   is_symnode_vtr7   r7   rL   specialize_symnode
	  s   


r  c                 C  s*   ddl m} t| } t| |r|  S | S )Nr4   r  )r  r  r  r  as_python_constant)r  r  r7   r7   rL   guard_if_dyn#	  s
   
r  c                 C  s   t dd t| | D S )Nc                 s  r  r\   )is_python_constantrl  r7   r7   rL   rx   /	  r  z&check_constant_args.<locals>.<genexpr>)rm  r|   r}   r   rj  r7   r7   rL   check_constant_args.	  s   r  c                 C  s^   ddl m} ddlm} d}t| | D ]}t||r"|d7 }qt||s* dS q|dkS )Nr4   r  UnspecializedPythonVariabler   F)variables.constantr  variables.tensorr  r|   r}   r   r  )rk  rl  r  r  unspec_countr   r7   r7   rL   check_unspec_python_args2	  s   


r  c                 C  s>   ddl m} t| | D ]}| st||s dS qdS )Nr4   r  FT)r  r  r|   r}   r   r  r  )rk  rl  r  r   r7   r7   rL   check_unspec_or_constant_args?	  s   r  c                   s.   ddl m  t fddt| | D S )Nr4   NumpyNdarrayVariablec                 3  s    | ]}t | V  qd S r\   )r  rl  r  r7   rL   rx   M	  s
    
z+check_numpy_ndarray_args.<locals>.<genexpr>)r  r  rG  r|   r}   r   rj  r7   r  rL   check_numpy_ndarray_argsJ	  s   r  ztype[KeysView[Any]]	dict_keysztype[ValuesView[Any]]dict_valuesodict_valuesztype[Iterator[Any]]tuple_iteratorrange_iteratorc                 C     h | ]}t |r|qS r7   rE  rv   methodr7   r7   rL   	<setcomp>[	  s    r  c                 C  r  r7   r  r  r7   r7   rL   r  b	      c                 C  r  r7   r  r  r7   r7   rL   r  c	  r  c                 C  r  r7   r  r  r7   r7   rL   r  f	  r  c                 C  s   t | tsJ t| S r\   )r  r  r  rj  r7   r7   rL   builtin_dict_keysi	  s   
r  c                   s^   t  tsJ t ttfr  S t  tr# fddt D S  fddt D S )Nc                      g | ]
}|t  |fqS r7   )r   rr  r  r8  r7   rL   r	  u	      z'get_items_from_dict.<locals>.<listcomp>c                   r  r7   )r  rr  r  r8  r7   rL   r	  w	  r  )r  r  r  r   r   r  r8  r7   r8  rL   get_items_from_dicto	  s   
r  c                 C  s   t | }tjj| |S r\   )
object_newr   r  Moduler  )rV   r}  r7   r7   rL   nn_module_newz	  s   r  c                 C  s   t tj| dS r   )r  reduceoperatormul)itr7   r7   rL   product	     r  c                 C  s   |   \}\}}|||  S r\   )
__reduce__)r  rN  rI  r}  rK  r7   r7   rL   tuple_iterator_getitem	  s   r  tuple[int, int, int]c                 C  s4   |   \}\}}|j|pd }|j}|j}|||fS r   )r  rK  rL  rM  )
range_iterrI  	range_obj	maybe_idxrK  rL  rM  r7   r7   rL   normalize_range_iter	  s
   
r  c                 C  
   |  |S r\   )as_subclass)r@  rV   r7   r7   rL   to_subclass	  r  r  c                 C  s.   t }t| tr	t}tt|| ||d S r   )r  r  r   nextr|   islicer  )rW  rb  
dict_classr7   r7   rL   dict_keys_getitem	  s   
r  c                 C  s2   | j j}| j}|rdnd}| d| d| }|S )NLGz["z"].)rs  rF   rU   )r   r  rU   r  r  
local_namer7   r7   rL   	enum_repr	  s
   r  c                 C  s>   || j d< t jj}tjjj	|| }r|| j d< d S d S )Nexample_valueunbacked_bindings)
metar   r_   	fake_mode	shape_envr   r   experimentalsymbolic_shapescompute_unbacked_bindings)r  r  r  symbol_to_pathr7   r7   rL   set_example_value	  s   

r  c                 C  sP   |   jjd}t|s&ddlm} ddlm} |dt	|dg |j
d |S )Nr  r4   graph_break_hintsr  z:Cannot check Tensor object identity without its fake valuez/TensorVariable is missing a fake example_value.r  r  r  r  )r  r  r  r_   r9   r  r  rM  r  rp   
DYNAMO_BUG)vtfake_tensorr  r  r7   r7   rL   _get_fake_tensor	  s   r  c                   s   ddl m}m}m}m}   r t fdd| D }||S d}	|r/t |r/d}	t	  d }
| D ]6}|	rJt||rI t	|u rI|d  S q3|t
j|| gi }|
d u r]|}
q3|t
j|||
gi }
q3|
d u rs|d}
|
S )Nr4   )BuiltinVariabler  TensorVariableVariableTrackerc                 3  s(    | ]}|  o|   kV  qd S r\   )r  r  rl  searchr7   rL   rx   	  s    
z iter_contains.<locals>.<genexpr>FT)r  r  r  r  r  r  rG  rO  r  r  r  eqcall_functionor_)r   r  txcheck_tensor_identityr  r  r  r  found_constmust_check_tensor_idfoundr   checkr7   r  rL   iter_contains	  s4   




r  c                 C  s   t | tjtjjtfS )z4Returns whether it indexes dictionaries using its id)r  r   r  r  r  r   )r  r7   r7   rL   	key_is_id	  r  r  c                 C  s   dd |   D S )Nc                 S  s    g | ]}t |rt|n|qS r7   )r  rq  r  r7   r7   rL   r	  	  s     zkey_to_id.<locals>.<listcomp>)r  r  r7   r7   rL   	key_to_id	  ru  r  c                  s   ddl m} t| ttfr=d fdd| D }t| tr$d| dS t| ts+J t| dkr7d| d	S d| d
S t| tjrMt	|  d
ddS || rT| jS t| tradd }|| S | S )Nr4   )is_builtin_callablerE  c                 3      | ]	}t | d V  qdS r  N
const_reprrv   r  r  r7   rL   rx   
  rA  zconst_repr.<locals>.<genexpr>[](z,)rq  r  'r  c                 S  s(   | j }|j}|dkr|jS |d |j S )Nbuiltins.)rs  rG   rH   )rq  klassrH  r7   r7   rL   fullname
  s
   zconst_repr.<locals>.fullname)trace_rulesr  r  r  r  rt   r  r|  r}  r  replacerF   rK  )r   r  r  
elems_reprr  r7   r  rL   r  
  s"   

r  c                  s$   d  fdd| D }d| d S )NrE  c                 3  r  r  r  r  r  r7   rL   rx   $
  rA  z!dict_keys_repr.<locals>.<genexpr>r  r   rt   )
const_keysr  keys_strr7   r  rL   dict_keys_repr#
  s   r  
__dict_key)UnsupportedFakeTensorExceptionc                 C  s   | dt | d| jj S )NrI  _c)rq  outputr   )r  rootr}  r7   r7   rL   get_safe_global_name.
  s   r  rA  r	   c                 G  s   |D ]	}| |v r dS qdS re  r7   )rA  
containers	containerr7   r7   rL   is_in8
  s
   r  )requires_suffixprefixc                G  sT   |st | g|R  s| S t D ]}|  d| }t |g|R  s%|  S qtd)zm
    Return a name that starts with `prefix` and is not in any of the
    `containers` (e.g., map, set).
    rI  unreachable)r  r|   rX   AssertionError)r  r  r  r  	candidater7   r7   rL   get_unique_name_wrt?
  s   r  c              
   C  sl   z|  W S  t y5 } z%ddlm} d|j d}t| |dt|j|g |d W Y d }~d S d }~ww )Nr4   r  zEncountered exception (z!) during fake tensor propagation.z!Fake tensor propagation exceptionr  )r  rM  r  reasonrf   rS  rp   )r  r  r  msgr7   r7   rL   wrap_fake_exceptionO
  s   
r  c                   sB   t jj| t fddW  d    S 1 sw   Y  d S )Nc                     s
   t  S r\   )r  deepcopyr7   r8  r7   rL   r   b
  r9  z)deepcopy_to_fake_tensor.<locals>.<lambda>)r   r  r  FakeCopyModer  )r}  r  r7   r8  rL   deepcopy_to_fake_tensor`
  s   $r"  c                 C  s   t t t | | S )z+
    Calculate root mean squared error
    )r   sqrtmeansquare)rx  r  r7   r7   rL   rmsee
  s   r&  g-C6?Tforce_max_multiplierc                   s:  du rt tttjtjjtjfrXt 	tttjfs+J dt	 dt		 t
t
	kr9d dS t
t
	koWt f	ddt	D S t	jdkrrtj	jj d	S t trt 	ts~J t t	 ksJ d
t  dt	  t D ] }t| 	| |  dsd|  dS qdS t trt 	tsJ tt	ksJ dt dt	 dS t tjtfrmt tjjrJ t 	tjjrJ dd 

fdd	fD \	jr*	js"J  	 	t 	tjs?J dt	 dt		 r|j	jkrSdj	j dS jtjkr|r_dS tjjtjd	jtjdd}|szd |S  r tj 	 tj 	tj	ddrdS tjj!j"	ddd}|dk rt#$d|% & '  |dkS sň	jtj	drdS jtj(krad}) * s	) * s) * rtjj	jd	||drdS t+' }t,)|rt#$d t+	' }	fdd}| }||| d   k}|sNrNt,)|rNt,)|rNtj-j.j/j0sNd}|s_d!||	1 	j| |S rfdS d" dS t t2t3t	dttj4frrdS 	k}|sd#t		 |S t5st6rňrt5	st6	s' t	t		u o	k}|sÈd$	 |S t7rt	t		u ott8t8	 d%S t	jd&v rt	t		u sJ t 	fd'dj9 D S t:d(t	j ))z-Check correctness to see if ref and res matchNztype mismatch r   zLength mismatchFc                 3  s6    | ]\}}}t ||| d V  qdS )	log_error(use_larger_multiplier_for_smaller_tensorr'  N)same)rv   aibi	fp64_refi)	cos_similarity	equal_nanexact_dtyper'  ignore_non_fpr)  relax_numpy_equalitytolr*  r7   rL   rx   
  s$    
zsame.<locals>.<genexpr>QuestionAnsweringModelOutputr(  zkeys mismatch z == )	r/  r4  r0  r1  r3  r2  r)  r*  r'  zAccuracy failed for key name %sTzelements mismatch c                 S  s   t | tjr| S t| S r\   )r  r   r  tensorr@  r7   r7   rL   	to_tensor
  s   zsame.<locals>.to_tensorc                 3  rF  r\   r7   )rv   r  )r8  r7   rL   rx   
  r  zdtype mismatch %s, %sr  )atolrtolr0  z+Accuracy failed: uint8 tensor did not matchr   gư>)dimepsgGz?zSimilarity score=%sg{Gz?z=Found nan in reference. Consider running in higher precision.c                    s    rdS j tjtjfv rdnd} r dkrd} | S r) dkr)d} | S  dk sIjdkrEjd	 jd
   krDdksIn dkrKd} | S )N      $@g      @g       @
   i  g      @r      r  r4   g{Gz?)r  r   r  bfloat16numelndimr  )
multiplier)r'  fp64_refrx  r  r4  r*  r7   rL   get_multiplier  s"   ,zsame.<locals>.get_multiplierr=  zRMSE (res-fp64): %.5f, (ref-fp64): %.5f and shape=%s. res.dtype: %s, multiplier: %f, tol: %f, use_larger_multiplier_for_smaller_tensor: %dz+Accuracy failed: allclose not within tol=%szAccuracy failed (%s): %s != %sz!Accuracy failed (numpy): %s != %sr/  r4  r0  r1  r3  r2  r)  r*  )MaskedLMOutputSeq2SeqLMOutput!CausalLMOutputWithCrossAttentionsLongformerMaskedLMOutput	InstancesSquashedNormalBoxesNormalTanhTransformFooVariablec                 3  s@    | ]}t t|t|t| 	
d V  qdS )rG  N)r+  rD  rv   r   )r/  r0  r1  rE  r2  r)  rx  r3  r  r4  r*  r7   rL   rx     s"    
zunsupported type: );r  r  r  rg   r  r   r  ParameterListr~  rK  r  rm  r  rF   r+  lossr  r  r  rH  r  floatr  r8   	is_sparseto_denser  r   allclosetor  flattenr  
functionalcosine_similarityrf   rS  detachcpurA  r  isnanrG  r&  mathrx  r5   cppinject_relu_bug_TESTING_ONLYr  rp   rR   r  r  r  r  	as_tensor__dict__r   )rx  r  rE  r/  r4  r0  r1  r3  r2  r)  r*  r'  r  rscore	loose_tol	ref_error	res_errorrF  rD  passes_testr7   )r/  r0  r1  r'  rE  r2  r)  rx  r3  r  r8  r4  r*  rL   r+  l
  sz  ,



,*



#
	

 r+  c                 C  s,   | j dd }d| j d| d| j dS )N/r  r  z' (r   rq  )r  splitrJ  rL  )rN  short_filenamer7   r7   rL   format_func_info  s   ro  c                  c  sF    t j} tjt _t j}tjt _zd V  W | t _|t _d S | t _|t _w r\   )r5   recompile_limitr  r  accumulated_recompile_limit)priorprior_acc_limitr7   r7   rL   disable_cache_limit  s   
rt  z'collections.defaultdict[Any, list[Any]]guard_failuresz3list[torch._dynamo.output_graph.GraphCompileReason]graph_break_reasonsc                 C  s2   dt j  d d tt  }tj| |S )Nrun_z%Y_%m_%d_%H_%M_%S_%fz-pid_)datetimenowstrftimerp   r&  getpidr:  rt   )root_dirdir_namer7   r7   rL   _get_debug_dir  s   
r~  c                  C  s   t j} t| S r\   )r5   r\  r~  )
debug_rootr7   r7   rL   r;    s   r;  c                 C  sh   d| j v rt| j d r| j d S |r2ddlm} ddlm} |dt| d|  dg |jd	 d S d S )
Nr  r   r  r4   r  z Missing FakeTensor example valuez,`FakeTensor` example value was required for z but not available.r  )r  r9   torch._dynamo.excr  r  r  rp   r  )r  requiredr  r  r7   r7   rL   extract_fake_example_value  s   


r  c                 C  s   t | |ju s	J | S r\   )r:   r  )r  r  r7   r7   rL   ensure_graph_fake  s   r  c                   s    d fdd}t jj||S )Nrb  torch.fx.Nodec                   s   | j dkrd| jvrt|  S | j dkr5d| jvr5| jjjv s#J jj| j }t|tjj	s3J |S | jd } sGt|tj
rGt|S |S )Nr  r  get_attr)r`  r  get_fake_valuetargetr  
nn_modulesr  r   r   GraphModuler  r  )rb  r`  r   allow_non_graph_faker  r7   rL   visit  s   

z)get_fake_values_from_nodes.<locals>.visit)rb  r  )r   r   r  map_arg)r  r_  r  r  r7   r  rL   get_fake_values_from_nodes  s   r  c              
     s  ddl m} ddlm}m}m}m}m} j}	dj	v r(t
j	d r(j	d S tjjf|\ d|	dkrZt dkrZt d tjjrZt d jft dd   |	dkrzjjj trttd	rt  tjjd
v stdd  D rtdd  D  z5j' t  t fdd}
W d   n1 sw   Y  W d   n1 sw   Y  W n |y     t y } z|}|j!dur|j!}t|tj"j#j$r|j%tj&j'j(j)tj&j'j*j)fv rdg}ndg}|dt+|j%d|j% d|d nt|tj"j#j,rCtj-j.j/s1|dt+|j%d|j% ddgd n|dt+|j%d|j% ddgd nt|tj"j#j0r|j%}	d}t|	tj1j2rytj34|	j5j|	j5j6}|dury|\}}d| d| d| d }|d!d"|j% d| d#gd n@t|tj7j8j9j:r||j;t+|d$d%t||r||j;|jd |t|t<rd&t+|v r|d'd(j d)| dg d |t+|=|j>dd}~ww |st?@tjAtBjCtDd*|
}|
S )+az  
    Run the computation represented by `node` using fake tensors and return the result.

    allow_non_graph_fake: whether to allow the return result to be:
        1. non-fake or 2. fake that is not created by this instance of Dynamo.
        If `True`, you must be prepared to deal with such return values, ideally
        by further wrapping them as this graph's fakes.
    r   )ValueRangeErrorr4   )TorchRuntimeErrorr  Unsupported	UserErrorUserErrorTyper  Ncall_methodcall_module_initialize_hook)interpolate
is_integerwrapped_gradientc                 s  s    | ]}t |tV  qd S r\   )r  complex)rv   ar7   r7   rL   rx   *  s    

z!get_fake_value.<locals>.<genexpr>c                 s  s4    | ]}t |tjr|jjd urt|n|V  qd S r\   )r  r   SymFloatr  hintrV  r  r7   r7   rL   rx   .  s    

c                     s   t j S r\   )run_noder  r7   rk  rl  nnmoduler  r  r7   rL   r   8  s    z get_fake_value.<locals>.<lambda>zkEnable tracing of data-dependent output operators with `torch._dynamo.config.capture_scalar_outputs = True`zConsider wrapping the operator into a PyTorch-understood custom operator (see https://pytorch.org/tutorials/advanced/custom_ops_landing_page.html)zData dependent operatorz
Operator `zP` has a non-Tensor output whose value is dependent on the data of Tensor inputs.r  zDynamic shape operatorz.`'s output shape depends on input Tensor data.zmEnable tracing of dynamic shape operators with `torch._dynamo.config.capture_dynamic_output_shape_ops = True`z'Dynamic shape operator (no meta kernel)zA` does not have a meta kernel that supports dynamic output shapesz!Please report an issue to PyTorchr  z:It's possible that the support was implemented in module `z` and you may need to `import z`(z), otherwise z3Operator does not support running with fake tensorszunsupported operator: z}see https://docs.google.com/document/d/1GgvOe7C8_NVOMLOCwDaYV1mXXyHMXY7ExoewHqooxrs/edit#heading=h.64r4npvq0w0 for how to fixconstrain_as_size_example)	case_nameargumentz&TypeError when making fake tensor callz
TypeError z: )r  )Etorch.utils._sympy.value_rangesr  rM  r  r  r  r  r  r`  r  r9   r  rk  rl  r  r  r   r  r  r"  r  r  r  r  r  r  r  _infer_parametersrU   rG  r   r  r   	__cause__r  r  DataDependentOutputExceptionfuncopsatenrA  rt  _local_scalar_denserp   DynamicOutputShapeException_dynamor5    capture_dynamic_output_shape_opsUnsupportedOperatorExceptionr  r  r  _dispatch_pystub_schemaoverload_namer   r  r  GuardOnDataDependentSymNodeCONSTRAINT_VIOLATIONrg  with_traceback__traceback__pytreetree_map_onlyr  r  partialr  )r  r  r  r  r  r  r  r  r  r`  ret_valr  causer  import_suggestionmaybe_pystubrH  ctxrI  r7   r  rL   r    s   	
&" 









cr  c                   C  s   t tdd S )Nr   )rD  _current_noder7   r7   r7   rL   get_current_node  r  r  c                 c  s*    t  }| t_z	d V  W |t_d S |t_w r\   )r  r  r   )r  oldr7   r7   rL   set_current_node  s   r  c           
        s*  j t   fdd}ddlm} zdkr-j i W W  d   S dkrbt d jsIdd	lm} |d
d|dg d t d j dd i W W  d   S dkr{|duslJ | i W W  d   S dkr| j	jW W  d   S dkrdj
v sJ j
d W W  d   S W nL ttfy } z!dd	lm} g }	t|trdg}	|dd|||	|d W Y d}~n,d}~w |y     ty } zt|||j|d}~ww W d   tW d   t1 sw   Y  t)a  
    Runs a given node, with the given args and kwargs.

    Behavior is dictated by a node's op.

    run_node is useful for extracting real values out of nodes.
    See get_real_value for more info on common usage.

    Note: The tracer arg is only used for 'get_attr' ops
    Note: The nnmodule arg is only used for 'call_module' ops

    Nodes that are not call_function, call_method, call_module, or get_attr will
    raise an AssertionError.
    c              	     s(   d dj  d  d d	t|  S )Nz0Dynamo failed to run FX node with fake tensors: r   z(*z, **z): got )r  r   )r  rk  rl  r  r`  r7   rL   make_error_message  s   z$run_node.<locals>.make_error_messager4   )r  r  Nr  r   r  z/Missing attribute when running call_method noder  zattribute not definedr  r  r  placeholderr  z;If the op is a PyTorch op, please file an issue to PyTorch.zGNotImplementedError/UnsupportedFakeTensorException when running FX noder  )r`  r  rM  r  r  r  r  rD  output_graphget_submoduler  r  r  r  rW  r   r  r  r  )
tracerr  rk  rl  r  r  r  r  r  r  r7   r  rL   r    s~   "


9
99r  c           
   
     s   ddl m}  j}| |v r||  S | j}tjj| j| j	f fdd\}}|dkr5d| j
v r5| j
d jS |dkrR jj| j }t|sJt|}n
||i | nd}zt | |||}||| < W |S  tyz }	 z|t|	|	jdd}	~	ww )	z
    Run the actual computation represented by `node` and return the result.
    This will execute any dependent nodes in the graph as well.
    r4   )r  c                   s
   t |  S r\   )get_real_value)rb  r  r7   rL   r     r9  z get_real_value.<locals>.<lambda>r  graphargr  N)rM  r  real_value_cacher`  r   r   r  r  rk  rl  r  exampler  r  r  r  r  r   r  r   rp   r  r  )
r  r  r  cacher`  rk  rl  	nn_module
real_valuer  r7   r  rL   r    s2   


r  c                   s   ddl m m}  fdd}|  D ]\}}||r&J d| d|| q|  D ]\}}||r?J d| d|| q+d S )Nr   )FakeTensorConfigr9   c                   s$    j rdd l}d|| j S dS )Nr   z"FAKE TENSOR CREATION TRACEBACK: 
 zNEnable TORCH_FAKE_TENSOR_DEBUG=1 to get creation stack traces on fake tensors.)debug	tracebackformat_list_debug_trace)r@  r  r  r7   rL   stack_or_hint.  s   z7assert_no_fake_params_or_buffers.<locals>.stack_or_hintzUnexpected fake buffer r   zUnexpected fake param )torch._subclasses.fake_tensorr  r9   named_buffersnamed_parameters)r`  r9   r  rU   bufferrX  r7   r  rL    assert_no_fake_params_or_buffers+  s   

r  c                 C  s   | j  d| j S )z9
    Returns the fully qualified name of the object.
    r  )rG   rH   r8  r7   r7   rL   fqn@  s   r  c                 C  s   t jjjr| S |S r\   )r   r  r5   assume_static_by_default)count1count2r7   r7   rL   ifdynstaticdefaultG  s   
r  r  types.ModuleTypec                 C  s\   t ttjtt| jD ]}|dr+|d dkr+t	
| j d|dd   qdS )z@
    Ensure all the files in a given submodule are imported
    z.pyr   rI  r  N)rH  r&  listdirr:  rT  r   rp   __file__r   	importlibimport_modulerF   )r  rP  r7   r7   rL   import_submoduleN  s
   "r  r   c                 C  r9  r\   )class_has_getattributerK  r  r7   r7   rL   object_has_getattributeW  r  r  rV   rK  c                 C  s6   zt t| dtjrW dS W dS  ty   Y dS w )N__getattribute__TF)r  r  r  r  r  AttributeErrorr^   r7   r7   rL   r  [  s   
r  ignore_nn_module_getattrc                 C  sF   z
t t| d}W n ty   d }Y nw |r!|tjjju r!d }|S )N__getattr__)r  r  rK  r  r   r  r  r  )r   r  
getattr_fnr7   r7   rL   get_custom_getattrg  s   r  c                   @  rB   )TensorStaticReasonrD   r?  r   N)rF   rG   rH   	PARAMETER
NOT_TENSORNN_MODULE_PROPERTYr7   r7   r7   rL   r  r  rM   r  r  c                 C  s8   | t jkrdS | t jkrdS | t jkrdS td|  )Nz>mark_dynamic on parameter, parameters are always static today.z2mark_dynamic on a non tensor, how did this happen?z4tensor is static because it is nn module associated.zIllegal reason )r  r  r  r  r  )r  r7   r7   rL   tensor_static_reason_to_messagex  s   


r  r6  Union[torch.Tensor, Any]	is_tensortensor_sourcer   )tuple[bool, Optional[TensorStaticReason]]c                 C  sn   ddl m} |  s|  rtjrdtjfS t	| t
jju s&||r.tjr.dtjfS |s5dtjfS dS )a@  
    Given a tensor, source, and is_tensor flag, determine if a shape should be static.

    Args:
    tensor - the real tensor to evaluate, parameters force a static shape.
    is_tensor - internal dynamo check, essentially "is_tensor": target_cls is TensorVariable,
    tensors not in a TensorVariable for whatever reason are forced static.

    Returns a tuple, where the first element is the bool of whether or not this tensor should have a static shape.
    The second element is a TensorStaticReason, useful for passing to tensor_static_reason_to_message if needed.
    r4   ))is_from_unspecialized_param_buffer_sourceTr  )r  r  r  r  r  r5   &force_nn_module_property_static_shapesr  r  rK  r   r  r  force_parameter_static_shapesr  r  )r6  r  r  r  r7   r7   rL   tensor_always_has_static_shape  s"   




r  c                   s    fdd}t |S )Nc                    sj   zddl m }  W n ty   dtt   Y S w dd jjD }| |g dd}t jjj	|S )Nr   )rz   zkTabulate module missing, please install tabulate to log the graph in tabular format, logging code instead:
c                 S  s$   g | ]}|j |j|j|j|jgqS r7   )r`  rU   r  rk  rl  )rv   rb  r7   r7   rL   r	    s    z<lazy_format_graph_tabular.<locals>.inner.<locals>.<listcomp>)opcoderU   r  rk  rl  rq   )
rz   r{   rp   r&   graphr_  r%   forward__code__r  )rz   
node_specs	graph_strr   r`  r7   rL   inner  s   z(lazy_format_graph_tabular.<locals>.innerr2   )r   r`  r  r7   r  rL   lazy_format_graph_tabular  s   r  c                 C  s,   |  d| d| d| dt |   d
S )Nr   z line z 
rr   )disBytecode)r  rU   rP  line_norN  r7   r7   rL   format_bytecode  s   ,r
  _forward_pre_hooks_forward_hooks_backward_pre_hooks_backward_hooks)_state_dict_pre_hooks_state_dict_hooks_load_state_dict_pre_hooks_load_state_dict_post_hooksc                   C  s    t tjjjjpt tjjjjS r\   )r  r   r  modulesrH  _global_backward_hooks_global_backward_pre_hooksr7   r7   r7   rL   nn_module_has_global_hooks  s   
r  c                 C  s   g }| o
| o
| }|s|r| t |s|r| t |r$| t g }|D ]}t| |g }|D ]}	||	 }
||
 q2q(|S )z
    Sometimes its useful to differentiate between types of hooks such as forward/backward/pre
    hooks executed during module.__call__, and state_dict hooks which are executed separately.
    )extendforward_hook_namesbackward_hook_namesstate_dict_hook_namesrD  r   )r  check_forward_hookscheck_backward_hookscheck_state_dict_hookshook_dicts_to_checkcheck_all_hooks	all_hookshook_dict_namehooks	hook_namer  r7   r7   rL   nn_module_get_all_hooks  s(   



r$  c                 C  s   t | |||d}t|S )zL
    Helper function to check if a module has any hooks attached to it.
    )r  r  r  )r$  r   )r  r  r  r  r"  r7   r7   rL   nnmodule_has_hooks  s   	r%  c                 C  sb   t | r| S t| tjrt| jS t| tjr| jddS t| t	t
fr/t| dd | D S | S )z0Convert tensor and tnp.ndarray to numpy.ndarray.T)forcec                 s      | ]}t |V  qd S r\   )to_numpy_helperrv   r}  r7   r7   rL   rx     r  z"to_numpy_helper.<locals>.<genexpr>)r9   r  tnpr  r(  r6  r   r  numpyr  r  rK  r  r7   r7   rL   r(    s   
r(  c                 C  s\   t dusJ t| t jrt| S t| tjr| jS t| ttfr,t	| dd | D S | S )zeConvert tnp.ndarray to tensor, leave other types intact. If a list/tuple, loop through it to convert.Nc                 s  r'  r\   )numpy_to_tensorr)  r7   r7   rL   rx     r  z"numpy_to_tensor.<locals>.<genexpr>)
r  r  r  r   rd  r*  r6  r  r  rK  r  r7   r7   rL   r,    s   
r,  c                   @  s&   e Zd Zdd Zd
ddZdd Zd	S )numpy_to_tensor_wrapperc                 C  s   || _ d| j j | _d S Nwrapped_rZ  rF   )r  rZ  r7   r7   rL   r       z numpy_to_tensor_wrapper.__init__ro   rp   c                 C  s   d| j j dS )Nz<Wrapped function <original >>r0  r  r7   r7   rL   __repr__#  r  z numpy_to_tensor_wrapper.__repr__c                 O  s   | j |i |}t|S r\   )rZ  r,  r  rk  rl  r   r7   r7   rL   r  &  s   z numpy_to_tensor_wrapper.__call__Nro   rp   )rF   rG   rH   r  r3  r  r7   r7   r7   rL   r-    s    
r-  c                 C  sF   t | tjrt| |}t|S t | tjr!tt| |}t|S d S r\   )r  r*  r  rD  r,  r   r  )r}  rU   r   r7   r7   rL   numpy_attr_wrapper+  s   
r6  c                   @  s,   e Zd ZdZdddZdddZd	d
 ZdS )numpy_method_wrapperzgConvert obj from torch.Tensor to tnp.ndarray and call method. Then convert result back to torch.Tensor.r  rp   c                 C  s   || _ d| j  | _d S r.  )r  rF   )r  r  r7   r7   rL   r  7  s   znumpy_method_wrapper.__init__ro   c                 C     d| j  dS )Nz<Wrapped method <original r2  )r  r  r7   r7   rL   r3  ;  rs  znumpy_method_wrapper.__repr__c                 O  sH   |d }t |tjrt|}t|| j}||dd  i |}t|S r  )r  r   r  r*  r  rD  r  r,  )r  rk  rl  r}  method_callabler   r7   r7   rL   r  >  s   
znumpy_method_wrapper.__call__N)r  rp   r5  rF   rG   rH   r   r  r3  r  r7   r7   r7   rL   r7  4  
    

r7  c                   @  s,   e Zd ZdZdddZddd	Zd
d ZdS )numpy_operator_wrapperzQImplements dunder methods for tnp.ndarray via functions from the operator libraryr`  Callable[..., Any]c                 C  s   || _ d|j | _d S r.  )r`  rF   )r  r`  r7   r7   rL   r  J  r1  znumpy_operator_wrapper.__init__ro   rp   c                 C  r8  )Nz<Wrapped operator <original r2  )rF   r  r7   r7   rL   r3  N  rs  znumpy_operator_wrapper.__repr__c                 O  s(   |rJ dd |D }| j | }t|S )Nc                 s  s*    | ]}t |tjrt|n|V  qd S r\   )r  r   r  r*  r  r  r7   r7   rL   rx   T  s    
z2numpy_operator_wrapper.__call__.<locals>.<genexpr>)r`  r,  r4  r7   r7   rL   r  Q  s   
znumpy_operator_wrapper.__call__N)r`  r=  r5  r:  r7   r7   r7   rL   r<  G  r;  r<  c                 C  s   t | ts| S | jrMg }|  D ]}t |tjr%||jj	|jj
 q|| qg }|  D ]}t |tjrF||jj	|jj
 q1|| q1n|  }|  }tj||| j| j| jd}|  |S )N)r  r  r  )r  r8   _has_symbolic_sizes_stridesr  r   r  r   r  r  	size_hintexprr  empty_stridedr  r  r  zero_)r   r  r  r  r  r7   r7   rL   defake[  s2   
rC  c                 C  s   dd l }| |jjju S r   )torch.utils.checkpointr  
checkpoint)r}  r   r7   r7   rL   is_utils_checkpoint{  s   rF  c                 C  s   ddl m} | |u S )Nr   )invoke_subgraph_placeholder)'torch._higher_order_ops.invoke_subgraphrG  )r}  rG  r7   r7   rL   is_invoke_subgraph  s   rI  c                  K  s"   ddl m} |jtjjfi | S )Nr4    TorchHigherOrderOperatorVariable)variables.higher_order_opsrK  maker   _higher_order_opsinvoke_subgraph)optionsrK  r7   r7   rL   build_invoke_subgraph_variable  s   rQ  c                  K  sF   dd l m  m} ddlm} |j}tjjj	r|j
}|j|fi | S )Nr   r4   rJ  )torch._higher_order_ops.wraprN  wraprL  rK  tag_activation_checkpointr   
_functorchr5   functionalize_rng_opswrap_activation_checkpointrM  )rP  higher_order_opsrK  activation_checkpoint_opr7   r7   rL   build_checkpoint_variable  s   
rZ  c                 C  s>   ddl m} | }| dkr	 |S | dv r|rt }|S d}|S )Nr4   )is_dynamo_supportedr_  )r  xpuF)
eval_framer[  r)   )device_typer[  compile_supportedr7   r7   rL   is_compile_supported  s   r`  offsetc                 C  s$   |  d}t|d| jdddS )z
    Convert byte offset `offset` of `str` into character offset.
    Byte offset is used for 3.11+ instruction column data.
    Takes things like unicode characters into consideration.

    Unchanged from CPython implementation.
    zutf-8Nr  )errors)encoder  decode)rp   ra  as_utf8r7   r7   rL   _fix_offset  s   
rf  c                   @  s.   e Zd ZU ded< ded< ded< ded< dS )_AnchorsrR   left_end_linenoleft_end_offsetright_start_linenoright_start_offsetNrO  r7   r7   r7   rL   rg    s
   
 rg  segmentOptional[_Anchors]c                   s  t jdksJ ddl}z|d|  d }W n
 ty    Y dS w t|jdkr*dS | d  fdd	} fd
d fdd} fdd}|jd }t||j	r_|j
}t||jrtt|jjd }|||jj}	||	\}}	 | |	  }
 s|
dv r|
dv r|||	\}}	n|||	\}}	 | |	  }
 s|
dv s|	d }|t | k r | |  }
 s|
dvr|d7 }t||	||S t||jrtt|j
jd }|||j
j}||\}} | | dkr|||\}} | | dkstt|jd }|||j}t||||S t||jr_tt|jjd }|||jj}||\}} | | dkrJ|||\}} | | dks:tt|jd }|||j}t||||S dS )a  
    Given source code `segment` corresponding to a bytecode
    instruction, determine:
        - for binary ops, the location of the binary op
        - for indexing, the location of the brackets.
    `segment` is expected to be a valid Python expression
    )rE      r   Nz(
z
)r4   rr   c                   s   t  |  |S r\   )rf  )linenora  linesr7   rL   	normalize  rs  z-_extract_anchors_from_expr.<locals>.normalizec                   sl   | t  k r"|t  |  kr"d}| d7 } | t  k r"|t  |  ks| t  k r0|t  |  k s2J | |fS r  r  ro  colrp  r7   rL   next_valid_char  s    z3_extract_anchors_from_expr.<locals>.next_valid_charc                   s>   |d7 }| |\} }| t  k r|t  |  k sJ | |fS r   rs  rt  rq  rv  r7   rL   r     s    z-_extract_anchors_from_expr.<locals>.incrementc                   sB   d}| d7 } | |\} }| t  k r|t  |  k sJ | |fS r  rs  rt  rw  r7   rL   nextline  s
    z,_extract_anchors_from_expr.<locals>.nextlinerD   z)\#z\#r  r  )r  r  astparseSyntaxErrorr  bodyrm  r  Exprr   BinOpr   rR   left
end_linenoend_col_offsetisspacerg  	SubscriptCallr  )rl  ry  treerr  r   rx  	statementr@  
cur_linenocur_colch	right_colleft_linenoleft_colright_linenor7   rw  rL   _extract_anchors_from_expr  sl   

r  rN  types.CodeTypeinstdis.Instructionc                   s  t jdkrhtj j|jj j|jj|jj	|jj
d}t|gd }d| dd } fddt|jj|jjd D }td| }t|d t|d  }|d d| }tt||}|S |jdusoJ |jjdu rwd	S t j|jj }|jjdu r|S |jj	du s|jj
du r|S t||jj	}	d}
d	}g }|jj|jjkrt||jj
}
||	|
 }|d
|	 d|
|	    n~||	d d }|d
|	 dt||	    t j|jj }t||jj
}
t|jjd |jjD ]*}t j| }||d 7 }t|t|  }|d
| dt||    q||d|
 7 }t|t|  }|d
| d|
|    d}zt|}W n
 tyX   Y nw |du rfdd |D }nydd |D }|jdkrz| j|	7  _|jdkr| j|	7  _tt|D ]J}tt|| D ]>}||jk rq||jkr||jk rq||jkr||jkrq||jkrŐq|| | dkrd|| |< qqdd |D }d	}tt|D ]}|t j|jj|  d 7 }||| d 7 }q|S )a  
    Python 3.11+ only. Returns lines of source code (from code object `code`)
    corresponding to `inst`'s location data, and underlines relevant code to `inst`.

    Example: CALL on `g`:
    f(g(
      ^^
        h(x)))
        ^^^^^

    We need our own implementation in < 3.13 since `format_frame_summary` in
    Python's `traceback` module doesn't handle multi-line expressions
    (and their anchor extraction code is not completely correct).
    )rE      )r  colno	end_colnor   rr   r4   Nc                   s   g | ]}t  j| qS r7   )	linecachegetliner  rstrip)rv   ro  rN  r7   rL   r	  a  rY  z.get_instruction_source_311.<locals>.<listcomp>r  r   ~c                 S  s   g | ]}| d dqS )r  ^)r  rv   markerr7   r7   rL   r	    r  c                 S     g | ]}t |qS r7   r  r  r7   r7   rL   r	    s    r  c                 S  s   g | ]}d  |qS )r  r
  r  r7   r7   rL   r	    rp  )r  r  r  FrameSummaryr  	positionsro  rJ  r  
col_offsetr  r  rt   
splitlinesr  textwrapdedentr  indentr  r  r  rf  r   lstripr  r  rh  ri  rj  rk  )rN  r  frame_summaryr  
orig_linesorig_lines_dedent
indent_lenr  
first_linestart_offset
end_offsetrl  markers	last_linero  line
num_spacesanchorsmutable_markersru  r  r7   r  rL   get_instruction_source_311D  s   


 
r  c                 C  s   t | tjrt| dd S d S )N_dynamo_static_input_type)r  r   r  rD  r7  r7   r7   rL   get_static_address_type  s   r  c                 C  sJ   t jjjt jjt jt jjf}t jjjt jjt jt jjf}| g ||R v S r\   )	r   r  r,   	get_statedefault_generatorr   r  	set_stater"  )r   getterssettersr7   r7   rL   is_rng_state_getter_or_setter  s   r  c                 C  s&   t | tjo| jdko| jjtjju S )N__get__)	r  r  r   rF   __self____objclass__r   r  _TensorBaser  r7   r7   rL   is_tensor_base_attr_getter  s
   r  c                 C  s
   t | dS )N__torch_function__)r  r  r7   r7   rL   is_torch_function_object  r  r  r  ,torch._dynamo.variables.base.VariableTrackerc                 C  s`   ddl m} ddlm} |  st| dr.t|  dr.t| |r#dS t| |o-t| jdS dS )Nr   )UserDefinedObjectVariable)TensorWithTFOverrideVariable
peek_valuer  TF)	torch._dynamo.variablesr  &torch._dynamo.variables.torch_functionr  r  r  r  r  r   )r  r  r  r7   r7   rL   has_torch_function  s   

r  c                 C  sD   d }d }t jj  }r| |jv r|j|  }|j}|j| d||dS )NF)static_shapessymbolic_contextr  )r   r  r   try_gettensor_to_contextr  from_tensor)r@  r  r  r  tracing_contextr7   r7   rL   to_fake_tensor  s   

r  c                 C  s:   t |  ot|  ot| ot| dot| jdo| jjS )N__dataclass_params__frozen)r  r  r   r  r  r  r  r7   r7   rL   is_frozen_dataclass  s   

r  c                 G  s4   |D ]}t | |rt| |  S qt|  d| )zX
    Return the first available attribute or throw an exception if none is present.
    z% does not has any of the attributes: )r  rD  r  )r}  attrsattrr7   r7   rL   get_first_attr  s
   
r  c                 #  sX    | sd V  d S  fdd}t jj|}|V  W d    d S 1 s%w   Y  d S )Nc                   s   dd }t j| | dS )Nc                 S  s(   t jjjd d  d7  < t j| |S )Ncompiled_autogradcompilesr4   )r   r  r  r<   rx  compile)gm_example_inputs_r7   r7   rL   inner_compiler1  s   zKmaybe_enable_compiled_autograd.<locals>.compiler_fn.<locals>.inner_compiler)backend	fullgraphdynamic)r   r  )r`  r  r  r  r7   rL   compiler_fn0  s   z3maybe_enable_compiled_autograd.<locals>.compiler_fn)r   r  r  _enable)should_enabler  r  r  r  r7   r  rL   maybe_enable_compiled_autograd*  s   
	"r  c                  C  s   G dd dt } t|  S )Nc                   @  s   e Zd ZdS )z*invalid_removeable_handle.<locals>.InvalidN)rF   rG   rH   r7   r7   r7   rL   Invalid?  s    r  )r  r+   )r  r7   r7   rL   invalid_removeable_handle=  s   
r  c                 C  s>   t | tjjs	| S t | tjjr| S | j| j}| j|_|S r\   )	r  r   r  r  r   r  rs  rB  re  )r  proxyr7   r7   rL   nn_module_proxyI  s   r  c                      s$   e Zd Z fddZdd Z  ZS )	GmWrapperc                   s   t    || _|| _d S r\   )rp  r  r`  unflatten_fn)r  r`  r  rr  r7   rL   r  U  s   

zGmWrapper.__init__c                 G  s   t |}| j| | S r\   )r  r`  r  r  r7   r7   rL   r   Z  s   zGmWrapper.forward)rF   rG   rH   r  r   rt  r7   r7   rr  rL   r  T  s    r  r`  torch.fx.GraphModulec                   s   dd t | jjD tjjjr;dgksJ t|d ts J t	|d  dd  fdd}|t
| ||nt|\}}tjtj|d}|t
| ||tjfd	d
}|S )z
    Mutate inputs so that they are flat and wrap gm such that it
    accepts those inputs.  This is needed for graphs that take
    bumpy inputs.
    c                 S  s,   g | ]\}}|j d kr|jddr|qS )r  	steal_argF)r`  r  r_   )rv   r  r  r7   r7   rL   r	  e  s
    z(flatten_graph_inputs.<locals>.<listcomp>r   c                 S  s   | d t | dd   S r  r  r  r7   r7   rL   
flatten_fnr  r  z(flatten_graph_inputs.<locals>.flatten_fnc                   s   | d   g|  d  R S r\   r7   )	flat_args)boxed_inputs_countr7   rL   r  u  s   z*flatten_graph_inputs.<locals>.unflatten_fn)treespecc                    s&   | }D ]}| |    q |S r\   )r]   )rk  r  r  )compiled_fnr  inputs_idx_to_clearr7   rL   wrapper  s   z%flatten_graph_inputs.<locals>.wrapper)	enumerater  r_  r   r  r  in_compiled_autograd_regionr  r  r  r  r  tree_flattenr  r  tree_unflattenarg_tree_leaves)r`  inputs
compile_gmr  flat_inputsspecr  r7   )r  r  r  r  rL   flatten_graph_inputs_  s    


r  c                 C  s*   t | tjjrt| dsg S | jdg S )Nr  locals_to_steal)r  r   r   r  r  r  r_   )maybe_gmr7   r7   rL   get_locals_to_steal  s   r  c                 C  s   || j d< d S )Nr  )r  )r`  r  r7   r7   rL   set_locals_to_steal  rs  r  c                   @  s   e Zd Zdd ZdddZdS )	Litc                 C  s
   || _ d S r\   r  )r  r  r7   r7   rL   r    r  zLit.__init__ro   rp   c                 C     | j S r\   r  r  r7   r7   rL   r3    s   zLit.__repr__Nr5  )rF   rG   rH   r  r3  r7   r7   r7   rL   r    s    r  zset[str]warn_once_cachec                 C  s,   | t v rd S t |  tj| |d d d S )Nr4   )
stacklevel)r  r"  warningswarn)r  r  r7   r7   rL   	warn_once  s   
r
  c                 C  s   t d}|d| S )Nz\x1B[@-_][0-?]*[ -/]*[@-~]r  )r  r  r  )textansi_escaper7   r7   rL   strip_color_from_string  s   
r  c               	   c  s<    zt jjd} d V  W t jj|  d S t jj|  w )NT)r   r  	_autograd _saved_tensors_hooks_set_tracing)rr  r7   r7   rL   +_disable_saved_tensors_hooks_during_tracing  s
   "r  c                   C  s   t jjjo	t   S r\   )r   rx  r5   freezingis_grad_enabledr7   r7   r7   rL   is_parameter_freezing  r>  r  c                   C  s   dd t t D S )Nc                 S  r  r7   ) get_torch_function_mode_stack_atro  r7   r7   rL   r	    s    z1get_torch_function_mode_stack.<locals>.<listcomp>)r  r   r7   r7   r7   rL   get_torch_function_mode_stack  s   r  c                 C  s"   | t  k r	| dksJ tj| S r   )r   r   r  _get_function_stack_at)indr7   r7   rL   r    s   r  c                 C  s,   t t D ]}t  q| D ]}t| qd S r\   )r  r   r   r   )r  rI  moder7   r7   rL   set_torch_function_mode_stack  s
   
r  c                  C  s   t t D ]} t  qd S r\   )r  r   r   )rI  r7   r7   rL   clear_torch_function_mode_stack  s   r  c                  G  s
   t   d S r\   )
breakpointr  r7   r7   rL   _breakpoint_for_c_dynamo  r  r  c                 C  sV   | j }t|}t|jdkrddlm} |d|j| jkr)ddlm} |dd S )NrD   r4   )InternalTorchDynamoErrorz[Tensor subclass method __metadata_guard__ must take exactly two subclass metadata argumentsz?Tensor subclass method __metadata_guard__ must be a classmethod)	__metadata_guard__r  	signaturer  r^  rM  r  r  rs  )r   r  sigr  r7   r7   rL   verify_guard_fn_signature  s   
r!  c                 C  sH   | j tj tj fv o#| jtjtjfv o#| jtjtjfv o#| jtjtjfv S r\   )r   r  r   r   r  __iter__)user_clsr7   r7   rL   #does_not_override_dict_iter_methods  s   r$  c                 C      t jjdddd }|| |S )NT	recursivec                 S  r  r\   )r  r   r  r7   r7   rL   r       
zcall_size.<locals>.fnr   r  disabler   r  r  r7   r7   rL   	call_size     

r-  c                 C  r%  )NTr&  c                 S  r  r\   )r  r(  r7   r7   rL   r    r)  zcall_stride.<locals>.fnr*  r,  r7   r7   rL   call_stride  r.  r/  c                 C  s   t jjdddd }|| S )NTr&  c                 S  s   |   S r\   )storage_offsetr   r7   r7   rL   r    s   zcall_storage_offset.<locals>.fnr*  )r   r  r7   r7   rL   call_storage_offset  s   
r1  c                   s   ddg} fdd|D }|S )Nr  tagc                   s(   i | ]}| j v r|t j | qS r7   )re  r  rS  r7  r7   rL   r    s    "z(_extract_tensor_dict.<locals>.<dictcomp>r7   )r@  KEYS_TO_COPYtensor_dictr7   r7  rL   _extract_tensor_dict  s   
r5  z(dict[int, weakref.ReferenceType[object]]user_obj_id_to_weakrefc                 C  s   t |   }|d usJ d|S )NzUser object is no longer alive)r6  )obj_idr}  r7   r7   rL   get_user_object_from_id+  s   
r8  c                 C  s   t | }t| t|< d S r\   )rq  r{  rx  r6  )r}  r7  r7   r7   rL   store_user_object_weakref1  s   r9  c                   @  sr   e Zd ZU dZded< dZded< dZeddd	Zedd
dZ	edddZ
edddZeedd ZdS )CompileTimeInstructionCounterr   rR   _counterr  _idro   r~   c                 C  s(   | j d | _ | j dkrt | _d S d S r   )_depthr   rK  r<  r^   r7   r7   rL   rK  ;  s   
z#CompileTimeInstructionCounter.startc                 C  s:   | j d | _ | j dkr|  jt| j7  _d| _d S d S )Nr4   r   r  )r=  r;  r   endr<  r^   r7   r7   rL   r>  A  s
   

z!CompileTimeInstructionCounter.endc                 C  s
   d| _ d S r   r;  r^   r7   r7   rL   r]   H  r)  z#CompileTimeInstructionCounter.clearc                 C  r  r\   r?  r^   r7   r7   rL   r   L  s   z#CompileTimeInstructionCounter.valuec                 c  sB    zt jr	|   d V  W t jr|   d S d S t jr |   w w r\   )r5   %record_compile_time_instruction_countrK  r>  r^   r7   r7   rL   recordP  s   

z$CompileTimeInstructionCounter.recordNr  )ro   rR   )rF   rG   rH   r;  ri   r<  r=  rj   rK  r>  r]   r   r   rA  r7   r7   r7   rL   r:  6  s   
 r:  featureusagec                 C  s"   t   rt  d| | dS dS )zQ
    Records whether we are using a feature
    Generally a feature is a JK.
    r.  N)r   r   set_key_value)rB  rC  r7   r7   rL   set_feature_use\  s   
rE  )ddp_optimizerpython_reducerno_optimization_ddp_optimization_modec                  C  sZ   t j} t| tr| rdnd}nt| tr| }n	tdt| |tv s+J d||S )NrF  rH  z;Invalid dynamo config optimize_ddp type type(optimize_ddp)=z.Invalid dynamo config optimize_ddp value mode=)r5   optimize_ddpr  r   rp   rh  rK  rI  )rJ  r  r7   r7   rL   get_optimize_ddp_modem  s   


rK  )rk   rl   rm   rn   ro   rp   r  )r   rR   ro   r~   )ro   r@   )ro   r   )ro   r   )NFNNNNNF)r   rp   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   ro   r   r   )r   r   r   r   ro   rp   )r   r   r   r   ro   r   )rp   F)r   r   r5  )rP  rp   ro   r~   )r\  r]  ro   rR   )r   r;   ro   r;   )r}  r   r~  r  ro   r  )r}  r   r~  r  ro   r  )r}  r   r~  r  ro   r   r\   )r  r  ro   r   )ra  r  ro   r~   r  )
r}  rR   r~  rR   r:  r=   r  r  r  r  )r  rR   ro   r~   )ro   r  )ro   r  )FF)r   rp   r  r   r   r   ro   r   )r  r  )ro   rJ  )r4   )ro   r  )rA  r	   ro   r   )r  rp   ro   rp   )r'  r   )T)r}  r	   )r  r  )r   r	   )rV   rK  )r   r	   r  r   )r  r  )r6  r  r  r   r  r   ro   r  )FFF)rp   rp   ra  rR   ro   rR   )rl  rp   ro   rm  )rN  r  r  r  ro   rp   )r  r  ro   r   )TT)r`  r  )rB  rp   rC  r   (  r   
__future__r   atexitrg   r)  r  r  rx  r  r|  r  rc  r  r  r|   rJ  r  r=  ra  r  r&  r  r  r  r  r   r  r  r  r  r  r{  r   r   r   r   r   r   r	   r
   r   r   r   r   r   r   r   typing_extensionsr   r   r   torch._functorch.config%torch.fx.experimental.symbolic_shapestorch.utils._pytreer  _pytreer  r   torch._Cr   r   r   r   torch._dispatch.pythonr   torch._dynamo.metrics_contextr   r   torch._guardsr   r   r   torch._subclasses.meta_utilsr   torch._utils_internalr    r!   r"   r#   r$   torch.fx._utilsr%   r&   torch.monitorr'   torch.nn.modules.lazyr(   torch.utils._tritonr)   r*   torch.utils.hooksr+   r[  collections.abcr,   r-   r.   r/   r0   r+  r  r  torch._loggingtorch._numpy_numpyr*  r1   r3   r  r5   fftlinalgr  r6   ri   NP_TO_TNP_MODULEr  r8   r9   r:   r{   r;   r  r  r  unpatched_nn_module_getattrr  unpatched_nn_module_call
_call_implunpatched_nn_module_call_implrh   r<   r>   troubleshooting_urlnnmodule_doc_urlnnmodule_doc_url_msgr?  rF   rf   r?   rV  rA   rX   timer_counterr}  rC   rN   rz   r   r   r   r   r   r   r   r   r   r   r   r   r   registerr  FloatTensorr  DoubleTensorr  double
HalfTensorr  halfBFloat16TensorrA  
ByteTensorr  
CharTensorr  
LongTensorr  long	IntTensorr  rR   ShortTensorr  short
BoolTensorr   tensortype_to_dtyper  r.  r,  r/  r(  rH  rO  r[  rc  rd  ri  rm  rn  r  r  ParamSpecArgsParamSpecKwargs	ParamSpecTypeVarTupleTypeAliasTyper  r  r  r  r  r  r  r  neltlegtgecmp_name_to_op_mappingcmp_name_to_op_str_mappingr  r  r  r  r  r  r  r  r  r  r  rP  rR  r  !DEFAULT_COMPILATION_METRICS_LIMITr  rT  rV  ro  r|  r  r   r   r  r  r  r  r  r   r  r  r  r  r  r  r  r  r'  r0  r5  r6  r;  r:  rV  ra  rj  rn  rx  r  rp   rQ   rK  Ellipsisrs  NotImplementedCodeTyper  r  memory_formatr  finfoiinfo	attention
SDPBackendr  _CudaDevicePropertiesry  r  r"  languager{  r  r  r  r  r  r  r  r  r  r  r  r   r  r  iterr  r  r  __length_hint__tuple_iterator_lenr   rB  r  r  dict_newr}   re  dict_methodsr  	tuple_newtuple_methodsr  list_methodsrr  list_getitemstr_methodsr  r  r  r  r  r  	iter_nextr  r  dict_getitemr  r  r  r  r  r  r  r  r  GLOBAL_KEY_PREFIXtorch._subclassesr  r  r  r  r  r"  r&  r3  r+  ro  rt  orig_code_mapru  rv  seen_code_mapr~  r;  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r
  r  r  r  all_hook_namesr  r$  r%  r(  r,  r-  r6  r7  r<  rC  rF  rI  rQ  rZ  r`  rf  rg  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r
  r  r  r  r  r  r  r  r  r!  r$  r-  r/  r1  r5  r6  r8  r9  r:  rE  rI  rK  r7   r7   r7   rL   <module>   s  ,



(  	~%



	!


 *0"+
O
  2 


J

		 $
"   

)!

  2 ,	M'	
"
#	 		y /	
&
