a
    hzu                    @  sD  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#m$Z$ ddlm%Z% ddlm&Z& ddlm'Z'm(Z( dd	lm)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1 dd
l2m3Z3m4Z4m5Z5m6Z6 ddl7Z7ddl8Z7ddl9Z7ddl:m;  m<Z= ddl7m>Z> ddl?m@Z@mAZAmBZBmCZC ddlDmEZE ddlFmGZGmHZH ddlImJZJmKZKmLZL ddlMmNZN ddlOmPZPmQZQmRZRmSZSmTZT ddlUmVZVmWZW ddlXmYZY ddlZm[Z[ ddl\m]Z]m^Z^ ddl_m`Z` ddlambZb ejcrddldmeZemfZfmgZgmhZhmiZimjZj zddlkZlW n emy   dZlY n0 zddlnZ7ddlompZq ddlImrZr ddlnmsZs ddltmuZu elrNeleljveljweljxfZydezd< eleqeljveqjveljweqjweljxeqjxiZ{ndZyi Z{dd l|m}Z}m~Z~mZ W n ey   Y n0 e0d!Ze7jjjZe7jjjZe7jjjZeej!Zd"ezd#< i Zd$ezd%< d&Zd'Zd(e d)ZeeZi Zd*ezd+< eeZd,ezd-< e ZG d.d/ d/e
jZG d0d1 d1Zd2d3d4d5d6d7Zdad8d9d:d;Zd8d9d<d=Zdad>d8d?d@dAZd,d9dBdCZd8d9dDdEZdFezdG< dHezdI< dFd9dJdKZdHd9dLdMZG dNdO dOe
jZG dPdQ dQZe Ze$dSd4dSdTdUdSdVdWdTdSdXdY
dZd[Ze/dTd\dTd4d]d^d_Ze/dUd`dTdad]dbd_ZdVdTdcddd_Zejd8d9dedfZe7je7je7jfe7je7je7jfe7je7je7jfe7je7jfe7je7jfe7je7jfe7je7je7jfe7je7je7jfe7je7je7jfe7je7jfi
ZG dgdh dhZeǃ Zdidj Zd8d9dkdlZdmdn Zdodp Zd4d9dqdrZd4d8dsdtduZdvd>dwdxdyZd!d!dzd{d|Zd}d~ Zdd ZG dd dZe/ddddddZe/ddddddZe/dddTdddZdd Zejdkrejejejej0ejejfZdd Zdd Zdd Ze/dddddZe/dddddZddTdddZe1ejejejejf Zdezd< dddddZdddddZejejejejejejdZdddddddZdddddZdd Zdd Zdd Zdd Zdd Ze&ddd ZdWddZdd ZdddÜddńZdddÜddǄZdZejG ddʄ dʃZdZejed̍adezd< dd8dϜddфZ dSd9ddӄZdSd9ddՄZd>d>d$ddd؜ddڄZeGedۍZeHedۍZd>d8dܜddބZd8d9ddZdd9ddZG dd dZ	da
dezd< dd9ddZdTd9ddZe$dXd4dTdTdXdddZejG dd dZG dd deӃZe e_dd ZddddZdd ZddddZe$dd Zd d ZdYddZdd Zdd Zdd	 Ze&dd
d9ddZdd ZdZddZdd Ze&ddd Zeee eŐe!e"e#de$j%e&j%ej'e7j'e7j(e7j)e7j*e7j+e7j,e7jj-j.e7j/j0hZ1dezd< e^ rddl2Z2e13e2j4j( dd Z5ej6dd Z7dddddZ8dd  Z9d!d" Z:d#d$ Z;d%d& Z<d'd( Z=d)d* Z>d+d, Z?e#i @ ZAd-ezd.< e#i B ZCd/ezd0< e#i D ZEd1ezd2< e#e" B ZFd/ezd3< e#eGdZHd4ezd5< e#eGeIdZJd4ezd6< eHjKZLeMjNZOePjNZQd7d8 eRePjSB e"jSB D ZTeUjNZVd9d8 eUjSB D ZWd:d8 eXjSB D ZYeXjZZ[d;d8 e!jSB D Z\d<d= Z]d>d? Z^d@dA Z_dBdC Z`dDdE ZadFdG ZbecZddHd9dIdJZedKdL ZfePjZZgdMdN ZhdOdP ZidQdR ZjdSdT Zkd[dUdVZlddWdXdYdZZmd[d\ Znd4d9d]d^Zod4d9d_d`ZpdaZqddblrmsZs dcdd ZtddTdedfdgZudRdhd4d4didjdkZvdldm Zwdndo Zxdpdq ZyddRdrdRdsdRdRejzdRdRf
dTdtdudvZ{dwdx Z|ej$dydz Z}eӃ Z~eeXZd{ezd|< g Zd}ezd~< eӃ Zej6dd Zdd Zd\ddZdd Zdd Zd]ddZe Zdd Ze$dd Zdd Zdd Zdd ZddddZdd ZddddZddddZdd ZddddZd^ddTdddZG dd de
jZddddZddTdddddZdd Zdd ZddgZddgZg dZee e Zdd Zd_ddZd`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dܐd݄ Zd4d>d>dޜdߐdZejG dd dZd4ddddZddd4dddZdd Zdd Zdd Zdd Zdd ZddTdddZdd Zdd Zdd Zej$dad dZdd Zdd ZG dd de7jjZdd	d
dZdd Zdd ZG dd dZeÃ ZĐdezd< db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) Ze7jАd*d+ Ze7jАd,d- Ze7jАd.d/ ZӐd0d1 Zi ZՐd2ezd3< d4d5 Z֐d6d7 ZG d8d9 d9Zd4dTd:d;d<Zِd=Zڐd
ezd>< d?d@ Ze$dAd9dBdCZe$dAd9dDdEZݐdFdTdGdHdIZe7jАdJd9dKdLZe7jАdJd8dMdNdOZdPd9dQdRZdS (c  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)AbstractContextManagercontextmanager)is_dataclass)	lru_cache)CodeTypeMethodWrapperType)	AnyCallablecastClassVarGenericOptionaloverloadTypeVarUnion)Literal	TypeAlias	TypeGuard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   )_get_flat_args)	Generator	ItemsView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_metricszdict[str, float]cumulative_time_spent_nsc                   @  s   e Zd ZdZdZdZdS )ReInplaceTriggerr0         N)__name__
__module____qualname__ZAUTO_FUNC_V1ZAUTO_FUNC_V2Z
TRITON_OPSr=   r=   r=   A/var/www/auris/lib/python3.9/site-packages/torch/_dynamo/utils.pyrG      s   rG   c                   @  sx   e Zd ZU eeZded< edddddZ	edd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]_valuesrG   int)triggerbytesc                 C  s&   |dkr"| j d|j   |7  < d S Nr   Zmissed_bytes_)rO   name)clsrQ   rR   r=   r=   rM   add_missed_bytes   s    z"ReinplaceCounters.add_missed_bytes)rQ   countc                 C  s$   |dkr | j d|   |7  < d S Nr   Zmissed_tensors_)rO   )rU   rQ   rW   r=   r=   rM   add_missed_opportunities   s    z*ReinplaceCounters.add_missed_opportunitiesc                 C  s   | j   d S N)rO   clearrU   r=   r=   rM   r[      s    zReinplaceCounters.clearc                 C  s*   d}t D ]}|| jd| d7 }q|S rX   )rG   rO   getrU   sumrQ   r=   r=   rM   get_total_missed   s    z"ReinplaceCounters.get_total_missedc                 C  s,   d}t D ]}|| jd|j d7 }q|S rS   )rG   rO   r]   rT   r^   r=   r=   rM   get_total_missed_bytes   s    z(ReinplaceCounters.get_total_missed_bytesc                 C  s   | j rtdd| j  d S )NZinductorZreinplace_counters)rO   r(   r\   r=   r=   rM   log   s    zReinplaceCounters.logN)rJ   rK   rL   collectionsdefaultdictrP   rO   __annotations__classmethodrV   rY   r[   r`   ra   rb   r=   r=   r=   rM   rN      s   



rN   z3Union[list[tuple[str, object]], list[list[object]]]z!Union[tuple[str, ...], list[str]]str)rowsheadersreturnc              
   C  sN   zdd l }|j | |dW S  tyH   ddd t|g| D  Y S 0 d S )Nr   ri   
c                 s  s   | ]}d  tt|V  qdS ), N)joinmaprg   ).0rowr=   r=   rM   	<genexpr>   s   ztabulate.<locals>.<genexpr>)tabulateImportErrorrn   	itertoolschain)rh   ri   rs   r=   r=   rM   rs      s    
rs   Nonerj   c                   C  s   t d a d S Nr0   )
curr_framer=   r=   r=   rM   increment_frame   s    r{   c                   C  s   t   t  dad S Nr   )rF   r[   rE   rz   r=   r=   r=   rM   reset_frame_count   s    r}   rP   )cntrj   c                 C  s   t | 7 a d S rZ   )op_count)r~   r=   r=   rM   increment_op_count   s    r   c                  C  sB   i } t  D ]\}}|d | |< q| dd| dd | d< | S )N    eAZentire_frame_compiler   Zentire_backward_compileZtotal_wall_time)rF   itemsr]   )total_by_keyphaseZtimingr=   r=   rM   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valuer=   r=   rM   print_time_report  s
    r   r   _METRICS_CONTEXTr   _RUNTIME_METRICS_CONTEXTc                   C  s   t S rZ   )r   r=   r=   r=   rM   get_metrics_context9  s    r   c                   C  s   t S rZ   )r   r=   r=   r=   rM   get_runtime_metrics_context=  s    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
    r0   rH   rI   N)rJ   rK   rL   __doc__CHROMIUMPT2_COMPILECOMPILATION_METRICr=   r=   r=   rM   r   A  s   r   c                   @  sB  e Zd ZdZedejfddddddd	Zed/dddddddZed0ddddddZ	edddddddZ
edejfddddddZedddddddZeejfddddddZeddd d!d"Zeddd d#d$Zed1ddd%d&d'Zed2dddd(d)d*Zeddd d+d,Zed-d. ZdS )3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)
    Nrg   rC   Optional[int]r   )
event_namemetadatatime_ns	log_levelc                 C  sR   |d u rt  }t }|tjkr&d}n|tjkr6d}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_eventr=   r=   rM   r   h  s    

z$CompileEventLogger.log_instant_eventFboolobject)r   r   	overwriter   c                 K  s   t  }| }|tjkr,|j| fi | n|tjkrd| }| |vrPtd| |j| fi | nZ|tjksrJ | }| |krtdt	 }|
 st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_contextr=   r=   rM   add_data~  s2    

zCompileEventLogger.add_data)r   r   r   c                 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   r=   r=   rM   add_toplevel  s    
zCompileEventLogger.add_toplevelrP   )r   r   r   r   c                 C  s   t  }|tjks|tjkr*|| || nV|tjks8J | }| |krPtdt }|	 sft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   r=   r=   rM   r     s&    zCompileEventLogger.incrementr0   )r   r   r   c                 C  s2   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   r=   r=   rM   increment_toplevel  s    	z%CompileEventLogger.increment_toplevelr   c                 C  s   t  }|tjks|tjkr*|| || nV|tjks8J | }| |krPtdt }|	 sftd||| || || dS )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   r=   r=   rM   r     s&    zCompileEventLogger.add_to_setc                 C  s2   t  }| }|du rtdt||| | dS )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   r=   r=   rM   add_to_set_toplevel	  s    
z&CompileEventLogger.add_to_set_toplevelr   r   c                 K  s   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=   r=   rM   chromium  s    zCompileEventLogger.chromiumc                 K  s   t j| tjfddi| dS )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   r=   r=   rM   pt2_compile'  s    	zCompileEventLogger.pt2_compiler   r   c                 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=   r=   rM   compilation_metric4  s
    z%CompileEventLogger.compilation_metricr   r   r   c                 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=   rM   instant@  s    
zCompileEventLogger.instantc                 K  s&   t  s
dS t }|j| fi | dS )z
        Adds to an existing pt2_compile event, but silently returns if the event doesn't exist
        or ChromiumEventLogger is not initialized.
        This function is syntactic sugar for chromium_event_logger().try_add_event_data.
        N)chromium_event_log_activer   try_add_event_data)r   r   r   r=   r=   rM   try_add_pt2_compileL  s    z&CompileEventLogger.try_add_pt2_compilec                 O  s.   t  s
dS t }| sdS | |i | dS )z
        Special function that quietly runs a given method, returning if CHROMIUM_EVENT_LOG is None or metrics context is not set
        N)r   r   r   )Z	method_fnargskwargsr   r=   r=   rM   try_X  s    zCompileEventLogger.try_)F)F)F)N)rJ   rK   rL   r   staticmethodr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r=   r=   r=   rM   r   O  sF    - 	 r   FOptional[str]r   zOptional[dict[str, object]]Optional[CompileId]Optional[bool]zGenerator[Any, None, None])
r   
phase_namer   r   dynamo_compile_column_us
compile_idis_backwardlog_waitcounterwaitcounter_name_overriderj   c	                 c  s8  |r|}	| }
n| }	d}
| t vr&g t | < i }|r8|| |
rJ|d|
i |dur`|d|i t }t }||	|||| tj|  dg}|r|r|n| }|	t
d|   tjj du}|r8|dsJ ttdsdt_t jd	7  _tjd	kr8|	t
d
  |s8d}|	t
|  z t ,}|D ]}|| qJdV  W d   n1 sx0    Y  W t }|| }t |  	|d  ||	|i ||| |r4t|	  |7  < t jd	8  _tjdk}|d }|r&t }| rZ||| |rZ|d| n4t }||| |r4|d| d}|d|| nt }|| }t |  	|d  ||	|i ||| |r2t|	  |7  < t jd	8  _tjdk}|d }|rt }| r2||| |r2|d| n4t }||| |r2|d| d}|d|| 0 dS )a  
    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".
    - 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_backward: Specify forward/backward directly when not available in a
      CompileContext, e.g., during runtime autotuning.
      that support it.
    - log_waitcounter: If set, we'll log a waitcounter of the form "pytorch.dynamo_timed.{key}"
    Nfn_namer   z (dynamo_timed)zpytorch.wait_counter.Z_usdepthr   r0   z#pytorch.wait_counter.dynamo_compilez.pytorch.wait_counter.compile_runtime_overheadsr     duration_usT)r   
is_runtime
is_forward)rE   r   r   r   r   log_event_starttorchprofilerZrecord_functionappendr+   Zguard_guardsCompileContextcurrent_compile_idendswithhasattr_dynamo_timed_tlsr   
contextlib	ExitStackenter_contextlog_event_endrF   r   r   r   r   )r   r   r   r   r   r   r   r   r   r   r   event_metadatar   start_nsZcx_mgrsZwc_nameZis_compile_timeZ
runtime_wcstackZcxZend_nsZtime_spent_nsZis_outer_eventr   r   Zruntime_contextextrar=   r=   rM   dynamo_timedh  s    6



(



r   zLiteral['str'])repr	aggregaterj   c                 C  s   d S rZ   r=   r   r   r=   r=   rM   compile_times  s    r   zLiteral['csv']ztuple[list[str], list[object]]c                 C  s   d S rZ   r=   r   r=   r=   rM   r     s    r   c                   s|   dd f fdd	| dkrFfddt D }d}|t|d	d
7 }|S | dkrx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   | S rZ   r=   xr=   r=   rM   <lambda>      zcompile_times.<locals>.<lambda>c                   s     r|t | S dt|| S )Nrm   )r_   rn   ro   )valuesitem_fnr   r=   rM   fmt_fn  s    zcompile_times.<locals>.fmt_fnrg   c                   s$   g | ]}| t | d d dfqS )c                 S  s   | dS )Nz.4fr=   r   r=   r=   rM   r     r   *compile_times.<locals>.<listcomp>.<lambda>r   )rE   rp   kr   r=   rM   
<listcomp>  s   z!compile_times.<locals>.<listcomp>z!TorchDynamo compilation metrics:
)ZFunctionzRuntimes (s)rk   csvc                   s   g | ]} |d d dqS )c                 S  s   | dS )Nz.6fr=   r   r=   r=   rM   r   !  r   r   r   r=   )rp   vr   r=   rM   r      s   N)rE   rs   r   listkeys)r   r   rh   r   r   ri   r=   )r   r   rM   r     s    

c                   C  s   t tddd d S )Nrg   Tr   )rb   infor   r=   r=   r=   rM   dump_compile_times)  s    r   c                   @  s6   e Zd ZddddddZdd Zd	d
dddZdS )DuplicateWarningChecker   rP   rw   )maxsizerj   c                 C  s   || _ |   d S rZ   )r  reset)selfr  r=   r=   rM   __init__=  s    z DuplicateWarningChecker.__init__c                 C  s   t  | _d S rZ   )r   setr  r=   r=   rM   r  A  s    zDuplicateWarningChecker.resetz!Union[str, tuple[object, object]]r   )r   rj   c                 C  sT   || j v r&| j j|dd tjsPdS n*d | j |< t| j | jkrP| j jdd q0dS )NT)lastF)r  move_to_endr;   verboselenr  popitemr  r   r=   r=   rM   addD  s    

zDuplicateWarningChecker.addN)r  )rJ   rK   rL   r  r  r  r=   r=   r=   rM   r  <  s   r  c                  C  s$   t jdddk} | rt S t S )NZTORCH_COMPILE_DEBUG01)osenvironr]   add_file_handlerr   r   )Zcompile_debugr=   r=   rM   setup_compile_debugS  s    r  c                   C  s   t   d S rZ   )graph_break_dup_warning_checkerr  r=   r=   r=   rM   reset_graph_break_dup_checker\  s    r  c                    sf   t jt d} t j| dd tt j| d td  t	
 }| fdd |S )NZtorchdynamoTexist_okz	debug.logztorch._dynamoc                     s
     S rZ   removeHandlerr=   Zlog_file_handlerloggerr=   rM   r   i  r   z"add_file_handler.<locals>.<lambda>)r  pathrn   get_debug_dirmakedirsloggingFileHandler	getLogger
addHandlerr   r   callback)Zlog_path	exitstackr=   r  rM   r  `  s    

r  c                    sV   t  } tjd urRttj tjj	 D ]"
  |  fdd q*| S | S )Nc                     s
     S rZ   r  r=   r  r=   rM   r   s  r   z setup_log_file.<locals>.<lambda>)r   r   r;   log_file_namer!  r"  r   _logging	_internalZget_loggersr$  r%  )r&  r=   r  rM   setup_log_filem  s    

r*  c                 C  s(   t   d|j dt| j d|j dS )Nz/error_recordings/_z.rec)r  co_nametyperJ   co_firstlineno)exccoder=   r=   rM   gen_record_file_namey  s    r1  )filenamerj   c                 C  s   zht j| rtd|  nJt jt j| dd t| d}|| W d    n1 s\0    Y  W n t	y   t
d|  Y n0 d S )Nz9Unable to write execution record %s; file already exists.Tr  wbz#Unable to write execution record %s)r  r  existsrb   warningr   dirnameopendump	Exception	exception)r2  Zexec_recordfr=   r=   rM   write_record_to_file~  s    ,r<  zfx.Graph)grj   c                 C  s&   d}| j D ]}d|jv r
|d7 }q
|S )Nr   callr0   )nodesop)r=  cnr=   r=   rM   count_calls  s
    


rC  )r   rj   c                 C  s   | S rZ   r=   r   r=   r=   rM   identity  s    rD  c                 C  s:   zt |  W dS  ty"   Y dS  ty4   Y dS 0 d S NTF)hash	TypeError
ValueErrorr   r=   r=   rM   hashable  s    rI  c                  O  s   d S rZ   r=   r   r   r=   r=   rM   nothing  s    rK  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 rZ   r   refsr  r=   r=   rM   r    s    zExactWeakKeyDictionary.__init__c                 C  s   | j t| S rZ   )r   idr  r=   r=   rM   __getitem__  s    z"ExactWeakKeyDictionary.__getitem__Nc                 C  s   | j t||S rZ   )r   r]   rO  )r  r   defaultr=   r=   rM   r]     s    zExactWeakKeyDictionary.getc                 C  s   t || jv S rZ   )rO  r   r  r=   r=   rM   __contains__  s    z#ExactWeakKeyDictionary.__contains__c                   s<   t |  jvr.t| fddj < |j < d S )Nc                   s
     S rZ   )
_remove_id)refidxr  r=   rM   r     r   z4ExactWeakKeyDictionary.__setitem__.<locals>.<lambda>)rO  rN  weakrefrT  r   )r  r   r   r=   rU  rM   __setitem__  s    
z"ExactWeakKeyDictionary.__setitem__c                 C  s(   || j v r| j |= || jv r$| j|= d S rZ   rM  )r  rV  r=   r=   rM   rS    s    

z!ExactWeakKeyDictionary._remove_idc                 C  s   | j   | j  d S rZ   )rN  r[   r   r  r=   r=   rM   r[     s    
zExactWeakKeyDictionary.clear)N)rJ   rK   rL   r   r  rP  r]   rR  rX  rS  r[   r=   r=   r=   rM   rL    s   
rL  r   ztype[T]z	TypeIs[T])objallowed_typesrj   c                 C  s   d S rZ   r=   rY  rZ  r=   r=   rM   istype  s    r\  z)tuple[type[list[T]], type[tuple[T, ...]]]c                 C  s   d S rZ   r=   r[  r=   r=   rM   r\    s    zIterable[type]c                 C  s   d S rZ   r=   r[  r=   r=   rM   r\    s    c                 C  s(   t |tttfrt| |v S t| |u S )zisinstance() without subclasses)
isinstancetupler   r  r-  r[  r=   r=   rM   r\    s    rI      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   r=   r=   rM   	is_typing  s    	rg  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uint8Zuint16Zuint32Zuint64rf  r=   r=   rM   is_numpy_int_type  s    ro  c                 C  s   t sdS t| t jt jt jfS rh  )ri  r\  float16float32float64rf  r=   r=   rM   is_numpy_float_type  s    rs  zCallable[..., T]z*TypeGuard[functools._lru_cache_wrapper[T]])r   rj   c                 C  s   d S rZ   r=   rf  r=   r=   rM   is_lru_cache_wrapped_function  s    rt  r   z,TypeGuard[functools._lru_cache_wrapper[Any]]c                 C  s   d S rZ   r=   rf  r=   r=   rM   rt    s    c                 C  s   t | tjott| dS )N__wrapped__)r]  	functools_lru_cache_wrapperis_functioninspectgetattr_staticrf  r=   r=   rM   rt  %  s    
r   
_FuncTypeszMTypeIs[Union[_FuncTypes, torch._ops.OpOverloadPacket, torch._ops.OpOverload]]c                 C  s   t | pt| tjjtjjfS rZ   )rx  r]  r   _opsZOpOverloadPacket
OpOverloadrf  r=   r=   rM   is_function_or_wrapper5  s    
r~  zTypeIs[_FuncTypes]c                 C  s   t | tjtjtjtjfS rZ   )r]  typesFunctionTypeBuiltinFunctionTypeMethodDescriptorTypeWrapperDescriptorTyperf  r=   r=   rM   rx  =  s    rx  )__eq____ne____lt____le____gt____ge__z==z!=<z<=>z>=zTypeIs[Union[types.GetSetDescriptorType, types.MethodDescriptorType, types.WrapperDescriptorType, types.MemberDescriptorType, types.MethodWrapperType]]c                 C  s   t | tjtjtjtjtjfS rZ   )r]  r  GetSetDescriptorTyper  r  MemberDescriptorTyper
   rf  r=   r=   rM   is_wrapper_or_member_descriptor_  s    r  c                 C  s   t | d S r|   ) unwrap_with_attr_name_if_wrapper)fnr=   r=   rM   unwrap_if_wrapper{  s    r  c                 C  s6   t | r*t| ddr*t| d| } d}nd }| |fS )NZ_torchdynamo_inlineF)rx  ry  rz  )r  	attr_namer=   r=   rM   r    s
    r  c                 C  s   t sdS t| t jS rh  )ri  r\  ndarrayrf  r=   r=   rM   is_numpy_ndarray  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	Parameterr;   traceable_tensor_subclasses_subclassesr>   r\  )rY  Ztensor_listr=   r=   rM   istensor  s    r  c                 C  s
   t | tS rZ   )r]  r,   modr=   r=   rM   is_lazy_module  s    r  r  c                  G  s   t |   d S rZ   )r   r   r=   r=   rM   
print_once  s    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    S rZ   r=   r=   r   r=   rM   r;    s    zmake_cell.<locals>.fNr0   r   )__closure__r  )valr;  r=   r   rM   	make_cell  s    r  c                 C  s   z.t dd | D }dd | D }||fW S  ty } zRddlm} ddlm} |dd	||   d
|t|   dg |d W Y d }~n
d }~0 0 d S )Nc                 s  s   | ]}|  V  qd S rZ   as_proxyrp   argr=   r=   rM   rr     r   z$proxy_args_kwargs.<locals>.<genexpr>c                 S  s   i | ]\}}||  qS r=   r  )rp   r   r  r=   r=   rM   
<dictcomp>  r   z%proxy_args_kwargs.<locals>.<dictcomp>r0   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hintsZfrom_exc)	r^  r   NotImplementedErrorr/  r  Zvariables.baser  r   r   )r   r   Z
proxy_argsproxy_kwargser  r  r=   r=   rM   proxy_args_kwargs  s    
r  Optional[float]r   )r   rj   c                 C  s   | d u rd S t | d S Nr   rP   r   r=   r=   rM   	to_int_ms  s    r  c                 C  s   | d u rd S t | d S )Ni@B r  r  r=   r=   rM   	to_int_us  s    r  rI   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=< e;Z<d>ed?< d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ZFdIedJ< dZGdedK< dLZHdedM< dZId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< dZTdedY< dZUdedZ< dZVded[< dZWded\< dZXded]< eYd^d_d`daZZdS )bCompilationMetricsNr   r   	frame_keyr,  co_filenamer   r.  
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_usr   !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 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_usrP   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python_version!pgo_put_remote_code_state_time_us!pgo_get_remote_code_state_time_usparam_numelparam_bytesparam_countrC   )metricsc           	      C  s"  ddddd}ddddd}dd	dd
d}dd	ddd}|| d|| d|| d|| d|| d|| d|| d|| d|| dd	}i ||}|| d|d< || d|d< || d|d< | d}|rt|nd|d< | f 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.
        r   r  )metricrj   c                 S  s   | d ur| d S d S )Ng    .Ar=   r
  r=   r=   rM   us_to_s9  s    z*CompilationMetrics.create.<locals>.us_to_sc                 S  s   | d ur| d S d S r  r=   r  r=   r=   rM   us_to_ms<  s    z+CompilationMetrics.create.<locals>.us_to_mszOptional[Any]r   c                   sJ   ddddd | d u rd S t | ttfs.dS d fdd	t| D S )
Nr   rg   itemrj   c                 S  s$   z
t | W S  ty   Y dS 0 d S N	<unknown>)rg   r9  )r  r=   r=   rM   safe_str@  s    
zFCompilationMetrics.create.<locals>.collection_to_str.<locals>.safe_strr  ,c                 3  s   | ]} |V  qd S rZ   r=   )rp   r  r  r=   rM   rr   L  r   zGCompilationMetrics.create.<locals>.collection_to_str.<locals>.<genexpr>)r]  r  r   rn   sortedr  r=   r  rM   collection_to_str?  s    z4CompilationMetrics.create.<locals>.collection_to_strc                 S  s6   | d u rd S zt t| W S  ty0   Y dS 0 d S r  )jsondumpsr   r9  r  r=   r=   rM   collection_to_json_strN  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  r   r   N)r]   rg   )	rU   r	  r  r  r  r  Zlegacy_metricsZall_metricsr   r=   r=   rM   create1  sV    
zCompilationMetrics.create)[rJ   rK   rL   r   re   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  r  r  r  LOG_FORMAT_VERSIONr  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  rf   r  r=   r=   r=   rM   r    s   
r  @   maxlenz%collections.deque[CompilationMetrics]_compilation_metrics)rA  rj   c                 C  s   t  }| }|sdS |j|| j| j| j| j| j| j| j	| j
| j| j| j| j| j| j| j| jdurlt| jnd| jdurt| jnd| jdurt| jnd| j| j| jd 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.
    N)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  )rA  Zevent_loggerr   r=   r=   rM   #add_compilation_metrics_to_chromium  sD    r   c                  C  s*   ddddd} | t  }tj|ddS )NrC   )drj   c                   s   h d  fdd|   D S )N>   debug_dir_rootZ_save_config_ignorer  Zrepro_toleranceZignore_logger_methodsTYPE_CHECKINGbase_dirlog_compilation_metricsZsame_two_models_use_fp64Zrepro_levelZ+inject_BUILD_SET_unimplemented_TESTING_ONLYZrepro_afterZrepro_forward_onlyr  Z_custom_ops_profileZnontraceable_tensor_subclassesZ)_autograd_backward_strict_mode_banned_opsr'  Zreorderable_logging_functionsZrepro_ignore_non_fpc                   s0   i | ](\}}| vr|t |tr(t|n|qS r=   )r]  r  r  )rp   r   r   Z	blocklistr=   rM   r    s   zJ_get_dynamo_config_for_logging.<locals>.clean_for_json.<locals>.<dictcomp>)r   r!  r=   r&  rM   clean_for_json  s    
z6_get_dynamo_config_for_logging.<locals>.clean_for_jsonT)	sort_keys)r;   get_config_copyr  r  )r(  Zconfig_dictr=   r=   rM   _get_dynamo_config_for_logging  s    r+  c                  C  s   G dd dt j} t }d}tjjr0tjj nd}|durzb| D ]2\}}t|t	sb|
| t|trFt|||< qF|D ]
}||= q~t j|| ddd}W n ty   d}Y n0 |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 0 d S )NzValue is not JSON serializable)superrQ  r9  )r  o	__class__r=   rM   rQ    s    zI_scrubbed_inductor_config_for_logging.<locals>.TypeSafeSerializer.default)rJ   rK   rL   rQ  __classcell__r=   r=   r.  rM   TypeSafeSerializer  s   r1  NT)rU   skipkeysr)  z(Inductor Config is not JSON serializable)r  JSONEncoderr  r   	_inductorr;   r*  r   r]  rg   r  r   r  r9  )r1  Zkeys_to_scrubZinductor_conf_strZinductor_config_copyr   r  r=   r=   rM   %_scrubbed_inductor_config_for_logging  s.    




r5  zOptional[type[BaseException]]zOptional[BaseException])start_time_nsend_time_nsr	  exc_type	exc_valuec                   s@  t jj rBzddlm} |}d}W qJ ty>   d }d }Y qJ0 nd }d }|d}|sdt jj	
 }|| d |d |r||jnd |rt|nd tt j t t t jjt rtjnd||tjd}	ti |	| t  d}
 jd	u rd
|
 }
 jdu r|
d }
t jj|
 fddd	|d t  t j!r<t"  d S )Nr   )REMOTE_CACHE_VERSIONZ_ManifoldCacher   r    )r   r  r  r  r  r  r  r  r  r  r  r  r  compilation_metricsFZbwd_TZ_runtimec                     s   dd t   D S )Nc                 S  s(   i | ] \}}|t |tr t|n|qS r=   )r]  r  r   )rp   r   r   r=   r=   rM   r  C  s   z@record_compilation_metrics.<locals>.<lambda>.<locals>.<dictcomp>)dataclassesZasdictr   r=   r<  r=   rM   r   C  s   z,record_compilation_metrics.<locals>.<lambda>)Zrecord_logging_overheadr   )#r   r4  utilsZ should_use_remote_fx_graph_cacheZtorch._inductor.fb.remote_cacher:  ModuleNotFoundErrorr]   r   r   r   rL   rg   r  r(  Zget_structured_logging_overheadr+  r5  versioncudar-   triton__version__ra  r  r  r  r   r   r   trace_structuredr   r;   r%  r&   )r6  r7  r	  r8  r9  r:  r  r  r   Zcommon_metricsrT   r=   r>  rM   record_compilation_metrics  sZ    



rF  )Zon_exit)new_sizerj   c                 C  s,   t t| krt  q tjt| d}|ad S )Nr  )r  r  popleftrc   deque)rG  Z	new_dequer=   r=   rM   set_compilation_metrics_limit_  s    
rJ  c                   C  s   t   d S rZ   )r  r[   r=   r=   r=   rM   clear_compilation_metricsg  s    rK  zlist[CompilationMetrics]c                   C  s   t tS rZ   )r   r  r=   r=   r=   rM   get_compilation_metricsl  s    rL  c                	   @  s  e Zd ZdZddddZddddZd	d
 ZddddZdd ZdddddZ	dddddZ
ddddddZddddddZd1dddd d!dd"d#d$Zddd%d&Zd2ddddd d!dd'd(d)Zd3dddd*dd+d,d-Zd4ddd*d dd.d/d0ZdS )5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.
    z	list[str]rx   c                 C  s(   t | jdr| jjS g | j_| jjS dS )z]
        The main event stack, with every chromium event.
        Logged to tlparse.
        r   N)r   tlsr   r  r=   r=   rM   	get_stackw  s    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)rO  )r  r   r=   r=   rM   r     s    z'ChromiumEventLogger.get_outermost_eventc                 C  s(   t | jdr| jjS g | j_| jjS dS )zq
        A smaller subset of the main stack that gets used to log
        PT2 Compile Events internally.
        r   N)r   rN  r   r  r=   r=   rM   r     s    z,ChromiumEventLogger.get_pt2_compile_substackrC   c                 C  s   t | jdsi | j_| jjS )N
event_data)r   rN  rP  r  r=   r=   rM   get_event_data  s    z"ChromiumEventLogger.get_event_datac                 C  s*   t  | _tt | _td| j d S )Nz*ChromiumEventLogger initialized with id %s)		threadinglocalrN  rg   uuiduuid4id_rb   r   r  r=   r=   rM   r    s    
zChromiumEventLogger.__init__rg   rw   )r   rj   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)rO  r   )r  r   r   r=   r=   rM   r     s    z&ChromiumEventLogger.try_add_event_datac                 K  sT   ||   vr*tdt| d|    d|  }||vrBi ||< || | 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)rO  r   r   rQ  r   )r  r   r   rP  r=   r=   rM   r     s    	z"ChromiumEventLogger.add_event_datarP   )r   r   r   c                 C  sr   ||   vr*tdt| d|    d|  }||vrBi ||< ||| vrZd|| |< || |  |7  < dS )zK
        Increment an integer event data field by the given amount
        rW  rX  rY  r   N)rO  r   r   rQ  r  r   r   r   rP  r=   r=   rM   r     s    zChromiumEventLogger.incrementr   c                 C  sr   ||   vr*tdt| d|    d|  }||vrBi ||< ||| vr\t || |< || | | dS )zR
        Add a value to a set within a event_name's metadata if it exists
        rW  rX  rY  N)rO  r   r   rQ  r  r  rZ  r=   r=   rM   r     s    	zChromiumEventLogger.add_to_setFNr   r   )r   r   r   r   r   rj   c                 C  sb   |pt jj }t||d< | ||d| |  | | j|fi | |r^| 	 | 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   rg   _log_timed_eventrO  r   r   r   r  r   r   r   r   r   r=   r=   rM   r     s    z#ChromiumEventLogger.log_event_startc                 C  s4   |   }|  }|  |  |  }|  d S rZ   )rO  r   r[   rQ  )r  r   ZsubstackrP  r=   r=   rM   r    s    zChromiumEventLogger.reset)r   r   r   r6  r   r   rj   c                   s   |pt jj }t||d< |  } |v r<|  }| = ni }|| |  |d|}	 fdd}
|  } |vrt	
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                   s$    | d kr t d |   q d S )Nz>ChromiumEventLogger: Detected overlapping events, fixing stack)rb   r5  pop)r   r   r=   rM   	pop_stack6  s
    z4ChromiumEventLogger.log_event_end.<locals>.pop_stackz7ChromiumEventLogger: Start event not in stack, ignoringN)r   r   r   r   rg   rQ  r   r\  rO  rb   r5  r   r%   rV  r`  )r  r   r   r   r6  r   r   Zall_event_datar   eventrb  Zevent_stackr   r=   ra  rM   r     s8    



z!ChromiumEventLogger.log_event_endzOptional[dict[str, Any]])r   r   r   r   rj   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   )rT   tsr   phcattidpidchromium_eventc                     s    S rZ   r=   r=   rc  r=   rM   r   n  r   z6ChromiumEventLogger._log_timed_event.<locals>.<lambda>FZ
payload_fnZsuppress_contextZexpect_trace_id)r   r(  rE  r'   )r  r   r   r   r   r=   rj  rM   r\  X  s     

z$ChromiumEventLogger._log_timed_event)r   r   r   r   rj   c              	     sv   |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 |rrt |  | j	| 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)rT   rd  r   re  rf  rg  rh  sri  c                     s    S rZ   r=   r=   rj  r=   rM   r     r   z7ChromiumEventLogger.log_instant_event.<locals>.<lambda>FTrk  )
rg   r   r   r   r   r(  rE  r%   r   rV  r]  r=   rj  rM   r   u  s.    
z%ChromiumEventLogger.log_instant_event)FN)N)N)NF)rJ   rK   rL   r   rO  r   r   rQ  r  r   r   r   r   r   r  r   r\  r   r=   r=   r=   rM   rM  p  s*   	   N !  rM  zOptional[ChromiumEventLogger]CHROMIUM_EVENT_LOGc                   C  s   t d u rt a t S rZ   )ro  rM  r=   r=   r=   rM   r     s    r   c                   C  s   t d uS rZ   )ro  r=   r=   r=   rM   r     s    r   )r   reset_event_log_on_exitr   rj   c                 c  st   t  }t }|| |i | z,dV  W || t i || |rp|  n$|| t i || |rn|  0 dS )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   rp  r   Zchromium_event_logZchromium_start_timer=   r=   rM   chromium_event_timed  s8    
rq  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 calledrC   scoperg   rT   c                 G  s$   t d urt  jd8  _| j| j= d S ry   )CleanupManagerrW   rs  rT   r  r   r=   r=   rM   __call__  s    zCleanupHook.__call__c                 C  s,   || vsJ t  jd7  _|| |< t| |S ry   )rt  rW   rr  )rs  rT   r  r=   r=   rM   r    s    zCleanupHook.createN)rJ   rK   rL   r   re   rv  r   r  r=   r=   r=   rM   rr    s   
rr  c                      s*   e Zd ZU dZded<  fddZ  ZS )rt  r   zClassVar[CleanupManager]instancec                   s&   | j | D ]
}|  q
t | d S rZ   )r   r,  rS  )r  rV  hookr.  r=   rM   rS    s    zCleanupManager._remove_id)rJ   rK   rL   rW   re   rS  r0  r=   r=   r.  rM   rt    s   
rt  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   yr=   r=   rM   clone_tensor  s    r  dtypec             	     s<  t | r| S  fdd}t  | jjdkrF|| W  d   S | jtju rtj||  || 	 | j
|  dW  d   S t| r| jtjtjhv r|  }|  }n|  }|  }tj||||||  | j
| jdW  d   S tdd t|  |  D }| jr6t|d	 f| }ntj|d	  pJ| j| jd
}|  |  d	 |   }||  |  | zJ| | !  | j"r|#| j$ | j"r| j%durt&| j% d|_%W n* t'y   ||  Y W  d   S 0 t(| dr| j)* |_)|W  d   S 1 s.0    Y  dS )zcopy while preserving stridesc                   sV   t | }| jr|| j | jr<| jd ur<t| j d|_t| drR| j	 |_|S )Nr  _dynamo_dynamic_indices)
r   ry  r|  rz  r{  r}  clone_inputr   r  copyr~  r  r=   rM   torch_clone  s    

z clone_input.<locals>.torch_cloneZxlaN)is_coalesced)layoutc                 s  s   | ]\}}|d  | V  qdS )r0   Nr=   )rp   shapestrider=   r=   rM   rr   '  s   zclone_input.<locals>.<genexpr>    )r  devicer  r  )+r?   r   no_gradr  r-  r  Z
sparse_cooZsparse_coo_tensorZ_indicesrO   r  r  r#   Z
sparse_csrZ
sparse_bsrZcrow_indicesZcol_indicesZccol_indicesZrow_indicesZsparse_compressed_tensorr   r_   zipsizer  Zis_quantizedZempty_quantizedemptyr  data_ptrZelement_sizeZas_strided_copy_ry  r|  rz  r{  r}  r  r   r   r  r  )r   r  r  Zcompressed_indicesZplain_indicesZneeded_sizeresultZcache_line_offsetr=   r  rM   r    sb    




r  c                 C  s   t | tu rft| }| D ]D\}}t|tr<t|||< qt|tjsTJ t |t|||< q|S t	| }t
t|D ]$}t|| tjrzt|| ||< qz|S rZ   )r-  dictr   r]  r^  clone_inputsr   r  r  r   ranger  )example_inputsresr   r   rl  r=   r=   rM   r  D  s    
r  ztorch.Tensor)r  c              
   C  sd   z|    W nR ty^ } z:ddlm} tddt| }|d| |W Y d }~n
d }~0 0 d S )Nr0   )	SkipFramez\(.*r;  z(torch.compile cannot be run in context: )r  r   r/  r  resubr   )r  r  r  Zfunctorch_subclass_namer=   r=   rM   skip_frame_if_in_functorch_modeW  s    r  c                  c  sB  t jj} t jjj}| h |  B t t j }t	| t j
 rTt t j
 }W d    n1 sh0    Y  W d    n1 s0    Y  zXd V  W t jj 2 t j| t j
 rt j
| W d    n1 s0    Y  nTt jj 4 t j| t j
 rt j
| W d    n1 s20    Y  0 d S rZ   )r   _CZ_DisableFuncTorchr?  Z_python_dispatchZ_disable_current_modesry  randomget_rng_stater  rB  is_availableset_rng_state)Zdisable_functorchZdisable_current_modes	rng_statecuda_rng_stater=   r=   rM   preserve_rng_stated  s"    

L
,r  c                 C  s&   t | tjjjtjjjtjjtjjfS rZ   )	r]  r   jitZ_traceZTopLevelTracedModule_scriptZRecursiveScriptModuleZScriptFunctionZScriptModule)Zmodel0r=   r=   rM   is_jit_modelv  s    r  c                 C  st   t | r| S ztj| |W S  tyn   ztj| W  Y S  tyh   |rZtd n
td Y n0 Y n0 d S )Nz	jit errorz0Both torch.jit.trace and torch.jit.script failed)	r  r   r  tracer9  scriptrb   r:  error)modelr  r  r=   r=   rM   torchscript  s    r  c              	   C  s*   zt | W S  ttfy$   Y d S 0 d S rZ   )ry  getfilerG  OSErrorrY  r=   r=   rM   r    s    r  c                 C  s   t t| S )zLTest if an object is a namedtuple or a torch.return_types.* quasi-namedtuple)is_namedtuple_clsr-  r  r=   r=   rM   is_namedtuple  s    r  c                   s   zt  trt dd}|dv r&W dS tt ddtrtt ddrtdd  jD }|tfkrlW dS |rt fd	d|D rW dS W n ty   Y n0 d
S )zhTest if an object is a namedtuple or a (torch.return_types|torch.autograd.forward_ad).* quasi-namedtuplerK   N)torch.return_typesztorch.autograd.forward_adT_fields_makec                 s  s   | ]}|t ur|V  qd S rZ   )r   rp   tr=   r=   rM   rr     r   z$is_namedtuple_cls.<locals>.<genexpr>c                 3  s"   | ]}t |o j|ju V  qd S rZ   )r  __new__r  r\   r=   rM   rr     s   F)
issubclassr^  getattrr]  callable	__bases__anyrG  )rU   modulebasesr=   r\   rM   r    s$    


	
r  z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sLJ | t|t	| j
}i }t|D ]0}|d dkrltt|||rlt||j||< qlt|| j
ksJ 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>.MarkerrP   indexNrJ   rK   rL   re   r=   r=   r=   rM   Marker  s   
r  r  r   r+  )r   )slicer  r^  r   r  r=  	dataclassrK   ro   r  n_fieldsdirr]  r  r  r  r  r]   )rU   r  rY  fieldsrT   r=   r=   rM   namedtuple_fields  s    
r  c                   s   t  X t t j t j r4t t j  dd t| 	 | 
 D W d    n1 sf0    Y   fdd}|S )Nc                 S  s   g | ]}||j t|fqS r=   )_versionr   ry  )rp   paramr=   r=   rM   r     s   z%checkpoint_params.<locals>.<listcomp>c                    sr   t  V t j t j r,t j  D ]\} }}| j|kr0| | q0W d    n1 sd0    Y  d S rZ   )r   r  r  r  rB  r  r  r  )r  rA  original_valuer  r  saved_stater=   rM   restore  s    


z"checkpoint_params.<locals>.restore)r   r  ry  r  r  rB  r  ru   rv   
parametersbuffers)gmr  r=   r  rM   checkpoint_params  s    

$	r  c                 C  sh   t j rt jj}nt}|  t  t d t	 }t
|D ]}| | }|  q@t	 }||| fS )Ni9  )r   rB  r  synchronizerK  gcZcollectZmanual_seedr   perf_counterr  )r  r  timesr  t0r+  r  t1r=   r=   rM   timed  s    


r  c                 C  s    t dd t|| dD S )Nc                 s  s   | ]}|j V  qd S rZ   )Zis_cudarp   r   r=   r=   rM   rr   	  r   z check_is_cuda.<locals>.<genexpr>T)allru   rv   r  )r  r  r=   r=   rM   check_is_cuda	  s    r  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 )Nr0   c                 S  s   g | ]}d | qS r  r=   rp   rl  r=   r=   rM   r   	  r   z rot_n_helper.<locals>.<listcomp>r_  zlambda r  z: ()Zrot_Z_helper)r  reversedevalrn   rJ   )rB  varsZrotatedr  r=   r=   rM   rot_n_helper	  s    "r  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pFt | tthB S rZ   )r\  r^  	frozensetr  ro   is_safe_constantr]  enumEnumr-  r   Sizerd  _GenericAliasr  GenericAliasr  r  r  r=   r=   rM   r  2	  s     	r  c                   C  s   ddhS Nr   r0   r=   r=   r=   r=   rM   common_constantsD	  s    r  z-TypeGuard[Union[torch.SymBool, torch.SymInt]]c                 C  s(   t | tjtjfo&t | jtjjjj S rZ   )	r]  r   ZSymBoolSymIntnodenestedr)  Z
nested_intZNestedIntNoderf  r=   r=   rM   is_torch_symN	  s    r  c                 C  s~   ddl m} t j o||   p||  r:tj	 p|| 
 rNtj	 p||  rbtj	 p|||p|td o|| t v S )Nr0   )is_from_defaultsz5pytorch/dynamo:enable_unspecialize_zero_one_plain_int)sourcer  r"   r]   Z#force_unspec_int_unbacked_size_likeguard_sourceis_localis_specialized_nn_moduler;   Zallow_unspec_int_on_nn_module"is_unspecialized_builtin_nn_moduleZis_unspecialized_nn_moduler$   r  )r   r  r  r=   r=   rM   is_int_specialization_caseT	  s"    	
r  c                 C  s   ddl m}m}m} t| |rf|  sf|  }|  }t|p\t	j
 o\t|tu o\t|| }|sf| S t| |r~||  S | S )Nr0   )ConstantVariableLazyVariableTrackerSymNodeVariable)	variablesr  r  r  r]  is_realizedZoriginal_sourcer  r  r;   Zspecialize_intr-  rP   r  r  Zevaluate_expr)r  r  r  r  r  r   Zis_symnode_vtr=   r=   rM   specialize_symnodes	  s    


r  c                 C  s*   ddl m} t| } t| |r&|  S | S )Nr0   r  )r  r  r  r]  as_python_constant)r  r  r=   r=   rM   guard_if_dyn	  s
    
r  c                 C  s   t dd t| | D S )Nc                 s  s   | ]}|  V  qd S rZ   )is_python_constantr  r=   r=   rM   rr   	  r   z&check_constant_args.<locals>.<genexpr>)r  ru   rv   r   rJ  r=   r=   rM   check_constant_args	  s    r  c                 C  s^   ddl m} ddlm} d}t| | D ](}t||rD|d7 }q,t||s, dS q,|dkS )Nr0   r   UnspecializedPythonVariabler   F)Zvariables.constantr  variables.tensorr  ru   rv   r   r]  )r   r   r  r  Zunspec_countr   r=   r=   rM   check_unspec_python_args	  s    


r  c                 C  s>   ddl m} t| | D ]}| st||s dS qdS )Nr0   r  FT)r  r  ru   rv   r   r  r]  )r   r   r  r   r=   r=   rM   check_unspec_or_constant_args	  s
    r	  c                   s.   ddl m  t fddt| | D S )Nr0   NumpyNdarrayVariablec                 3  s   | ]}t | V  qd S rZ   )r]  r  r
  r=   rM   rr   	  s   z+check_numpy_ndarray_args.<locals>.<genexpr>)r  r  r  ru   rv   r   rJ  r=   r
  rM   check_numpy_ndarray_args	  s    r  ztype[KeysView[Any]]	dict_keysztype[ValuesView[Any]]dict_valuesztype[ItemsView[Any, Any]]
dict_itemsodict_valuesztype[Iterator[Any]]tuple_iteratorrange_iteratorc                 C  s   h | ]}t |r|qS r=   r  rp   methodr=   r=   rM   	<setcomp>	  s   r  c                 C  s   h | ]}t |r|qS r=   r  r  r=   r=   rM   r  	  r   c                 C  s   h | ]}t |r|qS r=   r  r  r=   r=   rM   r  	  r   c                 C  s   h | ]}t |r|qS r=   r  r  r=   r=   rM   r  	  r   c                 C  s   t | tsJ t| S rZ   )r]  r  r   r'  r=   r=   rM   builtin_dict_keys	  s    r  c                   sb   t  tsJ t ttfr$  S t  trF fddt D S  fddt D S d S )Nc                   s   g | ]}|t  |fqS r=   )r   rP  r   r  r=   rM   r   	  r   z'get_items_from_dict.<locals>.<listcomp>c                   s   g | ]}|t  |fqS r=   )r  rP  r   r  r=   rM   r   	  r   )r]  r  r\  r   r   r   r  r=   r  rM   get_items_from_dict	  s    
r  c                 C  s   t | }tjj| |S rZ   )
object_newr   r  Moduler  )rU   rY  r=   r=   rM   nn_module_new	  s    r  c                 C  s   t tj| dS ry   )rv  reduceoperatormul)itr=   r=   rM   product	  s    r   c                 C  s   |   \}\}}|||  S rZ   )
__reduce__)r  r  r+  rY  r  r=   r=   rM   tuple_iterator_getitem	  s    r"  c                 C  s   t jtj| S rZ   )r   _dynamodisabler=  r  r\   r=   r=   rM   dataclass_fields	  s    r%  ztuple[int, int, int]c                 C  s4   |   \}\}}|j|pd }|j}|j}|||fS r|   )r!  r  r  r  )Z
range_iterr+  Z	range_objZ	maybe_idxr  r  r  r=   r=   rM   normalize_range_iter	  s
    r&  c                 C  s
   |  |S rZ   )Zas_subclass)r  rU   r=   r=   rM   to_subclass
  s    r'  c                 C  s.   t }t| trt}tt|| ||d S ry   )r  r]  r   nextru   islicer   )r!  rB  
dict_classr=   r=   rM   dict_keys_getitem
  s    
r+  c                 C  s2   | j j}| j}|rdnd}| d| d| }|S )NLGz["z"].)r/  rJ   rT   )r   rS  rT   r  rs  Z
local_namer=   r=   rM   	enum_repr
  s
    r.  c                 C  s:   || j d< t jj}tjjj	|| }r6|| j d< d S )Nexample_valueZunbacked_bindings)
metar"   r]   	fake_mode	shape_envr   r   experimentalsymbolic_shapesZcompute_unbacked_bindings)r  r/  r2  Zsymbol_to_pathr=   r=   rM   set_example_value
  s    

r5  c                 C  sP   |   jjd}t|sLddlm} ddlm} |dt	|dg |j
d |S )Nr/  r0   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  r0  r]   r?   r;  r7  r/  r  rg   
DYNAMO_BUG)vtfake_tensorr7  r  r=   r=   rM   _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 ]l}|	rt||r҈ t	|u r|d  S qf|t
j|| gi }|
d u r|}
qf|t
j|||
gi }
qf|
d u r|d}
|
S )Nr0   )BuiltinVariabler  TensorVariableVariableTrackerc                 3  s&   | ]}|  o|   kV  qd S rZ   )r  r  r  searchr=   rM   rr   G
  s   z iter_contains.<locals>.<genexpr>FT)r  r=  r  r>  r?  r  r  r  r]  r<  r  eqcall_functionor_)r   rA  txZcheck_tensor_identityr=  r  r>  r?  Zfound_constZmust_check_tensor_idfoundr   checkr=   r@  rM   iter_contains>
  s2    




rH  z?TypeIs[Union[torch.Tensor, torch.nn.Module, MethodWrapperType]])r   rj   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   r=   r=   rM   	key_is_idg
  s    rI  c                 C  s   dd |   D S )Nc                 S  s    g | ]}t |rt|n|qS r=   )rI  rO  r   r=   r=   rM   r   o
  r   zkey_to_id.<locals>.<listcomp>)r   rf  r=   r=   rM   	key_to_idn
  s    rJ  c                  s   ddl m} t| ttfr|d fdd| D }t| trHd| dS t| tsVJ t| dkrnd| d	S d| d
S nNt| tjrt	|  d
ddS || r| jS t| trdd }|| S | S d S )Nr0   )is_builtin_callabler  c                 3  s   | ]}t | d V  qdS rS  N
const_reprrp   rn  rM  r=   rM   rr   v
  r   zconst_repr.<locals>.<genexpr>[](z,)r  rM  'r;  c                 S  s(   | j }|j}|dkr|jS |d |j S )Nbuiltins.)r/  rK   rL   )r-  klassr  r=   r=   rM   fullname
  s
    zconst_repr.<locals>.fullname)Ztrace_rulesrK  r]  r   r^  rn   r  r  r  r.  replacerJ   r-  )r   rS  rK  Z
elems_reprrX  r=   rM  rM   rO  r
  s"    

rO  c                  s$   d  fdd| D }d| d S )Nr  c                 3  s   | ]}t | d V  qdS rL  rN  rP  rM  r=   rM   rr   
  r   z!dict_keys_repr.<locals>.<genexpr>rQ  rR  rn   )Z
const_keysrS  Zkeys_strr=   rM  rM   dict_keys_repr
  s    r[  Z
__dict_key)UnsupportedFakeTensorExceptionc                 C  s   | dt | d| jj S )Nr+  Z_c)rO  outputr   )rE  rootrY  r=   r=   rM   get_safe_global_name
  s    r_  r  c                 G  s   |D ]}| |v r dS qdS rE  r=   )r  
containers	containerr=   r=   rM   is_in
  s    rb  )requires_suffix)prefixrj   c                G  sX   |st | g|R  s| S t D ]*}|  d| }t |g|R  s |  S q tddS )zm
    Return a name that starts with `prefix` and is not in any of the
    `containers` (e.g., map, set).
    r+  ZunreachableN)rb  ru   rW   AssertionError)rd  rc  r`  rl  	candidater=   r=   rM   get_unique_name_wrt
  s    
rg  c              
   C  sn   z|  W S  t yh } zHddlm} d|j d}t| |dt|j|g |d W Y d }~n
d }~0 0 d S )Nr0   r  zEncountered exception (z!) during fake tensor propagation.z!Fake tensor propagation exceptionr  )r\  r/  r  reasonrb   r5  rg   )r  r  r  msgr=   r=   rM   wrap_fake_exception
  s    
rj  c                   sB   t jj|  t fddW  d    S 1 s40    Y  d S )Nc                     s
   t  S rZ   )r  deepcopyr=   r  r=   rM   r   
  r   z)deepcopy_to_fake_tensor.<locals>.<lambda>)r   r  r;  ZFakeCopyModerj  )rY  r1  r=   r  rM   deepcopy_to_fake_tensor
  s    rl  c                 C  s   t t t | | S )z+
    Calculate root mean squared error
    )r   sqrtmeanZsquare)rT  r  r=   r=   rM   rmse
  s    ro  g-C6?T)force_max_multiplierc                   sT  du rt tttjtjjtjfrt 	tttjfsVJ dt	 dt		 t
t
	krrd dS t
t
	kot f	ddt	D S t	jdkrtj	jj d	S t trt 	ts J t t	 ks>J d
t  dt	  t D ]D}t| 	| |  dsJd|  dS qJdS t trt 	tsJ tt	ksJ dt dt	 dS t tjtfrt tjjrJ t 	tjjrJ dd 

fdd	fD \	jrf	jsVJ  	 	t 	tjsJ dt	 dt		 r
j	jkrdj	j dS jtjkr
rdS tjjtjd	jtjdd}|sd |S  r tj 	 tj 	tj	ddrJd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rd}) * s	) * s) * rtjj	jd	||drdS t+' }t,)|r:t#$d t+	' }	fdd}| }||| d   k}|srt,)|rt,)|rtj-j.j/j0sd}|sЈd!||	1 	j| |S rdS d" dS n`t t2t3t	dttj4fr:rdS 	k}|s6d#t		 |S t5sNt6rrpt5	spt6	sp' 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 sJ t 	fd'dj9 D S t:d(t	j dS ))z-Check correctness to see if ref and res matchNztype mismatch r   zLength mismatchFc                 3  s4   | ],\}}}t ||| d V  qdS )	log_error(use_larger_multiplier_for_smaller_tensorrp  N)same)rp   ZaiZbiZ	fp64_refi)	cos_similarity	equal_nanexact_dtyperp  ignore_non_fprr  relax_numpy_equalitytolrs  r=   rM   rr   
  s   zsame.<locals>.<genexpr>ZQuestionAnsweringModelOutputrq  zkeys mismatch z == )	ru  rz  rv  rw  ry  rx  rr  rs  rp  zAccuracy failed for key name %sTzelements mismatch c                 S  s   t | tjr| S t| S rZ   )r]  r   r  tensorr  r=   r=   rM   	to_tensor:  s    zsame.<locals>.to_tensorc                 3  s   | ]} |V  qd S rZ   r=   )rp   r  )r}  r=   rM   rr   =  r   zdtype mismatch %s, %sr  )ZatolZrtolrv  z+Accuracy failed: uint8 tensor did not matchr   gư>)ZdimZ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} r8 dkr8d} nZrN dkrNd} nD dk sjdkrjd	 jd
   krdksn dkrd} | S )N      $@g      @g       @
   i  g       @r      r_  r0   g{Gz?)r  r   rp  bfloat16Znumelndimr  )
multiplier)rp  fp64_refrT  r  rz  rs  r=   rM   get_multiplier  s0    


	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ru  rz  rv  rw  ry  rx  rr  rs  )ZMaskedLMOutputZSeq2SeqLMOutputZ!CausalLMOutputWithCrossAttentionsZLongformerMaskedLMOutputZ	InstancesZSquashedNormalZBoxesZNormalZTanhTransformZFooVariablec                 3  s>   | ]6}t t|t|t| 	
d V  qdS )r  N)rt  r  rp   r   )ru  rv  rw  r  rx  rr  rT  ry  r  rz  rs  r=   rM   rr     s   zunsupported type: );r]  r   r^  rc   rI  r   r  ZParameterListr  r-  r  r  r  rJ   rt  Zlossr  r  r   r  r  floatr  r>   Z	is_sparseZto_denser  r   Zallclosetorn  flattenrq  Z
functionalZcosine_similarityrb   r5  detachcpur  rr  isnanr  ro  mathr4  r;   cppZinject_relu_bug_TESTING_ONLYr  rg   rP   r  ro  rs  r  	as_tensor__dict__r   )rT  r  r  ru  rz  rv  rw  ry  rx  rr  rs  rp  r   rZscoreZ	loose_tolZ	ref_errorZ	res_errorr  r  Zpasses_testr=   )ru  rv  rw  rp  r  rx  rr  rT  ry  r  r}  rz  rs  rM   rt  
  sx   ,


.*



#
	

 rt  c                 C  s,   | j dd }d| j d| d| j dS )N/r_  rT  z' (r   r  )r  splitr,  r.  )r0  Zshort_filenamer=   r=   rM   format_func_info  s    r  c                  c  sF   t j} tjt _t j}tjt _zd V  W | t _|t _n| t _|t _0 d S rZ   )r;   Zrecompile_limitra  r  Zaccumulated_recompile_limit)priorZprior_acc_limitr=   r=   rM   disable_cache_limit  s    r  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 )NZrun_z%Y_%m_%d_%H_%M_%S_%fz-pid_)datetimenowstrftimerg   r  getpidr  rn   )root_dirdir_namer=   r=   rM   _get_debug_dir.  s    
r  c                  C  s   t j} t| S rZ   )r;   r"  r  )Z
debug_rootr=   r=   rM   r  :  s    r  c                 C  sj   d| j v r"t| j d r"| j d S |rbddlm} ddlm} |dt| d|  dg |jd	 nd S d S )
Nr/  r   r  r0   r6  z Missing FakeTensor example valuez,`FakeTensor` example value was required for z but not available.r8  )r0  r?   Ztorch._dynamo.excr  r;  r7  rg   r9  )r  requiredr  r7  r=   r=   rM   extract_fake_example_value?  s    

r  c                 C  s   t | |ju sJ | S rZ   )r@   r1  )r  rE  r=   r=   rM   ensure_graph_fakeQ  s    r  c                   s$   dd fdd}t jj||S )Nztorch.fx.NoderB  c                   s   | j dkr d| jvr t|  S | j dkrjd| jvrj| jjjv sFJ jj| j }t|tjj	sfJ |S | jd } st|tj
rt|S |S )NrC  r/  get_attr)r@  r0  get_fake_valuetargetr]  
nn_modulesr]  r   r   GraphModuler  r  )rB  r  r   allow_non_graph_fakerE  r=   rM   visitW  s    

z)get_fake_values_from_nodes.<locals>.visit)r   r   r  map_arg)rE  r?  r  r  r=   r  rM   get_fake_values_from_nodesV  s    r  c              
     sp  ddl m} ddlm}m}m}m}m} j}	dj	v rPt
j	d rPj	d S tjjf|\ tjjjs|tjjjrtti |}
dd |
D }ng }
i }d|	d	krt dkrt d tjjrt d jft dd   |	d
kr8jjj tr,tdr,   tjj!dv sXt"dd  D rjtdd  D  znjP t# ( t$ fdd}W d   n1 s0    Y  W d   n1 s0    Y  W nH |y    Y n2 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 rRdg}ndg}|dt0|j*d|j* d|d nzt|tj'j(j1rtjjj2s|dt0|j*d|j* ddgd n"|dt0|j*d|j* ddgd nt|tj'j(j3rr|j*}	d}t|	tj4j5rPtj67|	j8j!|	j8j9}|durP|\}}d| d | d!| d"}|d#d$|j* d| d%gd nt|tj:j;j<j=r||j>t0|d&d'nZt||r||j>|jd |n8t|t?rd(t0|v r|d)d*j d+| dg d |t0|@|jAdW Y d}~n
d}~0 0 |sBtBCtjDtEjFtGd,|}tjjjsZtjjjrljjHI|
| |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   )ValueRangeErrorr0   )TorchRuntimeErrorr  Unsupported	UserErrorUserErrorTyper/  c                 S  s    i | ]}t |rt||jqS r=   )r?   rO  r  r  r=   r=   rM   r    s   z"get_fake_value.<locals>.<dictcomp>Ncall_methodcall_moduleZ_initialize_hook)Zinterpolate
is_integerZwrapped_gradientc                 s  s   | ]}t |tV  qd S rZ   )r]  complex)rp   ar=   r=   rM   rr     s   z!get_fake_value.<locals>.<genexpr>c                 s  s2   | ]*}t |tjr&|jjd ur&t|n|V  qd S rZ   )r]  r   ZSymFloatr  hintr  r  r=   r=   rM   rr     s   


c                     s   t j S rZ   )run_noder]  r=   r   r   nnmoduler  rE  r=   rM   r     r   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.r8  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 fixZconstrain_as_size_example)Z	case_nameargumentz&TypeError when making fake tensor callz
TypeError z: )rE  )JZtorch.utils._sympy.value_rangesr  r/  r  r  r  r  r  r@  r0  r?   r  r   r   r   r#  r;   Zuse_graph_deduplicationZtrack_nodes_for_deduplicationr1   r  r]  r  r  rl  r1  r^  r]  r  r  r  r   Z_infer_parametersrT   r  r   rj  r   	__cause__r  r;  ZDataDependentOutputExceptionfuncopsZatenr  rQ  Z_local_scalar_denserg   ZDynamicOutputShapeExceptionZ capture_dynamic_output_shape_opsZUnsupportedOperatorExceptionr|  r}  r  Z_dispatch_pystubZ_schemaZoverload_namer   r3  r4  ZGuardOnDataDependentSymNodeZCONSTRAINT_VIOLATIONrG  with_traceback__traceback__pytreeZtree_map_onlyr  rv  partialr  Zregion_trackerZtrack_node_mutations)r  rE  r  r  r  r  r  r  r  r@  Zflat_args_kwargsZid_to_initial_versionZret_valr  causer  Zimport_suggestionZmaybe_pystubr  ctxr+  r=   r  rM   r  k  s   	
&"

J










,r  c                   C  s   t tdd S )Nr   )r  _current_noder=   r=   r=   rM   get_current_node2  s    r  c                 c  s*   t  }| t_zd V  W |t_n|t_0 d S rZ   )r  r  r   )r  oldr=   r=   rM   set_current_node6  s
    r  c           
        s4  j t  fdd}ddlm} z$dkr\j i W W  d   S dkrt d jsdd	lm} |d
d|dg d t d j dd i W W  d   S dkr|dusJ | i W W  d   S dkr | j	jW W  d   S dkrTdj
v s:J j
d W W  d   S W n ttfy } zDdd	lm} g }	t|trdg}	|dd|||	|d W Y d}~nXd}~0  |y    Y n< ty } z"t|||j|W Y d}~n
d}~0 0 W d   n1 s0    Y  tdS )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  r   r   r  r@  r=   rM   make_error_messageS  s    z$run_node.<locals>.make_error_messager0   )r  rC  Nr  r   r  z/Missing attribute when running call_method noder;  zattribute not definedr8  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  r/  r  r  r   r  r  output_graphZget_submoduler0  r  r\  r]  r9  r   r  r  re  )
tracerr  r   r   r  r  r  r  r  r  r=   r  rM   r  @  s^     2

8r  c           
   
     s  ddl m}  j}| |v r"||  S | j}tjj| j| j	f fdd\}}|dkrjd| j
v rj| j
d jS |dkr jj| j }t|st|}q||i | nd}zt | |||}||| < W n: ty }	 z"|t|	|	jdW Y d}	~	n
d}	~	0 0 |S )	z
    Run the actual computation represented by `node` and return the result.
    This will execute any dependent nodes in the graph as well.
    r0   )r  c                   s
   t |  S rZ   )get_real_valuer  r  r=   rM   r     r   z get_real_value.<locals>.<lambda>r  Zgraphargr  N)r/  r  Zreal_value_cacher@  r   r   r  r  r   r   r0  Zexampler  r  r  r  r  rk  r  r   rg   r  r  )
r  r  r  cacher@  r   r   Z	nn_module
real_valuer  r=   r  rM   r    s.    

,r  c                   s   ddl m m}  fdd}|  D ](\}}||r$J d| d|| q$|  D ](\}}||rVJ d| d|| qVd S )Nr   )FakeTensorConfigr?   c                   s(    j r dd l}d|| j S d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_listZ_debug_trace)r  r  r  r=   rM   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  r?   Znamed_buffersZnamed_parameters)r  r?   r  rT   bufferr  r=   r  rM    assert_no_fake_params_or_buffers  s    

r  r  c                 C  s   | j  d| j S )z9
    Returns the fully qualified name of the object.
    rV  )rK   rL   r  r=   r=   rM   fqn  s    r  c                 C  s   t jjjr| S |S d S rZ   )r   r#  r;   Zassume_static_by_default)Zcount1Zcount2r=   r=   rM   ifdynstaticdefault  s    
r  ztypes.ModuleTyper  c                 C  s\   t ttjtt| jD ]8}|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   r+  rV  N)r  r  listdirr  r6  r   rg   __file__r   	importlibimport_modulerJ   )r  r2  r=   r=   rM   import_submodule  s    "r  rf  c                 C  s   t t| S rZ   )class_has_getattributer-  rf  r=   r=   rM   object_has_getattribute  s    r  c                 C  s   t | d}|||< d S )Nr  )r   __getattribute__)rY  rT   r   r!  r=   r=   rM    object_setattr_ignore_descriptor  s    r  r-  r\   c                 C  s6   zt t| dtjrW dS W n ty0   Y n0 dS )Nr  TF)r]  ry  rz  r  r  AttributeErrorr\   r=   r=   rM   r    s    

r  )r   ignore_nn_module_getattrc                 C  sF   zt t| d}W n ty*   d }Y n0 |rB|tjjju rBd }|S )N__getattr__)ry  rz  r-  r  r   r  r  r  )r   r  Z
getattr_fnr=   r=   rM   get_custom_getattr  s    
r  c                   @  s   e Zd ZdZdZdZdS )TensorStaticReasonrH   r  r   N)rJ   rK   rL   	PARAMETER
NOT_TENSORNN_MODULE_PROPERTYr=   r=   r=   rM   r    s   r  rh  c                 C  s<   | t jkrdS | t jkrdS | t jkr*dS td|  d S )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  re  r  r=   r=   rM   tensor_static_reason_to_message  s    


r  zUnion[torch.Tensor, Any]r!   z)tuple[bool, Optional[TensorStaticReason]])r{  	is_tensortensor_sourcerj   c                 C  sn   ddl m} |  s$|  r4tjr4dtjfS t	| t
jju sL||r\tjr\dtjfS |sjd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.
    r0   ))is_from_unspecialized_param_buffer_sourceT)FN)r  r  r  r  r  r;   Z&force_nn_module_property_static_shapesr  r  r-  r   r  r  Zforce_parameter_static_shapesr  r  )r{  r  r  r  r=   r=   rM   tensor_always_has_static_shape  s$    




r  c                   s    fdd}t |S )Nc                    sj   zddl m }  W n$ ty4   dtt   Y S 0 dd jjD }| |g dd}t jjj	|S )Nr   )rs   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 r=   )r@  rT   r  r   r   )rp   rB  r=   r=   rM   r   =  s   z<lazy_format_graph_tabular.<locals>.inner.<locals>.<listcomp>)opcoderT   r  r   r   rk   )
rs   rt   rg   r*   graphr?  r)   forward__code__r  )rs   Z
node_specsZ	graph_strr   r  r=   rM   inner4  s    z(lazy_format_graph_tabular.<locals>.innerr9   )r   r  r  r=   r  rM   lazy_format_graph_tabular3  s    r  c                 C  s,   |  d| d| d| dt |   d
S )Nr   z line z 
rl   )disBytecode)rd  rT   r2  line_nor0  r=   r=   rM   format_bytecodeH  s    r  Z_forward_pre_hooksZ_forward_hooksZ_backward_pre_hooksZ_backward_hooks)Z_state_dict_pre_hooksZ_state_dict_hooksZ_load_state_dict_pre_hooksZ_load_state_dict_post_hooksc                   C  s    t tjjjjpt tjjjjS rZ   )r  r   r  modulesr  Z_global_backward_hooksZ_global_backward_pre_hooksr=   r=   r=   rM   nn_module_has_global_hooksW  s    
r  c                 C  s   g }| o| o| }|s|r(| t |s0|r:| t |rH| t g }|D ],}t| |g }|D ]}	||	 }
||
 qdqP|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_namesr  r   )r  check_forward_hookscheck_backward_hookscheck_state_dict_hooksZhook_dicts_to_checkZcheck_all_hooksZ	all_hooksZhook_dict_namehooks	hook_namerx  r=   r=   rM   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  r=   r=   rM   nnmodule_has_hooks  s    	r  c                 C  sf   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 dS )z0Convert tensor and tnp.ndarray to numpy.ndarray.T)forcec                 s  s   | ]}t |V  qd S rZ   )to_numpy_helperrp   rY  r=   r=   rM   rr     r   z"to_numpy_helper.<locals>.<genexpr>N)r?   r]  tnpr  r  r{  r   r  numpyr^  r   r-  rf  r=   r=   rM   r    s    
r  c                 C  s`   t dusJ t| t jr"t| S t| tjr4| jS t| ttfrXt	| dd | D S | S dS )zeConvert tnp.ndarray to tensor, leave other types intact. If a list/tuple, loop through it to convert.Nc                 s  s   | ]}t |V  qd S rZ   )numpy_to_tensorr  r=   r=   rM   rr     r   z"numpy_to_tensor.<locals>.<genexpr>)
ri  r]  r  r   r  r  r{  r^  r   r-  rf  r=   r=   rM   r    s    
r  c                   @  s*   e Zd Zdd ZddddZdd Zd	S )
numpy_to_tensor_wrapperc                 C  s   || _ d| j j | _d S NZwrapped_r;  rJ   )r  r;  r=   r=   rM   r    s    z numpy_to_tensor_wrapper.__init__rg   rx   c                 C  s   d| j j dS )Nz<Wrapped function <original >>r  r  r=   r=   rM   __repr__  s    z numpy_to_tensor_wrapper.__repr__c                 O  s   | j |i |}t|S rZ   )r;  r  r  r   r   r   r=   r=   rM   rv    s    z numpy_to_tensor_wrapper.__call__N)rJ   rK   rL   r  r  rv  r=   r=   r=   rM   r    s   r  c                 C  sF   t | tjrt| |}t|S t | tjrBtt| |}t|S d S rZ   )r]  r  r  r  r  r   r  )rY  rT   r   r=   r=   rM   numpy_attr_wrapper  s    
r  c                   @  s4   e Zd ZdZddddZd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.rg   r  c                 C  s   || _ d| j  | _d S r  )r  rJ   )r  r  r=   r=   rM   r    s    znumpy_method_wrapper.__init__rx   c                 C  s   d| j  dS )Nz<Wrapped method <original r  r  r  r=   r=   rM   r    s    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  r  r  r  )r  r   r   rY  Zmethod_callabler   r=   r=   rM   rv    s    
znumpy_method_wrapper.__call__NrJ   rK   rL   r   r  r  rv  r=   r=   r=   rM   r    s   r  c                   @  s4   e Zd ZdZddddZdddd	Zd
d ZdS )numpy_operator_wrapperzQImplements dunder methods for tnp.ndarray via functions from the operator libraryzCallable[..., Any])r@  c                 C  s   || _ d|j | _d S r  )r@  rJ   )r  r@  r=   r=   rM   r    s    znumpy_operator_wrapper.__init__rg   rx   c                 C  s   d| j  dS )Nz<Wrapped operator <original r  )rJ   r  r=   r=   rM   r    s    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 rZ   )r]  r   r  r  r  r  r=   r=   rM   rr     s   z2numpy_operator_wrapper.__call__.<locals>.<genexpr>)r@  r  r  r=   r=   rM   rv    s    
znumpy_operator_wrapper.__call__Nr   r=   r=   r=   rM   r!    s   r!  c                 C  s   t | ts| S | jrg }|  D ]4}t |tjrJ||jj	|jj
 q || q g }|  D ]4}t |tjr||jj	|jj
 qb|| qbn|  }|  }tj||| j| j| jd}|  |S )N)r  r  r{  )r]  r>   Z_has_symbolic_sizes_stridesr  r   r  r   r  r2  Z	size_hintexprr  Zempty_stridedr  r  r{  Zzero_)r   r  rn  r  r  r=   r=   rM   defake  s0    
r#  c                 O  s   | |i |S rZ   r=   )r  r   r   r=   r=   rM   8_disable_side_effect_safety_checks_for_current_subtracer
  s    r$  c                 C  s   dd l }| |jjju S r|   )Ztorch.utils.checkpointr?  
checkpoint)rY  r   r=   r=   rM   is_utils_checkpoint  s    r&  c                 C  s   ddl m} | |u S )Nr   )invoke_subgraph_placeholder)Z'torch._higher_order_ops.invoke_subgraphr'  )rY  r'  r=   r=   rM   is_invoke_subgraph  s    r(  c                  K  s"   ddl m} |jtjjfi | S )Nr0    TorchHigherOrderOperatorVariable)variables.higher_order_opsr*  maker   _higher_order_opsZinvoke_subgraph)optionsr*  r=   r=   rM   build_invoke_subgraph_variable  s    r/  c                  K  sF   dd l m  m} ddlm} |j}tjjj	r4|j
}|j|fi | S )Nr   r0   r)  )Ztorch._higher_order_ops.wrapr-  wrapr+  r*  Ztag_activation_checkpointr   Z
_functorchr;   Zfunctionalize_rng_opsZwrap_activation_checkpointr,  )r.  Zhigher_order_opsr*  Zactivation_checkpoint_opr=   r=   rM   build_checkpoint_variable$  s    
r1  c                 C  sD   ddl m} t| j}| }|dkr(n|dv r<|r<t }nd}|S )Nr0   )is_dynamo_supportedr  )rB  ZxpuF)Z
eval_framer2  r   r  r-  r-   )Zdevice_typer2  r-  Zcompile_supportedr=   r=   rM   is_compile_supported7  s    r3  )rg   offsetrj   c                 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-8NrY  )errors)encoder  decode)rg   r4  Zas_utf8r=   r=   rM   _fix_offsetI  s    
r8  c                   @  s.   e Zd ZU ded< ded< ded< ded< dS )_AnchorsrP   left_end_linenoleft_end_offsetright_start_linenoright_start_offsetNr  r=   r=   r=   rM   r9  U  s   
r9  zOptional[_Anchors])segmentrj   c                   s  t jdksJ ddl}z|d|  d }W n ty@   Y dS 0 t|jdkrTd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 r6|
dv r&|||	\}}	q|||	\}}	q|	d }|t | k rx | |  }
 sx|
dvrx|d7 }t||	||S t||jrtt|j
jd }|||j
j}||\}} | | dkr|||\}}qtt|jd }|||j}t||||S t||jrtt|jjd }|||jj}||\}} | | dkrp|||\}}qLt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
    )rI      r   Nz(
z
)r0   rl   c                   s   t  |  |S rZ   )r8  )linenor4  linesr=   rM   	normalizey  s    z-_extract_anchors_from_expr.<locals>.normalizec                   sR   | t  k r*|t  |  kr*d}| d7 } q | t  k rF|t  |  k sJJ | |fS r  r  r@  colrA  r=   rM   next_valid_char~  s
    
 z3_extract_anchors_from_expr.<locals>.next_valid_charc                   s>   |d7 }| |\} }| t  k r2|t  |  k s6J | |fS ry   rD  rE  rB  rG  r=   rM   r     s     z-_extract_anchors_from_expr.<locals>.incrementc                   sB   d}| d7 } | |\} }| t  k r6|t  |  k s:J | |fS r  rD  rE  rH  r=   rM   nextline  s
     z,_extract_anchors_from_expr.<locals>.nextlinerH   z)\#z\#rQ  rS  )ra  rb  astparseSyntaxErrorr  bodyr  r]  Exprr   BinOpr   rP   left
end_linenoend_col_offsetisspacer9  	SubscriptCallr  )r>  rJ  treerC  r   rI  Z	statementr"  Z
cur_linenoZcur_colchZ	right_colZleft_linenoZleft_colZright_linenor=   rH  rM   _extract_anchors_from_expr_  sh    

 
rX  ztypes.CodeTypezdis.Instruction)r0  instrj   c                   s  t jdkrt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sJ |jjdu rd	S t j|jj }|jjdu r|S |jj	du s2|jj
du r6|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 ]V}t j| }||d 7 }t|t|  }|d
| dt||    q ||d|
 7 }t|t|  }|d
| d|
|    d}zt|}W n ty   Y n0 |du rdd |D }ndd |D }|jdkr| j|	7  _|jdkr| j|	7  _tt|D ]}tt|| D ]|}||jk rLq8||jkrh||jk rhq8||jkr||jkrq8||jkrq8|| | dkr8d|| |< q8q$dd |D }d	}tt|D ]8}|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).
    )rI      )rQ  colnoZ	end_colnor   rl   r0   Nc                   s   g | ]}t  j| qS r=   )	linecachegetliner  rstrip)rp   r@  r0  r=   rM   r     s   z.get_instruction_source_311.<locals>.<listcomp>r;  r   ~c                 S  s   g | ]}| d dqS )r`  ^)rY  rp   markerr=   r=   rM   r   3  r   c                 S  s   g | ]}t |qS r=   r   rb  r=   r=   rM   r   6  r   ra  c                 S  s   g | ]}d  |qS )r;  rZ  rb  r=   r=   rM   r   P  r   )ra  rb  r  FrameSummaryr  Z	positionsr@  r,  rQ  
col_offsetrR  r  rn   
splitlinesr  textwrapdedentr  indentr\  r]  r^  r8  r   lstriprX  re  r:  r;  r<  r=  )r0  rY  frame_summaryr  Z
orig_linesZorig_lines_dedentZ
indent_lenrj  
first_lineZstart_offset
end_offsetr>  markers	last_liner@  lineZ
num_spacesZanchorsZmutable_markersrF  rl  r=   r_  rM   get_instruction_source_311  s    


"
rr  c                 C  s   t | tjrt| dd S d S )N_dynamo_static_input_type)r]  r   r  r  r|  r=   r=   rM   get_static_address_type\  s    rt  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 rZ   )	r   r  r2   Z	get_stateZdefault_generatorr  rB  Z	set_stater  )r   ZgettersZsettersr=   r=   rM   is_rng_state_getter_or_setterc  s    ru  c                 C  s&   t | tjo$| jdko$| jjtjju S )N__get__)	r]  r  r
   rJ   __self____objclass__r   r  Z_TensorBaserf  r=   r=   rM   is_tensor_base_attr_gettert  s
    ry  c                 C  s8   zt tj| }t|tju W S  ty2   Y dS 0 d S rh  )ry  rz  r   r  r-  r  r  r  )rT   attrr=   r=   rM   is_tensor_getset_descriptor|  s
    r{  c                 C  s
   t | dS )N__torch_function__)r   rf  r=   r=   rM   is_torch_function_object  s    r}  z,torch._dynamo.variables.base.VariableTracker)r:  rj   c                 C  s   ddl m} ddlm} |  s8t| dr~t|  dr~d }t| |rVt| j	dd }nt| |rnt| j
dd }|d tjjfvS dS )Nr   )UserDefinedObjectVariable)TensorWithTFOverrideVariable
peek_valuer|  F)Ztorch._dynamo.variablesr~  Z&torch._dynamo.variables.torch_functionr  r  r   r  r]  r  Z
class_typer   r   r  Z_disabled_torch_function_impl)r:  r~  r  r  r=   r=   rM   has_torch_function  s    


r  c                 C  sD   d }d }t jj  }r2| |jv r2|j|  }|j}|j| d||dS )NF)Zstatic_shapessymbolic_contextr  )r   r   r"   Ztry_getZtensor_to_contextr  Zfrom_tensor)r  r1  r  r  Ztracing_contextr=   r=   rM   to_fake_tensor  s    

r  c                 C  s:   t |  o8t|  o8t| o8t| do8t| jdo8| jjS )N__dataclass_params__frozen)r  r  r   r   r  r  rf  r=   r=   rM   is_frozen_dataclass  s    

r  c                 G  s8   |D ]}t | |rt| |  S qt|  d| dS )zX
    Return the first available attribute or throw an exception if none is present.
    z% does not has any of the attributes: N)r   r  re  )rY  attrsrz  r=   r=   rM   get_first_attr  s    
r  c                 #  sR   | sd V  nB fdd}t jj|}|V  W d    n1 sD0    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_autogradZcompilesr0   )r   r#  r?  rB   r4  compile)Zgm_Zexample_inputs_r=   r=   rM   inner_compiler  s    zKmaybe_enable_compiled_autograd.<locals>.compiler_fn.<locals>.inner_compiler)backend	fullgraphdynamic)r   r  )r  r  r  r  r=   rM   compiler_fn  s    z3maybe_enable_compiled_autograd.<locals>.compiler_fn)r   r#  r  Z_enable)Zshould_enabler  r  r  r  r=   r  rM   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)rJ   rK   rL   r=   r=   r=   rM   Invalid  s   r  )r  r/   )r  r=   r=   rM   invalid_removeable_handle  s    r  c                 C  s>   t | tjjs| S t | tjjr$| S | j| j}| j|_|S rZ   )	r]  r   r  r  r   r  r/  r  r  )r  proxyr=   r=   rM   nn_module_proxy  s    r  c                      s$   e Zd Z fddZdd Z  ZS )	GmWrapperc                   s   t    || _|| _d S rZ   )r,  r  r  unflatten_fn)r  r  r  r.  r=   rM   r    s    
zGmWrapper.__init__c                 G  s   t |}| j| | S rZ   )r   r  r  ru  r=   r=   rM   r    s    zGmWrapper.forward)rJ   rK   rL   r  r  r0  r=   r=   r.  rM   r    s   r  ztorch.fx.GraphModule)r  c                   s   dd t | jjD tjjjrvdgks.J t|d ts@J t	|d  dd  fdd}|t
| ||n4t|\}}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  Z	steal_argF)r@  r0  r]   )rp   rl  r  r=   r=   rM   r     s   z(flatten_graph_inputs.<locals>.<listcomp>r   c                 S  s   | d t | dd   S r  rd  r  r=   r=   rM   
flatten_fn  s    z(flatten_graph_inputs.<locals>.flatten_fnc                   s   | d   g|  d  R S rZ   r=   )	flat_args)boxed_inputs_countr=   rM   r    s    z*flatten_graph_inputs.<locals>.unflatten_fn)Ztreespecc                    s&   | }D ]}| |    q |S rZ   )r[   )r   r  rl  )compiled_fnr  inputs_idx_to_clearr=   rM   wrapper!  s    z%flatten_graph_inputs.<locals>.wrapper)	enumerater  r?  r   r#  r  Zin_compiled_autograd_regionr]  r   r  r  r  Ztree_flattenrv  r  Ztree_unflattenZarg_tree_leaves)r  inputsZ
compile_gmr  Zflat_inputsspecr  r=   )r  r  r  r  rM   flatten_graph_inputs  s     


r  c                 C  s*   t | tjjrt| dsg S | jdg S )Nr0  locals_to_steal)r]  r   r   r  r   r0  r]   )Zmaybe_gmr=   r=   rM   get_locals_to_steal.  s    r  c                 C  s   || j d< d S )Nr  r0  )r  r  r=   r=   rM   set_locals_to_steal4  s    r  c                   @  s"   e Zd Zdd ZddddZdS )Litc                 C  s
   || _ d S rZ   rn  )r  rn  r=   r=   rM   r  9  s    zLit.__init__rg   rx   c                 C  s   | j S rZ   r  r  r=   r=   rM   r  <  s    zLit.__repr__N)rJ   rK   rL   r  r  r=   r=   r=   rM   r  8  s   r  zset[str]warn_once_cachec                 C  s,   | t v rd S t |  tj| |d d d S )Nr0   )
stacklevel)r  r  warningswarn)ri  r  r=   r=   rM   	warn_onceC  s    
r  c                 C  s   t d}|d| S )Nz\x1B[@-_][0-?]*[ -/]*[@-~]r;  )r  r  r  )textZansi_escaper=   r=   rM   strip_color_from_stringO  s    
r  c               	   c  s<   z&t jjd} d V  W t jj|  nt jj|  0 d S )NT)r   r  Z	_autogradZ _saved_tensors_hooks_set_tracing)r  r=   r=   rM   +_disable_saved_tensors_hooks_during_tracingU  s    r  c                   C  s   t jjjot   S rZ   )r   r4  r;   ZfreezingZis_grad_enabledr=   r=   r=   rM   is_parameter_freezing_  s    r  c                   C  s   dd t t D S )Nc                 S  s   g | ]}t |qS r=   ) get_torch_function_mode_stack_atr  r=   r=   rM   r   d  s   z1get_torch_function_mode_stack.<locals>.<listcomp>)r  r   r=   r=   r=   rM   get_torch_function_mode_stackc  s    r  c                 C  s"   | t  k r| dksJ tj| S r|   )r   r   r  Z_get_function_stack_at)indr=   r=   rM   r  i  s    r  c                 C  s,   t t D ]
}t  q
| D ]}t| qd S rZ   )r  r   r   r   )r   r+  moder=   r=   rM   set_torch_function_mode_stackn  s    r  c                  C  s   t t D ]
} t  q
d S rZ   )r  r   r   )r+  r=   r=   rM   clear_torch_function_mode_stackv  s    r  c                  G  s
   t   d S rZ   )
breakpointr  r=   r=   rM   _breakpoint_for_c_dynamo|  s    r  c                 C  sV   | j }t|}t|jdkr2ddlm} |d|j| jkrRddlm} |dd S )NrH   r0   )InternalTorchDynamoErrorz[Tensor subclass method __metadata_guard__ must take exactly two subclass metadata argumentsz?Tensor subclass method __metadata_guard__ must be a classmethod)	Z__metadata_guard__ry  	signaturer  r  r/  r  rw  r/  )r   r  sigr  r=   r=   rM   verify_guard_fn_signature  s    
r  c                 C  sH   | j tj tj fv oF| jtjtjfv oF| jtjtjfv oF| jtjtjfv S rZ   )r   r  r   r   r   __iter__)Zuser_clsr=   r=   rM   #does_not_override_dict_iter_methods  s    r  c                 C  s
   |  |S rZ   )r  r   rl  r=   r=   rM   	call_size  s    r  c                 C  s
   |  |S rZ   )r  r  r=   r=   rM   call_stride  s    r  c                 C  s   |   S rZ   )Zstorage_offsetr   r=   r=   rM   call_storage_offset  s    r  c                   s   ddg} fdd|D }|S )Nrs  tagc                   s(   i | ] }| j v r|t j | qS r=   )r  r  r  r|  r=   rM   r    s   z(_extract_tensor_dict.<locals>.<dictcomp>r=   )r  ZKEYS_TO_COPYZtensor_dictr=   r|  rM   _extract_tensor_dict  s    
r  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)r  )obj_idrY  r=   r=   rM   get_user_object_from_id  s    
r  c                 C  s   t | }t| t|< d S rZ   )rO  rW  rT  r  )rY  r  r=   r=   rM   store_user_object_weakref  s    r  c                   @  s   e Zd ZU dZded< dZded< dZedddd	Zeddd
dZ	eddddZ
eddddZeedd ZdS )CompileTimeInstructionCounterr   rP   _counterr_  _idrw   rx   c                 C  s$   | j d | _ | j dkr t | _d S ry   )_depthr   r  r  r\   r=   r=   rM   r    s    
z#CompileTimeInstructionCounter.startc                 C  s6   | j d | _ | j dkr2|  jt| j7  _d| _d S )Nr0   r   r_  )r  r  r   endr  r\   r=   r=   rM   r    s    
z!CompileTimeInstructionCounter.endc                 C  s
   d| _ d S r|   r  r\   r=   r=   rM   r[     s    z#CompileTimeInstructionCounter.clearc                 C  s   | j S rZ   r  r\   r=   r=   rM   r     s    z#CompileTimeInstructionCounter.valuec                 c  s<   z&t jr|   d V  W t jr8|   nt jr6|   0 d S rZ   )r;   Z%record_compile_time_instruction_countr  r  r\   r=   r=   rM   record  s    
z$CompileTimeInstructionCounter.recordN)rJ   rK   rL   r  re   r  r  rf   r  r  r[   r   r   r  r=   r=   r=   rM   r    s   
r  featureusagec                 C  s   t   rt  d| | dS )zQ
    Records whether we are using a feature
    Generally a feature is a JK.
    r  N)r   r   Zset_key_valuer  r=   r=   rM   set_feature_use  s    
r  )ddp_optimizerZpython_reducerZ'python_reducer_without_compiled_forward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 sVJ d||S )Nr  r  z;Invalid dynamo config optimize_ddp type type(optimize_ddp)=z.Invalid dynamo config optimize_ddp value mode=)r;   optimize_ddpr]  r   rg   rH  r-  r  )r  r  r=   r=   rM   get_optimize_ddp_mode  s    


r  zGenerator[None, None, None]c               	   c  sv   t jot } | rltd> t  dV  W d   n1 sB0    Y  W d   qr1 s`0    Y  ndV  dS )ar  
    Disables torch.inference_mode for the compilation (still on at runtime).
    This simplifies the compile stack where we can assume that inference_mode
    will always be off.

    Since inference_mode is equivalent to no_grad + some optimizations (version
    counts etc), we turn on no_grad here. The other optimizations are not
    relevant to torch.compile.
    FN)r;   "fake_tensor_disable_inference_moder   Zis_inference_mode_enabledZinference_moder  )Zis_inference_mode_onr=   r=   rM   maybe_disable_inference_mode  s    Dr  c                   c  sD   t jr:tjj  dV  W d   q@1 s.0    Y  ndV  dS )z
    Turns off tracking of inference_mode for fake tensor propagation. With this
    context manager, when a real tensor is converted to fake tensor, the fake
    tensor looses its inference-ness.
    N)r;   r  r   r  Z
meta_utilsZ$disable_inference_mode_for_fake_propr=   r=   r=   rM   *maybe_disable_inference_mode_for_fake_prop-  s    &r  zOptional[torch.fx.Node])r  rj   c                 C  s   | d u pd| j v pd| j v S )Nr/  r  r  )r  r=   r=   rM   is_node_meta_valid;  s    r  zAbstractContextManager[None]c                  C  s,   t jjjrt jjdnt } | 	  | S )NzPregraph bytecode)
r   Zautogradr   Z_is_profiler_enabledr  Z	_profilerZ_RecordFunctionFastr   nullcontext	__enter__cmr=   r=   rM   record_pregraph_bytecode_enter?  s    r  )r  rj   c                 C  s   |  d d d  d S rZ   )__exit__r  r=   r=   rM   record_pregraph_bytecode_exitJ  s    r  zlist[CodeType]c                  C  s   ddl m}  |  S )Nr   r"   )torch._guardsr"   get_traced_coder  r=   r=   rM   r  Q  s    r  )NFNNNNFN)F)F)rg   F)N)FF)F)r0   )F)T)F)F)FFF)FFF)TT)r0   (  r   
__future__r   atexitrc   r   r  r=  r  r   r  rv  r  r  ry  ru   r  r\  r!  r  r  r  r  ra  rh  rR  r   r  r  rd  rT  r  rW  r   r   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   Ztyping_extensionsr   r   r   r   r   Ztorch._functorch.configZ%torch.fx.experimental.symbolic_shapesZtorch.utils._pytreer?  Z_pytreer  r   Ztorch._Cr   r   r   r   Ztorch._dispatch.pythonr   Ztorch._dynamo.metrics_contextr   r   r  r    r!   r"   Ztorch._subclasses.meta_utilsr#   Ztorch._utils_internalr$   r%   r&   r'   r(   Ztorch.fx._utilsr)   r*   Ztorch.monitorr+   Ztorch.nn.modules.lazyr,   Ztorch.utils._tritonr-   r.   Ztorch.utils.hooksr/   Zgraph_utilsr1   r#  collections.abcr2   r3   r4   r5   r6   r7   r  ri  r@  Ztorch._loggingZtorch._numpyZ_numpyr  r8   r:   r;  r;   ZfftZlinalgr  r<   re   ZNP_TO_TNP_MODULEr  r>   r?   r@   rt   rA   r  r  r  Zunpatched_nn_module_getattrrv  Zunpatched_nn_module_callZ
_call_implZunpatched_nn_module_call_implrd   rB   rD   Ztroubleshooting_urlZnnmodule_doc_urlZnnmodule_doc_url_msgr#  rJ   rb   rE   r  rF   rW   Ztimer_counterr  rG   rN   rs   rz   r{   r}   r   r   r   r   r   r   r   r   rS  r   r   r   registerr   ZFloatTensorrq  ZDoubleTensorrr  doubleZ
HalfTensorrp  ZhalfZBFloat16Tensorr  Z
ByteTensorrn  Z
CharTensorrj  Z
LongTensorrm  longZ	IntTensorrl  rP   ZShortTensorrk  shortZ
BoolTensorr   Ztensortype_to_dtyper  r  r  r  r  r*  r1  r<  rC  rD  rI  rK  rL  r\  rb  ZParamSpecArgsZParamSpecKwargsZ	ParamSpecZTypeVarTupleZTypeAliasTyperc  rg  ro  rs  rt  r  r  r  r  r{  r~  rx  rB  neltlegtgeZcmp_name_to_op_mappingZcmp_name_to_op_str_mappingr  r  r  r  r  r  r  r  r  r  r  r  r  r  Z!DEFAULT_COMPILATION_METRICS_LIMITrI  r  r   r+  r5  rF  r   r   rJ  rK  rL  rM  ro  r   r   rq  rr  rt  rw  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rg   rR   r-  Ellipsisr/  NotImplementedr  r  Zmemory_formatr  ZfinfoZiinfoZ	attentionZ
SDPBackendrB  Z_CudaDevicePropertiesr  rC  r  languager  r  r  r  r  r  r  r  r  r	  r  r   r  r   r  r   r  r  iterr  r  r  __length_hint__Ztuple_iterator_lenr   r  r  r  Zdict_newrv   r  Zdict_methodsr^  	tuple_newZtuple_methodsr   Zlist_methodsrP  Zlist_getitemZstr_methodsr  r  r  r   r"  r%  r(  Z	iter_nextr&  r'  Zdict_getitemr+  r.  r5  r<  rH  rI  rJ  rO  r[  ZGLOBAL_KEY_PREFIXZtorch._subclassesr\  r_  rb  rg  rj  rl  ro  r  rt  r  r  Zorig_code_mapr  r  Z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	  Zall_hook_namesr  r  r  r  r  r  r  r  r!  r#  r$  r&  r(  r/  r1  r3  r8  r9  rX  rr  rt  ru  ry  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  Z_disable_dynamor  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r=   r=   r=   rM   <module>   s  , 





(         $ %



	!


 50#+O  2  

J



		 $
"   

)!
 
  2 E
	M'	
""
  #  	 		y /	&

