a
    ßñhÔ  ã                   @   sŒ  d dl Z d dlmZ d dlZd dlmZ d dlmZmZ d dl	m
Z
 d dlmZmZmZmZ zd dlmZ W n* ey–   d dlZG dd	„ d	eƒZY n0 G d
d„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZdd„ Zdd„ Zdd„ Zdd„ Zdd„ ZG dd„ deƒZG dd„ deƒZed g d!¢ƒZ G d"d#„ d#eƒZ!G d$d%„ d%eƒZ"G d&d'„ d'eƒZ#d(d)„ Z$G d*d+„ d+eƒZ%d,d-„ Z&d3d1d2„Z'dS )4é    N)ÚAny)ÚFuture)ÚdefaultdictÚ
namedtuple)Ú
attrgetter)ÚListÚDictÚTupleÚOptional)ÚContextDecoratorc                   @   s$   e Zd Zdd„ Zdd„ Zdd„ ZdS )r   c                 C   s   t ‚d S ©N©ÚNotImplementedError©Úself© r   úW/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torch/autograd/profiler.pyÚ	__enter__   s    zContextDecorator.__enter__c                 C   s   t ‚d S r   r   ©r   Úexc_typeÚexc_valÚexc_tbr   r   r   Ú__exit__   s    zContextDecorator.__exit__c                    s   t  ˆ ¡‡ ‡fdd„ƒ}|S )Nc                     s6   ˆ� ˆ | i |¤ŽW  d   ƒ S 1 s(0    Y  d S r   r   )ÚargsÚkwargs©Úfuncr   r   r   Úwrapped   s    z*ContextDecorator.__call__.<locals>.wrapped)Ú	functoolsÚwraps)r   r   r   r   r   r   Ú__call__   s    zContextDecorator.__call__N)Ú__name__Ú
__module__Ú__qualname__r   r   r    r   r   r   r   r      s   r   c                       st   e Zd ZdZ‡ fdd„Zdd„ Zdd„ Zdd	„ Zed
d„ ƒZ	edd„ ƒZ
ddd„Zdd„ Zddd„Zdd„ Z‡  ZS )Ú	EventListz&A list of Events (for pretty printing)c                    sD   |  dd¡}|  dd¡}tt| ƒj|i |¤Ž d| _|| _|| _d S )NÚuse_cudaTÚprofile_memoryF)ÚpopÚsuperr$   Ú__init__Ú_cpu_children_populatedÚ	_use_cudaÚ_profile_memory)r   r   r   r%   r&   ©Ú	__class__r   r   r)   $   s    zEventList.__init__c                 C   s   |   ¡ S r   )Útabler   r   r   r   Ú__str__,   s    zEventList.__str__c                 C   sî   | j r
dS dd„ | D ƒ}t|tdƒd�}tj|dd„ d�}|D ]¤\}}t|dd„ d�}g }d	}|D ]~}	t|ƒd	krÖ|d
 }
|	jj|
jjksš|	jj|
jjkr¤| 	¡  qf|
 
|	¡ |	jdu sÈJ d |	j¡ƒ‚|	 |
¡ qÖqf| |	¡ qbq>d| _dS )a4  Populates child events into each underlying FunctionEvent object.
        One event is a child of another if [s1, e1) is inside [s2, e2). Where
        s1 and e1 would be start and end of the child event's interval. And
        s2 and e2 start and end of the parent event's interval

        Example: In event list [[0, 10], [1, 3], [3, 4]] would have make [0, 10]
        be a parent of two other intervals.

        If for any reason two intervals intersect only partially, this function
        will not record a parent child relationship between then.
        Nc                 S   s   g | ]}|j s|‘qS r   )Úis_async©Ú.0Úevtr   r   r   Ú
<listcomp>A   ó    z3EventList.populate_cpu_children.<locals>.<listcomp>Úthread©Úkeyc                 S   s   | j | jfS r   )r7   Únode_id©Úeventr   r   r   Ú<lambda>J   r6   z1EventList.populate_cpu_children.<locals>.<lambda>c                 S   s   | j j| j j gS r   ©Úcpu_intervalÚstartÚendr;   r   r   r   r=   \   r6   r   éÿÿÿÿz*There is already a CPU parent event for {}T)Úcpu_children_populatedÚsortedr   Ú	itertoolsÚgroupbyÚlenr?   r@   rA   r'   Úappend_cpu_childÚ
cpu_parentÚformatr9   Úset_cpu_parentÚappendr*   )r   Zsync_eventsÚeventsÚthreadsÚ	thread_idZthread_eventsZthread_events_Zcurrent_eventsZcur_endr<   Úparentr   r   r   Úpopulate_cpu_children/   sF    þÿþÿ

ÿÿþ
zEventList.populate_cpu_childrenc                    sž   |   ¡  ‡ fdd„‰ i }| D ].}ˆ |ƒd u r|j|jf}||vr|j||< q| D ]H}ˆ |ƒ}|d urP|jd usrJ ‚|j|jf}||v r’|| |_qPg |_qPd S )Nc                    s(   | d u rd S | j dkr| S ˆ | jƒS d S ©Né   )ÚscoperI   ©r4   ©Ú	bw_parentr   r   rW   x   s
    
z5EventList.set_backward_stacktraces.<locals>.bw_parent)rQ   Úsequence_nrr7   ÚstackÚ
fwd_thread)r   Z
fwd_stacksr4   ÚtÚpr   rV   r   Úset_backward_stacktracesu   s     z"EventList.set_backward_stacktracesc                 C   s   t dd„ | D ƒƒS )Nc                 S   s   g | ]
}|j ‘qS r   ©Úself_cpu_time_total©r3   r<   r   r   r   r5   ”   r6   z1EventList.self_cpu_time_total.<locals>.<listcomp>)Úsumr   r   r   r   r_   ’   s    zEventList.self_cpu_time_totalc                 C   s   | j S r   )r*   r   r   r   r   rC   –   s    z EventList.cpu_children_populatedNéd   Fc              	   C   s   t | |||| j| j|d�S )a·  Prints an EventList as a nicely formatted table.

        Arguments:
            sort_by (str, optional): Attribute used to sort entries. By default
                they are printed in the same order as they were registered.
                Valid keys include: ``cpu_time``, ``cuda_time``, ``cpu_time_total``,
                ``cuda_time_total``, ``cpu_memory_usage``, ``cuda_memory_usage``,
                ``self_cpu_memory_usage``, ``self_cuda_memory_usage``, ``count``.
            top_level_events_only(bool, optional): Boolean flag to determine the
                selection of events to display. If true, the profiler will only
                display events at top level like top-level invocation of python
                `lstm`, python `add` or other functions, nested events like low-level
                cpu/cuda ops events are omitted for profiler result readability.

        Returns:
            A string containing the table.
        )Úsort_byÚ	row_limitÚheaderr%   r&   Útop_level_events_only)Úbuild_tabler+   r,   ©r   rc   rd   re   rf   r   r   r   r/   š   s    ùzEventList.tablec                 C   s2  ddl }t|dƒ��}g }d}| d¡ | D ]¸}| d|j|jj|j ¡ |jsT|jnd|j	› d|j› d�f ¡ |j
D ]l}| d	|j|jj|j|f ¡ | d
|j|jj|j|f ¡ | d|j|jj|j ¡ |jf ¡ |d7 }qvq,| | ¡ d |j¡ | ¡  | d¡ W d  ƒ n1 �s$0    Y  dS )zéExports an EventList as a Chrome tracing tools file.

        The checkpoint can be later loaded and inspected under ``chrome://tracing`` URL.

        Arguments:
            path (str): Path where the trace will be written.
        r   NÚwú[z_{"name": "%s", "ph": "X", "ts": %s, "dur": %s, "tid": %s, "pid": "CPU functions", "args": {}}, z
" node_id:z, thread_id:z "zt{"name": "%s", "ph": "s", "ts": %s, "tid": %s, "pid": "CPU functions", "id": %s, "cat": "cpu_to_cuda", "args": {}}, zu{"name": "%s", "ph": "f", "ts": %s, "tid": %s, "pid": "CUDA functions", "id": %s, "cat": "cpu_to_cuda", "args": {}}, z`{"name": "%s", "ph": "X", "ts": %s, "dur": %s, "tid": %s, "pid": "CUDA functions", "args": {}}, rS   é   ú])ÚosÚopenÚwriteÚnamer?   r@   Ú
elapsed_usÚ	is_remoter7   r:   ÚkernelsÚintervalÚdeviceÚseekÚtellÚSEEK_SETÚtruncate)r   Úpathrm   ÚfZchrome_eventsÚnext_idr4   Úkr   r   r   Úexport_chrome_traceµ   sF    
ÿúùÿ

ÿù	ù
ÿúzEventList.export_chrome_tracer   c                 C   sv   |   ¡  ttƒ}dd„ }| D ]}|||||ƒ  |¡ qt| ¡ | j| jd�}|D ]}|jd|… |_|sRd|_	qR|S )a=  Averages all function events over their keys.

        Arguments:
            group_by_input_shapes: group entries by
            (event name, input shapes) rather than just event name.
            This is useful to see which input shapes contribute to the runtime
            the most and may help with size-specific optimizations or
            choosing the best candidates for quantization (aka fitting a roof line)

            group_by_stack_n: group by top n stack trace entries

        Returns:
            An EventList containing FunctionEventAvg objects.
        c                 S   sJ   t | jƒt | jƒg}|r(| t | jƒ¡ |dkrB|| jd |… 7 }t|ƒS ©Nr   )Ústrr9   r:   rL   Úinput_shapesrY   Útuple)r<   Úgroup_by_input_shapesÚgroup_by_stack_nr9   r   r   r   Úget_key  s    z'EventList.key_averages.<locals>.get_key©r%   r&   NÚ )
rQ   r   ÚFunctionEventAvgÚaddr$   Úvaluesr+   r,   rY   r�   )r   rƒ   r„   Ústatsr…   r4   Zavg_listr   r   r   Úkey_averagesù   s    zEventList.key_averagesc                 C   s(   t ƒ }| D ]}||7 }d|_q
d|_|S )zVAverages all events.

        Returns:
            A FunctionEventAvg object.
        NZTotal)rˆ   r9   )r   Z
total_statr4   r   r   r   Útotal_average  s    zEventList.total_average)Nrb   NF)Fr   )r!   r"   r#   Ú__doc__r)   r0   rQ   r]   Úpropertyr_   rC   r/   r~   rŒ   r�   Ú__classcell__r   r   r-   r   r$   "   s   F


D
#r$   c                   @   sš   e Zd ZdZddd„Zdd„ Zdd	„ Zd
d„ Zdd„ Zdd„ Z	ddd„Z
ej
je
_dd„ Zejje_ddd„Zejje_dd„ Zejje_edd„ ƒZdS ) Úprofileao  Context manager that manages autograd profiler state and holds a summary of results.
    Under the hood it just records events of functions being executed in C++ and
    exposes those events to Python. You can wrap any code into it and it will
    only report runtime of PyTorch functions.
    Note: profiler is thread local and is automatically propagated into the async tasks

    Arguments:
        enabled (bool, optional): Setting this to False makes this context manager a no-op.
            Default: ``True``.

        use_cuda (bool, optional): Enables timing of CUDA events as well using the cudaEvent API.
            Adds approximately 4us of overhead to each tensor operation.
            Default: ``False``

        record_shapes (bool, optional): If shapes recording is set, information
            about input dimensions will be collected. This allows one to see which
            dimensions have been used under the hood and further group by them
            using prof.key_averages(group_by_input_shape=True). Please note that
            shape recording might skew your profiling data. It is recommended to
            use separate runs with and without shape recording to validate the timing.
            Most likely the skew will be negligible for bottom most events (in a case
            of nested function calls). But for higher level functions the total
            self cpu time might be artificially increased because of the shape
            collection.

        profile_memory (bool, optional): Whether to report memory usage, default: ``False``

        with_stack (bool, optional): record source information (file and line number) for the ops

    .. warning:
        Enabling memory profiling or source attribution incurs additional profiler
        overhead

    .. warning:
        This context managers should not be called recursively, i.e. no nested
        instances are allowed

    .. warning:
        Due to some CUDA multiprocessing limitations (multiprocessing-cuda-note_),
        one cannot use the profiler with ``use_cuda = True`` to benchmark
        DataLoaders with ``num_workers > 0``. If you wish to benchmark data loading,
        please use ``use_cuda = False`` or ``num_workers = 0``.

    Example:
        >>> x = torch.randn((1, 1), requires_grad=True)
        >>> with torch.autograd.profiler.profile() as prof:
        >>>     for _ in range(100):  # any normal python code, really!
        >>>         y = x ** 2
        >>          y.backward()
        >>> # NOTE: some columns were removed for brevity
        >>> print(prof.key_averages().table(sort_by="self_cpu_time_total"))
        -----------------------------------  ---------------  ---------------  ---------------
        Name                                 Self CPU total   CPU time avg     Number of Calls
        -----------------------------------  ---------------  ---------------  ---------------
        mul                                  32.048ms         32.048ms         200
        pow                                  27.041ms         27.041ms         200
        PowBackward0                         9.727ms          55.483ms         100
        torch::autograd::AccumulateGrad      9.148ms          9.148ms          100
        torch::autograd::GraphRoot           691.816us        691.816us        100
        -----------------------------------  ---------------  ---------------  ---------------

    TFc                 C   s8   || _ || _d | _| j sd S d| _|| _|| _|| _d S ©NF)Úenabledr%   Úfunction_eventsÚenteredÚrecord_shapesr&   Ú
with_stack)r   r“   r%   r–   r&   r—   r   r   r   r)   i  s    zprofile.__init__c                 C   s`   | j s
d S | jrtdƒ‚d| _| jr.tjjjntjjj}tj 	|| j
| j| j¡}tj |¡ | S )Nz*autograd profiler traces are not reentrantT)r“   r•   ÚRuntimeErrorr%   ÚtorchÚautogradÚProfilerStateZCUDAZCPUÚProfilerConfigr–   r&   r—   Ú_enable_profiler)r   Zprofiler_kindÚconfigr   r   r   r   z  s     ÿüzprofile.__enter__c                 C   s@   | j s
d S tj ¡ }tt|ƒ| j| jd�| _| j	r<| j 
¡  dS )Nr†   F)r“   r™   rš   Ú_disable_profilerr$   Úparse_event_recordsr%   r&   r”   r—   r]   )r   r   r   r   Úrecordsr   r   r   r   ‹  s    
ý
zprofile.__exit__c                 C   s   | j d u rdS t| j ƒS ©Nz#<unfinished torch.autograd.profile>)r”   Úreprr   r   r   r   Ú__repr__—  s    
zprofile.__repr__c                 C   s"   | j d u rdS | j  ¡  t| j ƒS r¢   )r”   rQ   r€   r   r   r   r   r0   œ  s    

zprofile.__str__c                 C   s    | j d u rtdƒ‚| j  ¡  d S )Nz/can't export a trace that didn't finish running)r”   r˜   rQ   r   r   r   r   Ú_check_finish¢  s    
zprofile._check_finishNrb   c                 C   s*   |   ¡  | jd usJ ‚| jj||||d�S )N)rc   rd   re   rf   )r¥   r”   r/   rh   r   r   r   r/   §  s    þzprofile.tablec                 C   s"   |   ¡  | jd usJ ‚| j |¡S r   )r¥   r”   r~   )r   rz   r   r   r   r~   °  s    zprofile.export_chrome_tracer   c                 C   s$   |   ¡  | jd usJ ‚| j ||¡S r   )r¥   r”   rŒ   )r   Zgroup_by_input_shaper„   r   r   r   rŒ   ¶  s    zprofile.key_averagesc                 C   s    |   ¡  | jd usJ ‚| j ¡ S r   )r¥   r”   r�   r   r   r   r   r�   ¼  s    zprofile.total_averagec                 C   s   |   ¡  | jdusJ ‚| jjS )zl Returns total time spent on CPU obtained as a sum of
        all self times across all the events.
        N)r¥   r”   r_   r   r   r   r   r_   Â  s    zprofile.self_cpu_time_total)TFFFF)Nrb   NF)Fr   )r!   r"   r#   rŽ   r)   r   r   r¤   r0   r¥   r/   r$   r~   rŒ   r�   r�   r_   r   r   r   r   r‘   *  s,   @     ú






r‘   c                   @   sP   e Zd ZdZedœdd„Zdd„ Zeeedœdd	„Ze	e e	e d
œdd„Z
dS )Úrecord_functionaÖ  Context manager/function decorator that adds a label to a block of
    Python code (or function) when running autograd profiler. It is
    useful when tracing the code profile.

    Arguments:
        name (str): Label assigned to the block of code.
        node_id (int): ID of node, for distributed profiling. Unset in
        non-distributed cases.

    Example:
        >>> x = torch.randn((1, 1), requires_grad=True)
        >>> with torch.autograd.profiler.profile() as prof:
        ...     y = x ** 2
        ...     with torch.autograd.profiler.record_function("label-z"): # label the block
        ...         z = y ** 3
        ...     y.backward()
        ...
        >>> # NOTE: some columns were removed for brevity
        >>> print(prof.key_averages().table(sort_by="self_cpu_time_total"))
        -----------------------------------  ---------------  ---------------  ---------------
        Name                                 Self CPU total %  CPU time avg     Number of Calls
        -----------------------------------  ---------------  ---------------  ---------------
        pow                                  60.77%           47.470us         3
        mul                                  21.73%           25.465us         2
        PowBackward0                         12.03%           121.891us        1
        torch::autograd::AccumulateGrad      2.70%            6.324us          1
        label-z                              2.13%            12.421us         1
        torch::autograd::GraphRoot           0.64%            1.503us          1
        -----------------------------------  ---------------  ---------------  ---------------
        Self CPU time total: 234.344us
        CUDA time total: 0.000us

    ©rp   c                 C   s   || _ d| _t d¡| _d S )NTrS   )rp   Úrun_callbacks_on_exitr™   ÚzerosÚhandle)r   rp   r   r   r   r)   î  s    zrecord_function.__init__c                 C   s   t jj | j¡| _| S r   )r™   ÚopsÚprofilerZ_record_function_enterrp   rª   r   r   r   r   r   ö  s    zrecord_function.__enter__)r   Ú	exc_valueÚ	tracebackc                 C   s   | j rtjj | j¡ d S r   )r¨   r™   r«   r¬   Z_record_function_exitrª   )r   r   r­   r®   r   r   r   r   ú  s    zrecord_function.__exit__)ÚfutÚreturnc                 C   s*   | j stdƒ‚d| _ tjj | j|¡}|S )a¹  
        _call_end_callbacks_on_future is meant to be used for profiling async
        calls that return a future. Calling this function will extend recording
        beyond this scope, until the future is satisfied. It is useful for profiling
        the end to end time of asynchronous calls. This function should only be called
        once to attach the callback onto the future, and will throw if called multiple
        times.

        Arguments:
            fut: (torch._C.Future): future for which to schedule
            callback for.

        Returns:
            A future that completes with the value of the passed in future when
            the profiling callbacks have ran.

        z6_call_end_callbacks_on_future can only be called once.F)r¨   r˜   r™   r«   r¬   Z_call_end_callbacks_on_jit_futrª   )r   r¯   Zprofiled_futurer   r   r   Ú_call_end_callbacks_on_futureþ  s
    z-record_function._call_end_callbacks_on_futureN)r!   r"   r#   rŽ   r€   r)   r   r   r   r   r±   r   r   r   r   r¦   Ì  s
   !r¦   c                   @   s*   e Zd ZdZddd„Zdd„ Zdd	„ Zd
S )Ú	emit_nvtxa½  Context manager that makes every autograd operation emit an NVTX range.

    It is useful when running the program under nvprof::

        nvprof --profile-from-start off -o trace_name.prof -- <regular command here>

    Unfortunately, there's no way to force nvprof to flush the data it collected
    to disk, so for CUDA profiling one has to use this context manager to annotate
    nvprof traces and wait for the process to exit before inspecting them.
    Then, either NVIDIA Visual Profiler (nvvp) can be used to visualize the timeline, or
    :func:`torch.autograd.profiler.load_nvprof` can load the results for inspection
    e.g. in Python REPL.

    .. warning:
        This context manager should not be called recursively, i.e. at most one
        instance should be enabled at any given time.

    Arguments:
        enabled (bool, optional, default=True): Setting ``enabled=False`` makes this context manager a no-op.
            Default: ``True``.
        record_shapes (bool, optional, default=False): If ``record_shapes=True``, the nvtx range wrapping
            each autograd op will append information about the sizes of Tensor arguments received
            by that op, in the following format:
            ``[[arg0.size(0), arg0.size(1), ...], [arg1.size(0), arg1.size(1), ...], ...]``
            Non-tensor arguments will be represented by ``[]``.
            Arguments will be listed in the order they are received by the backend op.
            Please note that this order may not match the order in which those arguments were passed
            on the Python side.  Also note that shape recording may increase the overhead of nvtx range creation.

    Example:
        >>> with torch.cuda.profiler.profile():
        ...     model(x) # Warmup CUDA memory allocator and profiler
        ...     with torch.autograd.profiler.emit_nvtx():
        ...         model(x)

    **Forward-backward correlation**

    When viewing a profile created using :class:`emit_nvtx` in the Nvidia Visual Profiler,
    correlating each backward-pass op with the corresponding forward-pass op can be difficult.
    To ease this task, :class:`emit_nvtx` appends sequence number information to the ranges it
    generates.

    During the forward pass, each function range is decorated with ``seq=<N>``.  ``seq`` is a running
    counter, incremented each time a new backward Function object is created and stashed for backward.
    Thus, the ``seq=<N>`` annotation associated with each forward function range tells you that
    if a backward Function object is created by this forward function,
    the backward object will receive sequence number N.
    During the backward pass, the top-level range wrapping each C++ backward Function's
    ``apply()`` call is decorated with ``stashed seq=<M>``.  ``M`` is the sequence number that
    the backward object was created with.  By comparing ``stashed seq`` numbers in backward with ``seq``
    numbers in forward, you can track down which forward op created each backward Function.

    Any functions executed during the backward pass are also decorated with ``seq=<N>``.  During
    default backward (with ``create_graph=False``) this information is irrelevant, and in fact,
    ``N`` may simply be 0 for all such functions.  Only the top-level ranges associated with
    backward Function objects' ``apply()`` methods are useful, as a way to correlate these Function
    objects with the earlier forward pass.

    **Double-backward**

    If, on the other hand, a backward pass with ``create_graph=True`` is underway (in other words,
    if you are setting up for a double-backward), each function's execution during backward
    is given a nonzero, useful ``seq=<N>``.  Those functions may themselves create Function objects
    to be executed later during double-backward, just as the original functions in the forward pass did.
    The relationship between backward and double-backward is conceptually the same as the relationship
    between forward and backward: The functions still emit current-sequence-number-tagged ranges,
    the Function objects they create still stash those sequence numbers, and during the eventual
    double-backward, the Function objects' ``apply()`` ranges are still tagged with ``stashed seq``
    numbers, which can be compared to `seq` numbers from the backward pass.

    .. warning:
        The sequence number is thread-local, and some forward functions don't create an associated
        backward Function object (instead delegating that to sub-functions further down the call chain).
        For these reasons, the correspondence of stashed sequence numbers in
        backward Function ``apply()`` ranges with `seq` numbers in forward-pass ranges is
        not guaranteed to be 1 to 1.  The sequence numbers alone may not be enough to fully
        disambiguate which forward function created which
        backward Function object.  You may need to make a judgment based on analytic knowledge of what
        the expected correspondence should be.
    TFc                 C   s   || _ d| _|| _d S r’   )r“   r•   r–   )r   r“   r–   r   r   r   r)   l  s    zemit_nvtx.__init__c                 C   sN   | j s
d S | jrtdƒ‚d| _tj ¡  tj tj tjj	j
| jdd¡¡ | S )Nz0NVTX annotation context manager is not reentrantTF)r“   r•   r˜   r™   ÚcudaÚsynchronizerš   r�   rœ   r›   ZNVTXr–   r   r   r   r   r   q  s    
üÿzemit_nvtx.__enter__c                 C   s"   | j s
d S tj ¡  tj ¡  dS r’   )r“   r™   r³   r´   rš   rŸ   r   r   r   r   r   �  s
    

zemit_nvtx.__exit__N)TF)r!   r"   r#   rŽ   r)   r   r   r   r   r   r   r²     s   P
r²   c                 C   s   t t| ƒƒS )zyOpens an nvprof trace file and parses autograd annotations.

    Arguments:
        path (str): path to nvprof trace
    )r$   Úparse_nvprof_trace)rz   r   r   r   Úload_nvprof‰  s    r¶   c                 C   s>   d}d}| |krd  | | ¡S | |kr4d  | | ¡S d  | ¡S )ú+Defines how to format time in FunctionEventg    €„.Ag     @�@z{:.3f}sz{:.3f}msz{:.3f}us©rJ   )Útime_usZUS_IN_SECONDZUS_IN_MSr   r   r   Úformat_time•  s    rº   c                 C   s4   |dkr"| dksJ d  | ¡ƒ‚dS d  | d | ¡S )r·   r   z Expected time_us == 0 but got {}ÚNaNz{:.2f}%g      Y@r¸   )r¹   Ztotal_time_usr   r   r   Úformat_time_share   s    r¼   c                 C   s~   d}d| }d| }t | ƒ|kr2d | d | ¡S t | ƒ|krPd | d | ¡S t | ƒ|krnd | d | ¡S t| ƒd S dS )z&Returns a formatted memory size stringi   z	{:.2f} Gbç      ð?z	{:.2f} Mbz	{:.2f} Kbz bN)ÚabsrJ   r€   )ÚnbytesZKBZMBZGBr   r   r   Úformat_memory§  s    rÀ   c                    s   t ‡ fdd„ƒS )Nc                    s   t t| ˆ ƒƒS r   )rº   Úgetattrr   r§   r   r   r=   ¶  r6   z attr_formatter.<locals>.<lambda>)r�   r§   r   r§   r   Úattr_formatterµ  s    rÂ   c                   @   sX   e Zd ZdZedƒZedƒZedƒZedƒZedƒZ	edƒZ
edd	„ ƒZed
d„ ƒZdS )ÚFormattedTimesMixinz{Helpers for FunctionEvent and FunctionEventAvg.

    The subclass should define `*_time_total` and `count` attributes.
    Úcpu_timeÚ	cuda_timeÚcpu_time_totalÚcuda_time_totalr_   Úself_cuda_time_totalc                 C   s   | j dkrdS d| j | j  S ©Nr   g        r½   )ÚcountrÆ   r   r   r   r   rÄ   Å  s    zFormattedTimesMixin.cpu_timec                 C   s   | j dkrdS d| j | j  S rÉ   )rÊ   rÇ   r   r   r   r   rÅ   É  s    zFormattedTimesMixin.cuda_timeN)r!   r"   r#   rŽ   rÂ   Úcpu_time_strÚcuda_time_strÚcpu_time_total_strÚcuda_time_total_strÚself_cpu_time_total_strÚself_cuda_time_total_strr�   rÄ   rÅ   r   r   r   r   rÃ   ¹  s   
rÃ   c                   @   s   e Zd Zdd„ Zdd„ ZdS )ÚIntervalc                 C   s   || _ || _d S r   )r@   rA   )r   r@   rA   r   r   r   r)   Ï  s    zInterval.__init__c                 C   s   | j | j S r   )rA   r@   r   r   r   r   rq   Ó  s    zInterval.elapsed_usN)r!   r"   r#   r)   rq   r   r   r   r   rÑ   Î  s   rÑ   ÚKernel)rp   ru   rt   c                	   @   sŽ   e Zd ZdZddd„Zd	d
„ Zdd„ Zdd„ Zedd„ ƒZ	edd„ ƒZ
edd„ ƒZedd„ ƒZedd„ ƒZedd„ ƒZedd„ ƒZdd„ ZdS ) ÚFunctionEventz.Profiling information about a single function.Nr   FTrB   c                 C   sv   || _ || _|| _t||ƒ| _|| _|| _g | _d| _g | _	d | _
|| _|	| _|
| _|| _|| _|| _|| _|| _d S rR   )Úidr:   rp   rÑ   r?   r7   rZ   rs   rÊ   Úcpu_childrenrI   r�   rY   rT   Úcpu_memory_usageÚcuda_memory_usager1   rr   rX   )r   rÔ   r:   rp   r7   Ú	cpu_startÚcpu_endrZ   r�   rY   rT   rÖ   r×   r1   rr   rX   r   r   r   r)   Ü  s$    zFunctionEvent.__init__c                 C   s   | j  t||t||ƒƒ¡ d S r   )rs   rL   rÒ   rÑ   )r   rp   ru   r@   rA   r   r   r   Úappend_kerneló  s    zFunctionEvent.append_kernelc                 C   s   t |tƒsJ ‚| j |¡ dS )z­Append a CPU child of type FunctionEvent.

        One is supposed to append only direct children to the event to have
        correct self cpu time being reported.
        N)Ú
isinstancerÓ   rÕ   rL   )r   Úchildr   r   r   rH   ö  s    zFunctionEvent.append_cpu_childc                 C   s   t |tƒsJ ‚|| _dS )a#  Set the immediate CPU parent of type FunctionEvent

        One profiling FunctionEvent should have only one CPU parent such that
        the child's range interval is completely inside the parent's. We use
        this connection to determine the event is from top-level op or not.
        N)rÛ   rÓ   rI   )r   rP   r   r   r   rK   ÿ  s    zFunctionEvent.set_cpu_parentc                 C   s$   | j r
dS | jtdd„ | jD ƒƒ S )Nr   c                 S   s   g | ]
}|j ‘qS r   )rÖ   ©r3   rÜ   r   r   r   r5     r6   z7FunctionEvent.self_cpu_memory_usage.<locals>.<listcomp>)r1   rÖ   ra   rÕ   r   r   r   r   Úself_cpu_memory_usage  s
    ÿz#FunctionEvent.self_cpu_memory_usagec                 C   s$   | j r
dS | jtdd„ | jD ƒƒ S )Nr   c                 S   s   g | ]
}|j ‘qS r   )r×   rÝ   r   r   r   r5     r6   z8FunctionEvent.self_cuda_memory_usage.<locals>.<listcomp>)r1   r×   ra   rÕ   r   r   r   r   Úself_cuda_memory_usage  s
    ÿz$FunctionEvent.self_cuda_memory_usagec                 C   s$   | j r
dS | jtdd„ | jD ƒƒ S )Nr   c                 S   s   g | ]
}|j ‘qS r   )rÆ   rÝ   r   r   r   r5      r6   z5FunctionEvent.self_cpu_time_total.<locals>.<listcomp>)r1   rÆ   ra   rÕ   r   r   r   r   r_     s
    ÿz!FunctionEvent.self_cpu_time_totalc                 C   s   t dd„ | jD ƒƒS )Nc                 s   s   | ]}|j  ¡ V  qd S r   ©rt   rq   ©r3   Zkinfor   r   r   Ú	<genexpr>%  r6   z0FunctionEvent.cuda_time_total.<locals>.<genexpr>)ra   rs   r   r   r   r   rÇ   #  s    zFunctionEvent.cuda_time_totalc                 C   s(   t dd„ | jD ƒƒt dd„ | jD ƒƒ S )Nc                 s   s   | ]}|j  ¡ V  qd S r   rà   rá   r   r   r   râ   )  r6   z5FunctionEvent.self_cuda_time_total.<locals>.<genexpr>c                 S   s   g | ]
}|j ‘qS r   )rÇ   rÝ   r   r   r   r5   *  r6   z6FunctionEvent.self_cuda_time_total.<locals>.<listcomp>)ra   rs   rÕ   r   r   r   r   rÈ   '  s    ÿz"FunctionEvent.self_cuda_time_totalc                 C   s
   | j  ¡ S r   )r?   rq   r   r   r   r   rÆ   ,  s    zFunctionEvent.cpu_time_totalc                 C   s   | j S r   r§   r   r   r   r   r9   0  s    zFunctionEvent.keyc                 C   sZ   d  | j| j| j| jj| jjtdd„ | jD ƒƒ| j	| j
| jt| jƒ| j| j| j| j| j¡S )NzÏ<FunctionEvent id={} node_id={} cpu_time={} cpu_start={} cpu_end={} cpu_children={} cuda_time={} name={} thread={} input_shapes={} cpu_memory_usage={} cuda_memory_usage={} is_async={} is_remote={} seq_nr={}>c                 S   s   g | ]
}|j ‘qS r   )rÔ   rÝ   r   r   r   r5   >  r6   z*FunctionEvent.__repr__.<locals>.<listcomp>)rJ   rÔ   r:   rË   r?   r@   rA   r€   rÕ   rÌ   rp   r7   r�   rÖ   r×   r1   rr   rX   r   r   r   r   r¤   4  s$    ïÿzFunctionEvent.__repr__)	NNNr   r   r   FTrB   )r!   r"   r#   rŽ   r)   rÚ   rH   rK   r�   rÞ   rß   r_   rÇ   rÈ   rÆ   r9   r¤   r   r   r   r   rÓ   Ú  s.      ý
	






rÓ   c                   @   s0   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
S )rˆ   z:Used to average stats over multiple FunctionEvent objects.c                 C   sp   d | _ d| _d| _d| _d| _d| _d| _d| _d| _d | _	d | _
d | _d| _d| _d| _d| _d | _d | _d S )Nr   F)r9   rÊ   r:   r1   rr   rÆ   rÇ   r_   rÈ   r�   rY   rT   rÖ   r×   rÞ   rß   rÕ   rI   r   r   r   r   r)   N  s$    zFunctionEventAvg.__init__c                 C   s  | j d u rR|j | _ |j| _|j| _|j| _|j| _|j| _|j| _|j| _|j| _t	|t
tfƒsdJ ‚|j | j kstJ ‚|  j|j7  _|  j|j7  _|  j|j7  _|  j|j7  _|  j|j7  _|  j|j7  _|  j|j7  _|  j|j7  _|  j|j7  _| S r   )r9   r:   r1   rr   rI   rÕ   r�   rY   rT   rÛ   rÓ   rˆ   rÆ   rÇ   r_   rÈ   rÖ   r×   rÞ   rß   rÊ   ©r   Úotherr   r   r   r‰   b  s,    
zFunctionEventAvg.addc                 C   s
   |   |¡S r   )r‰   rã   r   r   r   Ú__iadd__~  s    zFunctionEventAvg.__iadd__c              
   C   s,   d  | j| j| j| j| jt| jƒ| j| j	¡S )Nz�<FunctionEventAvg key={} self_cpu_time={} cpu_time={}  self_cuda_time={} cuda_time={} input_shapes={} cpu_memory_usage={} cuda_memory_usage={}>)
rJ   r9   rÏ   rË   rÐ   rÌ   r€   r�   rÖ   r×   r   r   r   r   r¤   �  s    öÿzFunctionEventAvg.__repr__N)r!   r"   r#   rŽ   r)   r‰   rå   r¤   r   r   r   r   rˆ   L  s
   rˆ   c                   @   s   e Zd Zdd„ ZdS )ÚStringTablec                 C   s(   t |ƒdkrtj |¡n|| |< | | S rR   )rG   r™   Ú_CÚ	_demangle©r   r9   r   r   r   Ú__missing__–  s     zStringTable.__missing__N)r!   r"   r#   rê   r   r   r   r   ræ   •  s   ræ   c                    s  dd„ }d}d ‰i }g }g }t ƒ }g d¢}dd„ ‰ ‡fdd„}tj| Ž D ]N}	|	 ¡ }
ˆd u rj|
d	krj|	‰qHd
|
v rH|	 ¡ dks‚J ‚|	||	 ¡ |	 ¡ f< qHˆd ur¨ˆ ¡ r¬J ‚| D �]H}i }i }i }tƒ }d }|D �]&}	||	ƒ}|	 ¡ |v sò||v rþ| |¡ qÐ|	 	¡ dk�rx|d u�r\| ¡ |	 ¡ k�oH| 	¡ |	 	¡ k�oH| ¡ |	 ¡ k}|�r\| |¡ qÐ|	||< d||< d||< �n||	 	¡ dk�rž||v �sžJ d 
|¡ƒ‚|| }|| }|| }| ¡ |	 ¡ k}|	 ¡ }t|	 ¡ |	 ¡ || ¡  | ¡ ˆ |¡ˆ |	¡| ¡ | ¡ ‡ fdd„| ¡ D ƒ| ¡ ||||| ¡ d�}|�s€| ¡ �r€|||ƒ}||	|ƒ}|| dk�r€| | ¡ | ¡ ||¡ | |¡ ||= ||= ||= nV|	 	¡ dk�rô| ¡ D ]}||  |	 ¡ 7  < �q´| ¡ D ]}||  |	 ¡ 7  < �qØ|	}qÐq°|jdd„ d� |S )Nc                 S   s   |   ¡ |  ¡ fS )zr
        Returns a tuple to be used by parse_event_records for correlating start and
        end records.
        )rª   r:   )Úrecordr   r   r   Úget_record_keyž  s    z+parse_event_records.<locals>.get_record_keyr   )z profiler::_record_function_enterzprofiler::_record_function_exitzaten::is_leafzaten::output_nrzaten::_versionc                    s   g d¢}t ‡ fdd„|D ƒƒS )N))úautograd/__init__Z_make_grads)rí   Úbackward)ztorch/tensorrî   )ú_internal/common_utilsZprof_callable)rï   Zprof_func_call)rï   Zprof_meth_callc                    s&   g | ]}|d  ˆ v o|d ˆ v  ‘qS )r   rS   r   )r3   r{   ©Úentryr   r   r5   ¾  r6   zCparse_event_records.<locals>.filter_stack_entry.<locals>.<listcomp>)Úall)rñ   Zfiltered_entriesr   rð   r   Úfilter_stack_entryµ  s    z/parse_event_records.<locals>.filter_stack_entryc                    sD   |   ¡ dksJ ‚ˆ d usJ ‚||  ¡ |   ¡ f }| | ¡ˆ  |¡ S )NrB   )ru   r:   Zcuda_elapsed_usÚcpu_elapsed_us)Zcuda_recordZcuda_records_mapZcuda_time_0)Ústart_recordr   r   Úadjusted_timeÅ  s    z*parse_event_records.<locals>.adjusted_timeZ__start_profileZ__cuda_start_eventrB   Úpushr'   zŠExpected record with key {} to exist in range_starts.
                    This means that the pop event did not have a corresponding push.c                    s   g | ]}ˆ |ƒr|‘qS r   r   ©r3   rñ   )ró   r   r   r5     r6   z'parse_event_records.<locals>.<listcomp>)rÔ   r:   rp   r7   rØ   rÙ   rZ   r�   rY   rT   rÖ   r×   r1   rr   rX   Zmemory_allocc                 S   s   | j j| j j gS r   r>   rU   r   r   r   r=   4  r6   z%parse_event_records.<locals>.<lambda>r8   )ræ   rE   Úchainrp   ru   r:   rr   Úsetr‰   ÚkindrJ   rO   rÓ   rª   rô   Zfwd_thread_idZshapesrY   rT   rX   Zhas_cudarÚ   rL   ÚkeysrÖ   r×   Úsort)Zthread_recordsrì   r|   Zcuda_recordsÚ	functionsZrecord_stackZstring_tableZfiltered_out_namesrö   rë   rp   Zthread_record_listZcpu_memory_allocsZcuda_memory_allocsZrange_startsZfiltered_handlesZprev_recordZ
record_keyZ	duplicater@   rÖ   r×   r1   Zis_remote_eventZfeZ
cuda_startZcuda_endrª   r   )ró   rõ   r   r    �  s¾    

ÿ

ÿý
ÿþþ
ñ

ü
r    c                   @   s    e Zd ZdZdd„ Zdd„ ZdS )ÚEnforceUniquez0Raises an error if a key is seen more than once.c                 C   s   t ƒ | _d S r   )rú   Úseenr   r   r   r   r)   =  s    zEnforceUnique.__init__c                 G   s*   || j v rtdt|ƒ ƒ‚| j  |¡ d S )Nzduplicate key: )r   r˜   r€   r‰   ré   r   r   r   Úsee@  s    
zEnforceUnique.seeN)r!   r"   r#   rŽ   r)   r  r   r   r   r   rÿ   ;  s   rÿ   c              	   C   s8  dd l }| | ¡}|j|_i }| d¡D ]}tj |d ¡||d < q(d}g }i }tƒ }| |¡D ]N}	| 	|	d ¡ t
|	d d||	d  |	d |	d	 dd
�}
| |
¡ |
||
j< qbd}tƒ }| |¡D ]\}	| 	|	d |	d ¡ |	d dksú|	d dksúJ ‚||	d  }
|
 |	d d|	d |	d ¡ qÆ|jdd„ d� |S )Nr   z)SELECT _id_ as id, value FROM StringTableÚvaluerÔ   a&  
    SELECT
        start.id AS marker_id, start.name, start.timestamp AS start_time, end.timestamp AS end_time
    FROM
        CUPTI_ACTIVITY_KIND_MARKER AS start INNER JOIN CUPTI_ACTIVITY_KIND_MARKER AS end
        ON start.id = end.id
    WHERE
        start.name != 0 AND end.name = 0
    Z	marker_idrp   Ú
start_timeZend_time)rÔ   r:   rp   rØ   rÙ   r7   a¹  
    SELECT
        start.id AS marker_id, start.name, start.timestamp, end.timestamp,
        runtime._id_ AS runtime_id, runtime.cbid, runtime.start AS runtime_start, runtime.end AS runtime_end,
        kernel.start AS kernel_start, kernel.end AS kernel_end, kernel.name AS kernel_name
    FROM
        CUPTI_ACTIVITY_KIND_MARKER AS start
        INNER JOIN CUPTI_ACTIVITY_KIND_MARKER AS end
            ON start.id = end.id
        INNER JOIN CUPTI_ACTIVITY_KIND_RUNTIME as runtime
            ON (start.timestamp < runtime.start AND runtime.end < end.timestamp)
        INNER JOIN CUPTI_ACTIVITY_KIND_CONCURRENT_KERNEL AS kernel
            ON kernel.correlationId = runtime.correlationId
    Z
runtime_idZcbidéÓ   é   Zkernel_nameZkernel_startZ
kernel_endc                 S   s   | j jS r   )r?   r@   rU   r   r   r   r=   ƒ  r6   z$parse_nvprof_trace.<locals>.<lambda>r8   )Úsqlite3ÚconnectZRowZrow_factoryÚexecuter™   rç   rè   rÿ   r  rÓ   rL   rÔ   rÚ   rý   )rz   r  ÚconnÚstringsÚrZmarker_queryrþ   Zfunctions_mapÚuniqueÚrowr4   Zkernel_queryr   r   r   rµ   F  sD    
	
ú

ýrµ   rb   TFc                    sŽ  t | ƒdkrdS ˆdur8tt| ‡fdd„dd�||d�} td	d
„ | D ƒƒ}tdd
„ | D ƒƒd }d}	tdd
„ | D ƒƒd }
t|
dƒ}
d}g }| D ](}|jdur�t |jƒdkr�| |j¡ q�t |ƒdk}|rêtdd
„ |D ƒƒd }t|dƒ}g d¢}|�r| g d¢¡ |�r4| ddg¡ t	j
 ¡ �r4| ddg¡ | d¡ tdd
„ | D ƒƒ}|�r`| d¡ d‰ dg‰dg‰ˆ  g‰d}d-‡ ‡‡‡fdd„	}||ƒ |d d… D ]}||	ƒ �q¤|�rÌ| d!¡ ||
ƒ |�rè| d"¡ ||d#d$� ˆd }ˆd }ˆd }d}g ‰‡fd%d&„}td'd
„ | D ƒƒ}td(d
„ | D ƒƒ}|du�rV|d)| ƒ ||ƒ |�rp|d)| ƒ |d*ƒ ||ƒ ||j|Ž ƒ ||ƒ d}| D �]¸}||k�r¬ �qR|�rÄ|jdu�rÄ�q–n|d 7 }|jt|j|ƒ|j|j�sòt|j|ƒnd|j|jg}|�r&| |jt|j|ƒ|j|jg¡ |�rl| t|jƒt|jƒg¡ t	j
 ¡ �rl| t|jƒt|jƒg¡ | |j ¡ |�rŠ| |j!¡ |�r¨| t"|j#ƒd|
… ¡ |�rÞd}t |jƒdk�rÔ|jd d|… }| |¡ ||j|Ž ƒ |�r–dgt |ƒd   }|jd |… D ]"}||j||d|… g Ž ƒ �q| d¡ ||j|Ž ƒ �q–||ƒ |d+ t$|ƒ¡ƒ |�r„|d, t$|ƒ¡ƒ d %ˆ¡S ).zVPrints a summary of events (which can be a list of FunctionEvent or FunctionEventAvg).r   r‡   Nc                    s
   t | ˆ ƒS r   )rÁ   rU   )rc   r   r   r=   ™  r6   zbuild_table.<locals>.<lambda>T)r9   Úreverser†   c                 S   s$   g | ]}|j d uot|j ƒdk‘qS r   )r�   rG   r`   r   r   r   r5   �  r6   zbuild_table.<locals>.<listcomp>c                 S   s   g | ]}t |jƒ‘qS r   )rG   r9   r2   r   r   r   r5   Ÿ  r6   é   é   c                 S   s   g | ]}t t|jƒƒ‘qS r   )rG   r€   r�   r2   r   r   r   r5   £  r6   é-   c                 S   s   g | ]}t d d„ |D ƒƒ‘qS )c                 S   s   g | ]}t |ƒ‘qS r   )rG   rø   r   r   r   r5   ­  r6   z*build_table.<locals>.<listcomp>.<listcomp>)Úmax)r3   rY   r   r   r   r5   ­  r6   éK   )ÚNamez
Self CPU %zSelf CPUzCPU total %z	CPU totalzCPU time avg)z	Self CUDAzSelf CUDA %z
CUDA totalzCUDA time avgzCPU MemzSelf CPU MemzCUDA MemzSelf CUDA Memz
# of Callsc                 S   s   g | ]}|j d k‘qS )rB   )r:   r2   r   r   r   r5   Í  r6   zNode IDrk   é   ú>c                    s\   ˆd  d| t | ƒ d dˆ   7  < ˆd  d|  dˆ   7  < ˆd  | ˆ  7  < d S )Nr   z{: Ú}ú ú-)r€   )ÚpaddingÚtext_dir)ÚSPACING_SIZEÚheader_sep_lstÚline_length_lstÚrow_format_lstr   r   Ú
add_columnØ  s    (zbuild_table.<locals>.add_columnrS   zInput ShapeszSource Locationú<)r  c                    s   ˆ   | ¡ ˆ   d¡ d S )NÚ
)rL   )Ús)Úresultr   r   rL   ñ  s    
zbuild_table.<locals>.appendc                 S   s   g | ]
}|j ‘qS r   r^   r`   r   r   r   r5   õ  r6   c                 S   s   g | ]
}|j ‘qS r   )rÈ   r2   r   r   r   r5   ö  r6   ú=z1This report only display top-level ops statisticszSelf CPU time total: {}zCUDA time total: {})r  )&rG   r$   rD   Úanyr  ÚminrY   rL   Úextendr™   r³   Zis_availablera   rJ   rI   r9   r¼   r_   rÏ   r1   rÆ   rÍ   rË   rÐ   rÈ   rÎ   rÌ   rÀ   rÖ   rÞ   r×   rß   rÊ   r:   r€   r�   rº   Újoin)rM   rc   re   rd   r%   r&   rf   Zhas_input_shapesZname_column_widthZDEFAULT_COLUMN_WIDTHZshapes_column_widthZsrc_column_widthZstacksr4   Z	has_stackÚheadersZappend_node_idZMAX_STACK_ENTRYr   Ú_Z
row_formatZ
header_sepZline_lengthrL   r_   rÇ   Zevent_limitZ
row_valuesZ	src_fieldZempty_headersrñ   r   )r  r  r  r$  r  rc   r   rg   ‹  s   	ÿþÿ

þþÿ





ÿ÷
ûüüÿ
 
rg   )NNrb   TFF)(rE   Útypingr   r™   Ztorch.futuresr   Úcollectionsr   r   Úoperatorr   r   r   r	   r
   Ú
contextlibr   ÚImportErrorr   ÚobjectÚlistr$   r‘   r¦   r²   r¶   rº   r¼   rÀ   rÂ   rÃ   rÑ   rÒ   rÓ   rˆ   ræ   r    rÿ   rµ   rg   r   r   r   r   Ú<module>   sP     
 #On	rI G      ù