o
    h                     @   s  d dl Z d dlZd dlZd dlZd dlZd dlmZmZ d dlm	Z	 d dl
mZ d dlmZ d dlmZmZmZ d dlmZ d dlmZ d dlZd dlm  mZ d d	lmZ d d
lmZmZm Z m!Z!m"Z" d dl#m$Z$ d dl%m&Z&m'Z' d dl(m)Z)m*Z* g dZ+dZ,G dd dej-Z.dd Z/G dd deZ0G dd dZ1G dd deZ2d d d dde3de3de3de3de3d e3d!efd"d#Z4d$e3d!e2fd%d&Z5	'd1d(e6d)ee6 d*e7fd+d,Z8G d-d. d.e1Z9G d/d0 d0e0Z:dS )2    N)ABCabstractmethod)Iterable)Enum)partial)AnyCallableOptional)Self)warn)_get_privateuse1_backend_name)_add_execution_trace_observer!_disable_execution_trace_observer _enable_execution_trace_observer_ExperimentalConfig _remove_execution_trace_observer)	is_fbcode)kineto_availableProfilerActivity)MemoryProfileMemoryProfileTimeline)supported_activitiesProfilerActionscheduletensorboard_trace_handlerprofileExecutionTraceObserverProfilerStepc                   @   s   e Zd ZdZdd ZdS )_NumpyEncoderz~
    Json encoder for numpy types (np.int, np.float, np.array etc.)
    Returns default encoder if numpy is not available
    c                 C   sx   zddl }W n ty   tj| | Y S w t||jr!t|S t||jr+t	|S t||j
r5| S tj| |S )zEncode NumPy types to JSONr   N)numpyImportErrorjsonJSONEncoderdefault
isinstanceintegerintfloatingfloatndarraytolist)selfobjnp r.   k/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/torch/profiler/profiler.pyr#   /   s   z_NumpyEncoder.defaultN)__name__
__module____qualname____doc__r#   r.   r.   r.   r/   r   )   s    r   c                   C   s
   t j S )a  
    Returns a set of supported profiler tracing activities.

    Note: profiler uses CUPTI library to trace on-device CUDA kernels.
    In case when CUDA is enabled but CUPTI is not available, passing
    ``ProfilerActivity.CUDA`` to profiler results in using the legacy CUDA
    profiling code (same as in the legacy ``torch.autograd.profiler``).
    This, in turn, results in including CUDA time in the profiler table output,
    but not in the JSON trace.
    )torchautograd_supported_activitiesr.   r.   r.   r/   r   ?   s   
r   c                   @   s4   e Zd ZdZedd Zedd Zedd ZdS )	_ITraceObserverz^Abstract interface for a Trace observer.
    This satisfies 3 methods: start, stop and cleanupc                 C      d S Nr.   r+   r.   r.   r/   startQ      z_ITraceObserver.startc                 C   r8   r9   r.   r:   r.   r.   r/   stopU   r<   z_ITraceObserver.stopc                 C   r8   r9   r.   r:   r.   r.   r/   cleanupY   r<   z_ITraceObserver.cleanupN)r0   r1   r2   r3   r   r;   r=   r>   r.   r.   r.   r/   r7   M   s    

r7   c                   @   sd  e Zd ZdZddddddddddd
deee  dededed	ed
edee dee	 dedee
g ef  fddZdd Zdd Zdd Zdd Zdd ZdefddZd=dedefd d!Zd"edee fd#d$Z		%	d>d&ed'ed(efd)d*Zd+d, Zd-ed.efd/d0Zd-ed.efd1d2Zd-ed.efd3d4Zd5d6 Zd7efd8d9Zd?ded:ee d7dfd;d<ZdS )@_KinetoProfilea	  Low-level profiler wrap the autograd profile

    Args:
        activities (iterable): list of activity groups (CPU, CUDA) to use in profiling, supported values:
            ``torch.profiler.ProfilerActivity.CPU``, ``torch.profiler.ProfilerActivity.CUDA``,
            ``torch.profiler.ProfilerActivity.XPU``.
            Default value: ProfilerActivity.CPU and (when available) ProfilerActivity.CUDA
            or (when available) ProfilerActivity.XPU.
        record_shapes (bool): save information about operator's input shapes.
        profile_memory (bool): track tensor memory allocation/deallocation (see ``export_memory_timeline``
            for more details).
        with_stack (bool): record source information (file and line number) for the ops.
        with_flops (bool): use formula to estimate the FLOPS of specific operators
            (matrix multiplication and 2D convolution).
        with_modules (bool): record module hierarchy (including function names)
            corresponding to the callstack of the op. e.g. If module A's forward call's
            module B's forward which contains an aten::add op,
            then aten::add's module hierarchy is A.B
            Note that this support exist, at the moment, only for TorchScript models
            and not eager mode models.
        experimental_config (_ExperimentalConfig) : A set of experimental options
            used by profiler libraries like Kineto. Note, backward compatibility is not guaranteed.
        execution_trace_observer (ExecutionTraceObserver) : A PyTorch Execution Trace Observer object.
            `PyTorch Execution Traces <https://arxiv.org/pdf/2305.14516.pdf>`__ offer a graph based
            representation of AI/ML workloads and enable replay benchmarks, simulators, and emulators.
            When this argument is included the observer start() and stop() will be called for the
            same time window as PyTorch profiler.
        acc_events (bool): Enable the accumulation of FunctionEvents across multiple profiling cycles


    .. note::
        This API is experimental and subject to change in the future.

        Enabling shape and stack tracing results in additional overhead.
        When record_shapes=True is specified, profiler will temporarily hold references to the tensors;
        that may further prevent certain optimizations that depend on the reference count and introduce
        extra tensor copies.
    NF

activitiesrecord_shapesprofile_memory
with_stack
with_flopswith_modulesexperimental_configexecution_trace_observer
acc_eventscustom_trace_id_callbackrA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   c       
         C   s   |rt |nt | _|| _|| _|| _|| _|| _|| _|| _	|	| _
|
| _d | _d | _d | _tj| jv r8d| _n(tj| jv rBd| _ntj| jv rLd| _ntj| jv rVd| _n
tj| jv r`t | _i | _d S )Ncudaxpumtiahpu)setr   rA   rB   rE   rC   rD   rF   rG   rH   rI   rJ   profilermem_tl
use_devicer   CUDAXPUMTIAHPUPrivateUse1r   preset_metadata)r+   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   r.   r.   r/   __init__   s0   
z_KinetoProfile.__init__c                 C   s   |    |   d S r9   )prepare_tracestart_tracer:   r.   r.   r/   r;      s   z_KinetoProfile.startc                 C   s   |    d S r9   )
stop_tracer:   r.   r.   r/   r=      s   z_KinetoProfile.stopc                 C   sZ   | j d u s| js&tjtj| jv | j| j| j	| j
| j| jd| j| j| jd| _ | j   d S )NT)use_cpurR   rB   rE   rC   rD   rF   
use_kinetorG   rI   rJ   )rP   rI   profr   r   CPUrA   rR   rB   rE   rC   rD   rF   rG   rJ   _prepare_tracer:   r.   r.   r/   rZ      s   
z_KinetoProfile.prepare_tracec                 C   s  | j r| j   | jd usJ | j  | jr| dd | jr&| dd | jr/| dd | jr8| dd | j	rA| dd t
 r|  }|rU| dtj|td ttd	rwd
d lm  m} |jjrwdtjd< | dd dtjd< | j D ]\}}| || q|d S d S )NrC   1rD   rB   rF   rE   distributedInfocls	_inductorr   DISABLE_CUPTI_LAZY_REINIT0TEARDOWN_CUPTI)rH   r;   rP   _start_tracerC   add_metadata_jsonrD   rB   rF   rE   r   _get_distributed_infor!   dumpsr   hasattrr4   torch._inductor.configrf   configtriton
cudagraphsosenvironrX   items)r+   	dist_infoinductor_configkvr.   r.   r/   r[      s<   




z_KinetoProfile.start_tracec                 C   s2   | j r| j   | jd usJ | jd d d  d S r9   )rH   r=   rP   __exit__r:   r.   r.   r/   r\      s   
z_KinetoProfile.stop_tracepathc              	   C   s   | j sJ |drVtjdddd}|  | j |j}t|jd#}t|d}|	| W d   n1 s:w   Y  W d   n1 sIw   Y  t
|j |S | j |S )	z
        Exports the collected trace in Chrome JSON format. If kineto is enabled, only
        last cycle in schedule is exported.
        .gzw+b.jsonFsuffixdeleterbwbN)rP   endswithtempfileNamedTemporaryFilecloseexport_chrome_tracenameopengzip
writelinesrs   remove)r+   r{   fpretvaluefinfoutr.   r.   r/   r      s   

z"_KinetoProfile.export_chrome_traceself_cpu_time_totalmetricc                 C   s   | j sJ | j ||S )zSave stack traces to a file

        Args:
            path (str): save stacks file to this location;
            metric (str): metric to use: "self_cpu_time_total" or "self_cuda_time_total"
        )rP   export_stacks)r+   r{   r   r.   r.   r/   r     s   
z_KinetoProfile.export_stacksenablec                 C   s   | j sdS | j || dS )a  Toggle collection of activities on/off at any point of collection. Currently supports toggling Torch Ops
        (CPU) and CUDA activity supported in Kineto

        Args:
            activities (iterable): list of activity groups to use in profiling, supported values:
                ``torch.profiler.ProfilerActivity.CPU``, ``torch.profiler.ProfilerActivity.CUDA``
        Examples:

        .. code-block:: python

            with torch.profiler.profile(
                activities=[
                    torch.profiler.ProfilerActivity.CPU,
                    torch.profiler.ProfilerActivity.CUDA,
                ]
            ) as p:
                code_to_profile_0()
                // turn off collection of all CUDA activity
                p.toggle_collection_dynamic(False, [torch.profiler.ProfilerActivity.CUDA])
                code_to_profile_1()
                // turn on collection of all CUDA activity
                p.toggle_collection_dynamic(True, [torch.profiler.ProfilerActivity.CUDA])
                code_to_profile_2()
            print(p.key_averages().table(
                sort_by="self_cuda_time_total", row_limit=-1))
        N)rP   toggle_collection_dynamic)r+   r   rA   r.   r.   r/   r     s   z(_KinetoProfile.toggle_collection_dynamicr   group_by_input_shapegroup_by_stack_ngroup_by_overload_namec                 C   s   | j sJ | j |||S )a  Averages events, grouping them by operator name and (optionally) input shapes, stack
        and overload name.

        .. note::
            To use shape/stack functionality make sure to set record_shapes/with_stack
            when creating profiler context manager.
        )rP   key_averages)r+   r   r   r   r.   r.   r/   r   2  s   
z_KinetoProfile.key_averagesc                 C   s   | j sJ | j jS )z
        Returns the list of unaggregated profiler events,
        to be used in the trace callback or after the profiling is finished
        )rP   function_eventsr:   r.   r.   r/   eventsD  s   
z_KinetoProfile.eventskeyvaluec                 C   s&   d| dd d }tj|| dS )zo
        Adds a user defined metadata with a string key and a string value
        into the trace file
        "z\"N)replacer4   r5   _add_metadata_json)r+   r   r   wrapped_valuer.   r.   r/   add_metadataL  s   z_KinetoProfile.add_metadatac                 C   s   t j|| dS )zs
        Adds a user defined metadata with a string key and a valid json value
        into the trace file
        N)r4   r5   r   r+   r   r   r.   r.   r/   rk   T  s   z _KinetoProfile.add_metadata_jsonc                 C   s   || j |< dS )z
        Preset a user defined metadata when the profiler is not started
        and added into the trace file later.
        Metadata is in the format of a string key and a valid json value
        N)rX   r   r.   r.   r/   preset_metadata_json[  s   z#_KinetoProfile.preset_metadata_jsonc                 C   sz   dd l m} | r| sd S | }|| | | |j	 d}|dkr;t
jj }ddd |D |d< |S )Nr   )backendrank
world_sizepg_count	pg_confignccl.c                 s   s    | ]}t |V  qd S r9   )str.0ry   r.   r.   r/   	<genexpr>s  s    z7_KinetoProfile._get_distributed_info.<locals>.<genexpr>nccl_version)torch.distributeddistributedis_availableis_initializedget_backendget_rankget_world_sizeget_pg_countdistributed_c10d_get_all_pg_configsr4   rK   r   versionjoin)r+   distr   rv   r   r.   r.   r/   rl   c  s   z$_KinetoProfile._get_distributed_inforeturnc                    sT   d} fdd|D }|rt d| d jd ur" jjd us$J t jjS )N)rB   rC   rD   c                    s    g | ]}t  |s| d qS )z=True)getattr)r   ir:   r.   r/   
<listcomp>x  s     z2_KinetoProfile._memory_profile.<locals>.<listcomp>z, z required for memory profiling.)
ValueErrorr   rP   kineto_resultsr   )r+   requiredmissingr.   r:   r/   _memory_profilev  s   z_KinetoProfile._memory_profiledevicec              	   C   s0  |du r| j r| j dkr| j d }n	tj rdnd}t|  | _|dr0| j|| dS |drt	j
dd	d
d}|  |drO| j|j| n| j|j| t|j#}t|d}|| W d   n1 ssw   Y  W d   n1 sw   Y  t|j dS | j|| dS )ao  Export memory event information from the profiler collected
        tree for a given device, and export a timeline plot. There are 3
        exportable files using ``export_memory_timeline``, each controlled by the
        ``path``'s suffix.

        - For an HTML compatible plot, use the suffix ``.html``, and a memory timeline
          plot will be embedded as a PNG file in the HTML file.

        - For plot points consisting of ``[times, [sizes by category]]``, where
          ``times`` are timestamps and ``sizes`` are memory usage for each category.
          The memory timeline plot will be saved a JSON (``.json``) or gzipped JSON
          (``.json.gz``) depending on the suffix.

        - For raw memory points, use the suffix ``.raw.json.gz``. Each raw memory
          event will consist of ``(timestamp, action, numbytes, category)``, where
          ``action`` is one of ``[PREEXISTING, CREATE, INCREMENT_VERSION, DESTROY]``,
          and ``category`` is one of the enums from
          ``torch.profiler._memory_profiler.Category``.

        Output: Memory timeline written as gzipped JSON, JSON, or HTML.
        NrK   z:0zcuda:0cpuz.htmlr|   w+tr~   Fr   zraw.json.gzwt)rR   r4   rK   r   r   r   rQ   r   export_memory_timeline_htmlr   r   r   export_memory_timeline_rawr   export_memory_timeliner   r   r   rs   r   )r+   r{   r   r   r   r   r.   r.   r/   r     s*   


z%_KinetoProfile.export_memory_timeline)r   )Fr   Fr9   )r0   r1   r2   r3   r	   r   r   boolr   r7   r   r   rY   r;   r=   rZ   r[   r\   r   r   r   r&   r   r   r   rk   r   rl   r   r   r   r.   r.   r.   r/   r?   ^   s|    *
	

)(

#
 	r?   c                   @   s    e Zd ZdZdZdZdZdZdS )r   zG
    Profiler actions that can be taken at the specified intervals
    r            N)r0   r1   r2   r3   NONEWARMUPRECORDRECORD_AND_SAVEr.   r.   r.   r/   r     s    r   )repeat
skip_firstskip_first_waitwaitwarmupactiver   r   r   r   c                    sd   dt dtf fdd}dkr$dkr$ dkr$dkr$dks(J ddkr0td |S )a  
    Returns a callable that can be used as profiler ``schedule`` argument. The profiler will skip
    the first ``skip_first`` steps, then wait for ``wait`` steps, then do the warmup for the next ``warmup`` steps,
    then do the active recording for the next ``active`` steps and then repeat the cycle starting with ``wait`` steps.
    The optional number of cycles is specified with the ``repeat`` parameter, the zero value means that
    the cycles will continue until the profiling is finished.

    The ``skip_first_wait`` parameter controls whether the first ``wait`` stage should be skipped.
    This can be useful if a user wants to wait longer than ``skip_first`` between cycles, but not
    for the first profile. For example, if ``skip_first`` is 10 and ``wait`` is 20, the first cycle will
    wait 10 + 20 = 30 steps before warmup if ``skip_first_wait`` is zero, but will wait only 10
    steps if ``skip_first_wait`` is non-zero. All subsequent cycles will then wait 20 steps between the
    last active and warmup.
    stepr   c                    s   | dksJ | k rt jS | 8 } dkr| 7 }    }dkr,| | kr,t jS | | }|k r7t jS | k r@t jS ||d k rIt jS t jS )Nr   r   )r   r   r   r   r   )r   	num_stepsmod_stepr   r   r   r   r   r   r.   r/   schedule_fn  s&   zschedule.<locals>.schedule_fnr   z#Invalid profiler schedule argumentsz>Profiler won't be using warmup, this can skew profiler results)r&   r   r   )r   r   r   r   r   r   r   r.   r   r/   r     s    *r   _c                 C   s   t jS )zy
    Default profiler behavior - immediately starts recording the events,
    keeps doing it on every profiler step.
    )r   r   )r   r.   r.   r/   _default_schedule_fn     r   Fdir_nameworker_nameuse_gzipc                    s4   ddl ddlddld fdd}|S )a  
    Outputs tracing files to directory of ``dir_name``, then that directory can be
    directly delivered to tensorboard as logdir.
    ``worker_name`` should be unique for each worker in distributed scenario,
    it will be set to '[hostname]_[pid]' by default.
    r   Nr   c              
      s   j  s#z	j dd W n ty" } ztd  |d }~ww s0  d   d  d}r@|d }| j 	 | d S )NT)exist_okzCan't create directory: r   r   z.pt.trace.jsonr|   )
r{   isdirmakedirs	ExceptionRuntimeErrorgethostnamegetpidtime_nsr   r   )r_   e	file_namer   rs   sockettimer   r   r.   r/   
handler_fn
  s   z-tensorboard_trace_handler.<locals>.handler_fnr   N)rs   r   r   )r   r   r   r   r.   r   r/   r     s
   	r   c                       s
  e Zd ZdZdddddddddddddddeee  deeege	f  deede
f  d	ed
ededededee dee dedee deeg ef  f fddZdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'eej fd(d)Z  ZS )*r   a0  Profiler context manager.

    Args:
        activities (iterable): list of activity groups (CPU, CUDA) to use in profiling, supported values:
            ``torch.profiler.ProfilerActivity.CPU``, ``torch.profiler.ProfilerActivity.CUDA``,
            ``torch.profiler.ProfilerActivity.XPU``.
            Default value: ProfilerActivity.CPU and (when available) ProfilerActivity.CUDA
            or (when available) ProfilerActivity.XPU.
        schedule (Callable): callable that takes step (int) as a single parameter and returns
            ``ProfilerAction`` value that specifies the profiler action to perform at each step.
        on_trace_ready (Callable): callable that is called at each step when ``schedule``
            returns ``ProfilerAction.RECORD_AND_SAVE`` during the profiling.
        record_shapes (bool): save information about operator's input shapes.
        profile_memory (bool): track tensor memory allocation/deallocation.
        with_stack (bool): record source information (file and line number) for the ops.
        with_flops (bool): use formula to estimate the FLOPs (floating point operations) of specific operators
            (matrix multiplication and 2D convolution).
        with_modules (bool): record module hierarchy (including function names)
            corresponding to the callstack of the op. e.g. If module A's forward call's
            module B's forward which contains an aten::add op,
            then aten::add's module hierarchy is A.B
            Note that this support exist, at the moment, only for TorchScript models
            and not eager mode models.
        experimental_config (_ExperimentalConfig) : A set of experimental options
            used for Kineto library features. Note, backward compatibility is not guaranteed.
        execution_trace_observer (ExecutionTraceObserver) : A PyTorch Execution Trace Observer object.
            `PyTorch Execution Traces <https://arxiv.org/pdf/2305.14516.pdf>`__ offer a graph based
            representation of AI/ML workloads and enable replay benchmarks, simulators, and emulators.
            When this argument is included the observer start() and stop() will be called for the
            same time window as PyTorch profiler. See the examples section below for a code sample.
        acc_events (bool): Enable the accumulation of FunctionEvents across multiple profiling cycles
        use_cuda (bool):
            .. deprecated:: 1.8.1
                use ``activities`` instead.

    .. note::
        Use :func:`~torch.profiler.schedule` to generate the callable schedule.
        Non-default schedules are useful when profiling long training jobs
        and allow the user to obtain multiple traces at the different iterations
        of the training process.
        The default schedule simply records all the events continuously for the
        duration of the context manager.

    .. note::
        Use :func:`~torch.profiler.tensorboard_trace_handler` to generate result files for TensorBoard:

        ``on_trace_ready=torch.profiler.tensorboard_trace_handler(dir_name)``

        After profiling, result files can be found in the specified directory. Use the command:

        ``tensorboard --logdir dir_name``

        to see the results in TensorBoard.
        For more information, see
        `PyTorch Profiler TensorBoard Plugin <https://github.com/pytorch/kineto/tree/master/tb_plugin>`__

    .. note::
        Enabling shape and stack tracing results in additional overhead.
        When record_shapes=True is specified, profiler will temporarily hold references to the tensors;
        that may further prevent certain optimizations that depend on the reference count and introduce
        extra tensor copies.


    Examples:

    .. code-block:: python

        with torch.profiler.profile(
            activities=[
                torch.profiler.ProfilerActivity.CPU,
                torch.profiler.ProfilerActivity.CUDA,
            ]
        ) as p:
            code_to_profile()
        print(p.key_averages().table(
            sort_by="self_cuda_time_total", row_limit=-1))

    Using the profiler's ``schedule``, ``on_trace_ready`` and ``step`` functions:

    .. code-block:: python

        # Non-default profiler schedule allows user to turn profiler on and off
        # on different iterations of the training loop;
        # trace_handler is called every time a new trace becomes available
        def trace_handler(prof):
            print(prof.key_averages().table(
                sort_by="self_cuda_time_total", row_limit=-1))
            # prof.export_chrome_trace("/tmp/test_trace_" + str(prof.step_num) + ".json")

        with torch.profiler.profile(
            activities=[
                torch.profiler.ProfilerActivity.CPU,
                torch.profiler.ProfilerActivity.CUDA,
            ],

            # In this example with wait=1, warmup=1, active=2, repeat=1,
            # profiler will skip the first step/iteration,
            # start warming up on the second, record
            # the third and the forth iterations,
            # after which the trace will become available
            # and on_trace_ready (when set) is called;
            # the cycle repeats starting with the next step

            schedule=torch.profiler.schedule(
                wait=1,
                warmup=1,
                active=2,
                repeat=1),
            on_trace_ready=trace_handler
            # on_trace_ready=torch.profiler.tensorboard_trace_handler('./log')
            # used when outputting for tensorboard
            ) as p:
                for iter in range(N):
                    code_iteration_to_profile(iter)
                    # send a signal to the profiler that the next iteration has started
                    p.step()

    The following sample shows how to setup up an Execution Trace Observer (`execution_trace_observer`)

    .. code-block:: python

        with torch.profiler.profile(
            ...
            execution_trace_observer=(
                ExecutionTraceObserver().register_callback("./execution_trace.json")
            ),
        ) as p:
            for iter in range(N):
                code_iteration_to_profile(iter)
                p.step()

    You can also refer to test_execution_trace_with_kineto() in tests/profiler/test_profiler.py.
    Note: One can also pass any object satisfying the _ITraceObserver interface.
    NF)rA   r   on_trace_readyrB   rC   rD   rE   rF   rG   rH   rI   use_cudarJ   rA   r   r   .rB   rC   rD   rE   rF   rG   rH   rI   r   rJ   c                   sx  |rt |nt }|d ur(tdtdd |r|tj ntj|v r(|tj t|dks2J dt	 j
|||||||	|
r@|
nt ||d
 |rQ|| _d| _nt| _d| _|| _d| _| | j| _d | _i tjtjfg tjtjf| jgtjtjf| j| jgtjtjf| j| jgtjtjfttd	| j| jgtjtjfg tjtjf| jgtjtjf| jgtjtjfttd
| jgtjtjfttd| jgtjtjfg tjtjfg tjtjf| j| jgtjtjf| j| j| jgtjtjf| j| j| j| jgtjtjf| j| j| j| jgtjd f| j| jgtjd f| j| jgtjd f| j| jgi| _tj !t" d S )Nz;`use_cuda` is deprecated, use `activities` argument insteadr   )
stacklevelr   z"No valid profiler activities foundr@   TFz+Incorrect schedule: WARMUP followed by NONEz+Incorrect schedule: RECORD followed by NONEz-Incorrect schedule: RECORD followed by WARMUP)#rO   r   r   FutureWarningaddr   rS   r   lensuperrY   r   "build_execution_trace_obs_from_envr   record_stepsr   r   step_numcurrent_actionstep_rec_fnr   r   r   rZ   r   r[   r   r   r\   _trace_ready
action_mapr_   KinetoStepTrackerinit_step_countPROFILER_STEP_NAME)r+   rA   r   r   rB   rC   rD   rE   rF   rG   rH   rI   r   rJ   activities_set	__class__r.   r/   rY     s   







"
'
-45?zprofile.__init__c                 C   s   |    | S r9   )r;   r:   r.   r.   r/   	__enter__  s   zprofile.__enter__c                 C   s,   |    tjt | jr| j  d S d S r9   )r=   r_   r  erase_step_countr  rH   r>   )r+   exc_typeexc_valexc_tbr.   r.   r/   rz   #  s
   zprofile.__exit__c                 C   s>   |  tj| j | jrtdt| j | _	| j	
  d S d S )NProfilerStep#)_transit_actionr   r   r  r   r_   record_functionr   r   r  r  r:   r.   r.   r/   r;   )  s   zprofile.startc                 C   s.   | j r| jr| jd d d  | | jd  d S r9   )r   r  rz   r  r  r:   r.   r.   r/   r=   1  s   zprofile.stopc                 C   s   | j r| jr| jddd | j}|  jd7  _| | j| _| || j tj	dds7t
 r=tj	ddr=tjt | j rRtdt| j | _| j  dS dS )zP
        Signals the profiler that the next profiling step has started.
        Nr   KINETO_USE_DAEMON KINETO_FORCE_STEP_HOOKr  )r   r  rz   r  r   r   r  rs   rt   getr   r_   r  increment_stepr  r  r   r  )r+   prev_actionr.   r.   r/   r   6  s$   zprofile.stepc                 C   s
   || _ dS )zP
        Sets a callback to be called when a new trace ID is generated.
        N)rJ   )r+   callbackr.   r.   r/   set_custom_trace_id_callbackL  s   
z$profile.set_custom_trace_id_callbackc                 C   s   | j du rdS | j jS )z/
        Returns the current trace ID.
        N)rP   trace_idr:   r.   r.   r/   get_trace_idR  s   
zprofile.get_trace_idc                 C   s   | j r
|  |  d S d S r9   )r   r:   r.   r.   r/   r  Z  s   zprofile._trace_readyc                 C   s,   | j ||f}|r|D ]}|  qd S d S r9   )r  r  )r+   r  r  action_listactionr.   r.   r/   r  ^  s   zprofile._transit_actionr   c                 C   s   | j d u rd S | j jS r9   )rP   _statsr:   r.   r.   r/   r  d  s   
zprofile._stats)r0   r1   r2   r3   r	   r   r   r   r&   r   r   r   r   r7   r   rY   r  rz   r;   r=   r   r  r  r  r  r_   _ProfilerStatsr  __classcell__r.   r.   r	  r/   r     sj     
	
{r   c                   @   s   e Zd ZdZd%ddZdd Zeded  fdd	Zd%d
dZ	de
defddZd&dee
 fddZe	d&dedee
 fddZdd Zedd Zdd Zdd Zdd Zdd  Zdee
 fd!d"Zd%d#d$ZdS )'r   a  Execution Trace Observer

    Each process can have a single ExecutionTraceObserver instance. The observer
    can be added to record function callbacks via calling register_callback()
    explicitly. Without calling unregister_callback(), repeated calls to
    register_callback() will not add additional observers to record function
    callbacks. Once an ExecutionTraceObserver is created, the start() and stop()
    methods control when the event data is recorded.

    Deleting or calling unregister_callback() will remove the observer from the
    record function callbacks, finalize the output file, and will stop
    incurring any overheads.
    r   Nc                 C   s(   d| _ d| _d| _d| _d| _d| _dS )z1
        Initializes the default states.
        Fr  N)_registered_execution_trace_runningextra_resources_collectionresources_diroutput_file_pathoutput_file_path_observerr:   r.   r.   r/   rY   y  s   
zExecutionTraceObserver.__init__c                 C      |    dS zO
        Calls unregister_callback() to make sure to finalize outputs.
        Nunregister_callbackr:   r.   r.   r/   __del__     zExecutionTraceObserver.__del__c               
   C   s   t jdddkrRz
tjdddd} W n ty- } ztd|  W Y d	}~d	S d	}~ww |   t }|	| j
 t jd
ddkrK|d |S |d |S d	S )a  
        Returns an ExecutionTraceObserver instance if the environment variable
        ENABLE_PYTORCH_EXECUTION_TRACE is set to 1, otherwise returns None.

        Configures the observer to also collect extra resources if the environment variable
        ``ENABLE_PYTORCH_EXECUTION_TRACE_EXTRAS=1``. These are resources such as generated kernels,
        index tensor data etc. that are required to make the Execution Trace replayable.
        ENABLE_PYTORCH_EXECUTION_TRACErh   rb   r   z.et.jsonFr   zTExecution trace will not be recorded. Exception on creating default temporary file: N%ENABLE_PYTORCH_EXECUTION_TRACE_EXTRAST)rs   rt   r  r   r   r   r   r   r   register_callbackr   set_extra_resource_collection)r   r   etr.   r.   r/   r     s&   


z9ExecutionTraceObserver.build_execution_trace_obs_from_envc                 C   s   || _ | j r| jdd dS )aB  
        Collects extra resources such as generated kernels, index tensor data, and any other
        metadata that is required to complete the Execution Trace content.

        The caller should call this method with val=True after calling register_callback() if they want
        to collect the extra resources.
        T)
can_createN)r$  get_resources_dir)r+   valr.   r.   r/   r1    s   z4ExecutionTraceObserver.set_extra_resource_collectionr&  c                 C   s>   dt fdd}| js|| _|dr| }|| _t|| _| S )zv
        Adds ET observer to record function callbacks. The data will be
        written to output_file_path.
        r   c                  S   s   t jdddd} |   | jS )Nr}   r~   Fr   )r   r   r   r   )r   r.   r.   r/   get_temp_uncompressed_file  s   zLExecutionTraceObserver.register_callback.<locals>.get_temp_uncompressed_filer|   )r   r"  r&  r   r'  r   )r+   r&  r6  r.   r.   r/   r0    s   

z(ExecutionTraceObserver.register_callbackFc                 C   s:   | j sdS | jr| jS tj| j|d}|sdS || _| jS )a  
        Generates the resources directory for the generated kernels,
        or index tensor data or any other metadata that is required
        to complete the Execution Trace content.

        The directory is created right where the ET file is being output.

        Only works if the observer has called set_extra_resource_collection(val=True).

        Returns None if the observer is not configured with extra resource collection.
        N)
create_dir)r$  r%  r   get_resources_dir_for_et_pathr&  )r+   r3  generated_pathr.   r.   r/   r4    s   z(ExecutionTraceObserver.get_resources_dirr7  c                 C   sz   t j| \}}t j|t j|d d }t j|s;|r9zt | W |S  ty8   td|  Y d S w d S |S )Nr   
_resourcesz(Execution trace exception when creating )	rs   r{   splitr   splitextexistsmkdirr   r   )
trace_pathr7  work_dirr   resource_dirr.   r.   r/   r8    s   z4ExecutionTraceObserver.get_resources_dir_for_et_pathc              
      s   d fdd}dt dt ddfdd} jrM   z|  W n ty7 } ztd	|  W Y d}~nd}~ww t   jd
rH| j j d _dS dS )zE
        Removes ET observer from record function callbacks.
        r   Nc               
      s   z   } W n ty  } ztd|  W Y d }~d S d }~ww | s%d S ddlm} dd |jD }|D ]}|d u r<q5tj|}tj	| |}t
|| q5d S )Nz>Execution trace exception when generating resource directory: r   )PyCodeCachec                 S   s"   g | ]}t |d ddur|jqS )__file__N)r   rC  r   r.   r.   r/   r     s
    z\ExecutionTraceObserver.unregister_callback.<locals>._save_triton_kernels.<locals>.<listcomp>)r4  r   r   torch._inductor.codecacherB  modulesrs   r{   basenamer   shutilcopyfile)rA  r   rB  kernel_fileskernel_filer   dstr:   r.   r/   _save_triton_kernels  s,   zHExecutionTraceObserver.unregister_callback.<locals>._save_triton_kernelsuncompressed_fileoutput_filec              	   S   s   t d|  d|  t| d#}t|d}|| W d    n1 s&w   Y  W d    n1 s5w   Y  t|  d S )NzExecution Trace: compressing z to r   r   )printr   r   r   rs   r   )rM  rN  r   r   r.   r.   r/   _save_gz_file  s   zAExecutionTraceObserver.unregister_callback.<locals>._save_gz_filez(Execution trace failed to save kernels: gzFr   )	r   r"  r=   r   r   r   r&  r   r'  )r+   rL  rP  r   r.   r:   r/   r+    s   

z*ExecutionTraceObserver.unregister_callbackc                 C      | j S )z^
        Returns True if the execution trace observer is registered, otherwise False.
        )r"  r:   r.   r.   r/   is_registered)  r   z$ExecutionTraceObserver.is_registeredc                 C   rR  )zK
        Returns True if the observer is running, otherwise False.
        )r#  r:   r.   r.   r/   
is_running0  s   z!ExecutionTraceObserver.is_runningc                 C   s,   | j r| jst  d| _|   dS dS dS )z$
        Starts to capture.
        TN)r"  r#  r   _record_pg_configr:   r.   r.   r/   r;   6  s
   zExecutionTraceObserver.startc                 C   s   | j rt  d| _ dS dS )z#
        Stops to capture.
        FN)r#  r   r:   r.   r.   r/   r=   ?  s   
zExecutionTraceObserver.stopc                 C   r(  r)  r*  r:   r.   r.   r/   r>   G  r-  zExecutionTraceObserver.cleanupc                 C   s   | j r| j S dS )z7
        Returns the output file name or None.
        N)r&  r:   r.   r.   r/   get_output_file_pathM  s   z+ExecutionTraceObserver.get_output_file_pathc                 C   sN   | j r!tj r#tj r%tjjjj}tj	dt
j|td d S d S d S d S )Nz## process_group:init ##rd   )rS  r4   r   r   r   r   _worldpg_config_infor5    _record_function_with_args_enterr!   rm   r   )r+   rX  r.   r.   r/   rU  V  s   z(ExecutionTraceObserver._record_pg_configr   )F)r0   r1   r2   r3   rY   r,  staticmethodr	   r   r1  r   r
   r0  r4  r   r8  r+  propertyrS  rT  r;   r=   r>   rV  rU  r.   r.   r.   r/   r   j  s2    

5
		r   )NF);r   r!   rs   rG  r   abcr   r   collections.abcr   enumr   	functoolsr   typingr   r   r	   typing_extensionsr
   warningsr   r4   torch.autograd.profilerr5   rP   r_   torch._Cr   torch._C._profilerr   r   r   r   r   torch._environmentr   torch.autogradr   r   torch.profiler._memory_profilerr   r   __all__r  r"   r   r   r7   r?   r   r&   r   r   r   r   r   r   r   r.   r.   r.   r/   <module>   sv     V
8	
  P