3
I4W^/„  ã               @   s  d dl Z d dlZd dlmZmZ d dlmZ 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G dd„ de	ƒZG dd„ de	ƒZeddddgƒ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d+d)d*„ZdS ),é    N)ÚdefaultdictÚ
namedtuple)Ú
attrgetterc                   sl   e Zd ZdZ‡ f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                s   t t| ƒj||Ž d| _d S )NF)Úsuperr   Ú__init__Ú_cpu_children_populated)ÚselfÚargsÚkwargs)Ú	__class__© ú8/tmp/pip-build-e66j97b2/torch/torch/autograd/profiler.pyr   
   s    zEventList.__init__c             C   s   | j ƒ S )N)Útable)r	   r   r   r   Ú__str__   s    zEventList.__str__c       	      C   sÈ   | j r
dS t| tdƒd�}tj|tdƒd�}x�|D ]ˆ\}}t|dd„ d�}g }d}xf|D ]^}xNt|ƒdkrª|d	 }|jj|jjks’|jj|jjkrœ|j	ƒ  q^|j
|ƒ P q^W |j|ƒ qXW q2W d| _dS )
a3  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 partialy, this function
        will not record a parent child relationship between then.
        NÚthread)Úkeyc             S   s   | j j| j j gS )N)Úcpu_intervalÚstartÚend)Úeventr   r   r   Ú<lambda>4   s    z1EventList.populate_cpu_children.<locals>.<lambda>r   é   Téÿÿÿÿ)Úcpu_children_populatedÚsortedr   Ú	itertoolsÚgroupbyÚlenr   r   r   ÚpopÚappend_cpu_childÚappendr   )	r	   ÚeventsÚthreadsÚ	thread_idZthread_eventsZcurrent_eventsZcur_endr   Úparentr   r   r   Úpopulate_cpu_children   s,    


zEventList.populate_cpu_childrenc             C   s   t dd„ | D ƒƒS )Nc             S   s   g | ]
}|j ‘qS r   )Úself_cpu_time_total)Ú.0r   r   r   r   ú
<listcomp>I   s    z1EventList.self_cpu_time_total.<locals>.<listcomp>)Úsum)r	   r   r   r   r'   G   s    zEventList.self_cpu_time_totalc             C   s   | j S )N)r   )r	   r   r   r   r   K   s    z EventList.cpu_children_populatedNéd   c             C   s   t | |||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``, ``count``.

        Returns:
            A string containing the table.
        )Úsort_byÚ	row_limitÚheader)Úbuild_table)r	   r,   r-   r.   r   r   r   r   O   s    zEventList.tablec             C   sü   ddl }t|dƒ�à}g }d}xÄ| D ]¼}|jt|jd|jj|jjƒ |jdi d�ƒ xŒ|j	D ]‚}|jt|jd|jj|jd|di d	�ƒ |jt|jd
|j
j|jd|di d	�ƒ |jt|jd|j
j|j
jƒ |jdi d�ƒ |d7 }qXW q"W |j||ƒ W dQ R X 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ÚXzCPU functions)ÚnameÚphÚtsZdurÚtidÚpidr
   ÚsZcpu_to_cuda)r2   r3   r4   r5   r6   ÚidÚcatr
   ÚfzCUDA functionsr   )ÚjsonÚopenr!   Údictr2   r   r   Ú
elapsed_usr   ÚkernelsÚintervalÚdeviceÚdump)r	   Úpathr;   r:   Zchrome_eventsÚnext_idÚevtÚkr   r   r   Úexport_chrome_trace^   sT    




zEventList.export_chrome_traceFc             C   sH   | j ƒ  ttƒ}dd„ }x"| D ]}||||ƒ j||ƒ qW t|jƒ ƒS )aæ  Averages all function events over their keys.

        @param group_by_input_shapes The key would become
        (event name, input dimensions) rather than just event name.
        This is useful to see which dimensionality contributes to the runtime
        the most and may help with dimension specific optimizations or
        choosing best candidates for quantization (aka fitting a roof line)

        Returns:
            An EventList containing FunctionEventAvg objects.
        c             S   s   |s
| j S | j t| jƒfS )N)r   ÚstrÚinput_shapes)r   Úgroup_by_input_shapesr   r   r   Úget_key§   s    z'EventList.key_averages.<locals>.get_key)r&   r   ÚFunctionEventAvgÚaddr   Úvalues)r	   rJ   ÚstatsrK   rE   r   r   r   Úkey_averages˜   s    
zEventList.key_averagesc             C   s,   t ƒ }x| D ]}||7 }d|_qW d|_|S )zVAverages all events.

        Returns:
            A FunctionEventAvg object.
        NZTotal)rL   r   )r	   Z
total_statrE   r   r   r   Útotal_average°   s    

zEventList.total_average)Nr+   N)F)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r&   Úpropertyr'   r   r   rG   rP   rQ   Ú__classcell__r   r   )r   r   r      s   6
:
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 )Úprofilea¹
  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.

    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.

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

    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   s,   || _ || _d | _| j sd S d| _|| _d S )NF)ÚenabledÚuse_cudaÚfunction_eventsÚenteredÚrecord_shapes)r	   rY   rZ   r]   r   r   r   r   î   s    zprofile.__init__c             C   sT   | j s
d S | jrtdƒ‚d| _| jr.tjjjntjjj}tjj	tjj
|| jƒƒ | S )Nz*autograd profiler traces are not reentrantT)rY   r\   ÚRuntimeErrorrZ   ÚtorchÚautogradÚProfilerStateZCUDAZCPUÚ_enable_profilerÚProfilerConfigr]   )r	   Zprofiler_kindr   r   r   Ú	__enter__÷   s    
zprofile.__enter__c             C   s&   | j s
d S tjjƒ }tt|ƒƒ| _dS )NF)rY   r_   r`   Ú_disable_profilerr   Úparse_cpu_tracer[   )r	   Úexc_typeÚexc_valÚexc_tbÚrecordsr   r   r   Ú__exit__  s
    
zprofile.__exit__c             C   s   | j d krdS t| j ƒS )Nz#<unfinished torch.autograd.profile>)r[   Úrepr)r	   r   r   r   Ú__repr__
  s    
zprofile.__repr__c             C   s   | j d krdS t| j ƒS )Nz#<unfinished torch.autograd.profile>)r[   rH   )r	   r   r   r   r     s    
zprofile.__str__c             C   s    | j d krtdƒ‚| j jƒ  d S )Nz/can't export a trace that didn't finish running)r[   r^   r&   )r	   r   r   r   Ú_check_finish  s    
zprofile._check_finishNr+   c             C   s   | j ƒ  | jj|||d�S )N)r,   r-   r.   )rn   r[   r   )r	   r,   r-   r.   r   r   r   r     s    zprofile.tablec             C   s   | j ƒ  | jj|ƒS )N)rn   r[   rG   )r	   rC   r   r   r   rG     s    zprofile.export_chrome_tracec             C   s   | j ƒ  | jj|ƒS )N)rn   r[   rP   )r	   Zgroup_by_input_shaper   r   r   rP   $  s    zprofile.key_averagesc             C   s   | j ƒ  | jjƒ S )N)rn   r[   rQ   )r	   r   r   r   rQ   )  s    zprofile.total_averagec             C   s   | j ƒ  | jjS )zl Returns total time spent on CPU obtained as a sum of
        all self times across all the events.
        )rn   r[   r'   )r	   r   r   r   r'   .  s    zprofile.self_cpu_time_total)TFF)Nr+   N)F)rR   rS   rT   rU   r   rd   rk   rm   r   rn   r   r   rG   rP   rQ   rV   r'   r   r   r   r   rX   ¾   s    /
	





rX   c               @   s(   e Zd ZdZdd„ Zdd„ Zdd„ ZdS )	Úrecord_functionaK  Context manager that adds a label to a block of Python code when running autograd
    profiler.  It is useful when tracing the code profile.

    Arguments:
        name (str): Label assigned to the block of code.

    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
    c             C   s
   || _ d S )N)r2   )r	   r2   r   r   r   r   U  s    zrecord_function.__init__c             C   s   t jj| jƒ d S )N)r_   r`   Z_push_ranger2   )r	   r   r   r   rd   X  s    zrecord_function.__enter__c             G   s   t jjƒ  dS )NF)r_   r`   Z
_pop_range)r	   r
   r   r   r   rk   [  s    
zrecord_function.__exit__N)rR   rS   rT   rU   r   rd   rk   r   r   r   r   ro   7  s   ro   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 )NF)rY   r\   r]   )r	   rY   r]   r   r   r   r   ±  s    zemit_nvtx.__init__c             C   sJ   | j s
d S | jrtdƒ‚d| _tjjƒ  tjjtjjtjj	j
| jƒƒ | S )Nz0NVTX annotation context manager is not reentrantT)rY   r\   r^   r_   ÚcudaÚsynchronizer`   rb   rc   ra   ZNVTXr]   )r	   r   r   r   rd   ¶  s    

zemit_nvtx.__enter__c             C   s"   | j s
d S tjjƒ  tjjƒ  dS )NF)rY   r_   rq   rr   r`   re   )r	   rg   rh   ri   r   r   r   rk   Å  s
    

zemit_nvtx.__exit__N)TF)rR   rS   rT   rU   r   rd   rk   r   r   r   r   rp   `  s   P
rp   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)rC   r   r   r   Úload_nvprofÍ  s    rt   c             C   s>   d}d}| |krdj | | ƒS | |kr4dj | | ƒS dj | ƒS )z+Defines how to format time in FunctionEventg     @�@z{:.3f}sz{:.3f}msz{:.3f}usg    €„.A)Úformat)Útime_usZUS_IN_SECONDZUS_IN_MSr   r   r   Úformat_timeÙ  s    rw   c             C   s*   |dkr| dkst ‚dS dj| d | ƒS )z+Defines how to format time in FunctionEventr   ÚNaNz{:.2f}%g      Y@)ÚAssertionErrorru   )rv   Ztotal_time_usr   r   r   Úformat_time_shareä  s    rz   c                s   t ‡ fdd„ƒS )Nc                s   t t| ˆ ƒƒS )N)rw   Úgetattr)r	   )r2   r   r   r   í  s    z attr_formatter.<locals>.<lambda>)rV   )r2   r   )r2   r   Úattr_formatterì  s    r|   c               @   sP   e Zd Z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'   c             C   s   | j dkrdS d| j | j  S )Nr   g        g      ð?)Úcountr€   )r	   r   r   r   r~   û  s    zFormattedTimesMixin.cpu_timec             C   s   | j dkrdS d| j | j  S )Nr   g        g      ð?)r‚   r�   )r	   r   r   r   r   ÿ  s    zFormattedTimesMixin.cuda_timeN)rR   rS   rT   rU   r|   Úcpu_time_strÚcuda_time_strÚcpu_time_total_strÚcuda_time_total_strÚself_cpu_time_total_strrV   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 )N)r   r   )r	   r   r   r   r   r   r     s    zInterval.__init__c             C   s   | j | j S )N)r   r   )r	   r   r   r   r>   	  s    zInterval.elapsed_usN)rR   rS   rT   r   r>   r   r   r   r   rˆ     s   rˆ   ÚKernelr2   rA   r@   c               @   sb   e Zd ZdZd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dd„ ZdS )ÚFunctionEventz.Profiling information about a single function.Nc             C   s:   || _ || _t||ƒ| _|| _g | _d| _g | _|| _d S )Nr   )	r8   r2   rˆ   r   r   r?   r‚   Úcpu_childrenrI   )r	   r8   r2   r   Ú	cpu_startÚcpu_endrI   r   r   r   r     s    zFunctionEvent.__init__c             C   s   | j jt||t||ƒƒƒ d S )N)r?   r!   r‰   rˆ   )r	   r2   rA   r   r   r   r   r   Úappend_kernel  s    zFunctionEvent.append_kernelc             C   s   t |tƒst‚| jj|ƒ dS )z®Append a CPU child of type FunctionEvent.

        One is supposed to append only dirrect children to the event to have
        correct self cpu time being reported.
        N)Ú
isinstancerŠ   ry   r‹   r!   )r	   Úchildr   r   r   r       s    zFunctionEvent.append_cpu_childc             C   s   | j tdd„ | jD ƒƒ S )Nc             S   s   g | ]
}|j ‘qS r   )r€   )r(   r�   r   r   r   r)   ,  s    z5FunctionEvent.self_cpu_time_total.<locals>.<listcomp>)r€   r*   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 jƒ V  qd S )N)r@   r>   )r(   Zkinfor   r   r   ú	<genexpr>1  s    z0FunctionEvent.cuda_time_total.<locals>.<genexpr>)r*   r?   )r	   r   r   r   r�   /  s    zFunctionEvent.cuda_time_totalc             C   s
   | j jƒ S )N)r   r>   )r	   r   r   r   r€   3  s    zFunctionEvent.cpu_time_totalc             C   s   | j S )N)r2   )r	   r   r   r   r   7  s    zFunctionEvent.keyc             C   sB   dj | j| j| jj| jjtdd„ | jD ƒƒ| j| j	| j
t| jƒƒ	S )Nzx<FunctionEvent id={} cpu_time={} cpu_start={} cpu_end={} cpu_children={} cuda_time={} name={} thread={} input_shapes={}>c             S   s   g | ]
}|j ‘qS r   )r8   )r(   r�   r   r   r   r)   C  s    z*FunctionEvent.__repr__.<locals>.<listcomp>)ru   r8   rƒ   r   r   r   rH   r‹   r„   r2   r   rI   )r	   r   r   r   rm   ;  s    zFunctionEvent.__repr__)N)rR   rS   rT   rU   r   rŽ   r    rV   r'   r�   r€   r   rm   r   r   r   r   rŠ     s   

	rŠ   c               @   s*   e Zd ZdZdd„ Zd
dd„Zdd„ Zd	S )rL   z:Used to average stats over multiple FunctionEvent objects.c             C   s(   d | _ d| _d| _d| _d| _d | _d S )Nr   )r   r‚   r€   r�   r'   rI   )r	   r   r   r   r   N  s    zFunctionEventAvg.__init__Fc             C   s”   | j d kr|j | _ |r|j| _| s4|j| jks4t‚t|tƒsBt‚|j | j ksRt‚|  j|j7  _|  j|j7  _|  j	|j	7  _	|  j
d7  _
| S )Nr   )r   rI   ry   r�   rŠ   r€   r~   r�   r   r'   r‚   )r	   ÚotherrJ   r   r   r   rM   V  s    
zFunctionEventAvg.addc             C   s    dj | j| j| j| jt| jƒƒS )NzS<FunctionEventAvg key={} self_cpu_time={} cpu_time={} cuda_time={} input_shapes={}>)ru   r   r‡   rƒ   r„   rH   rI   )r	   r   r   r   rm   h  s    zFunctionEventAvg.__repr__N)F)rR   rS   rT   rU   r   rM   rm   r   r   r   r   rL   L  s   
rL   c               @   s   e Zd Zdd„ ZdS )ÚStringTablec             C   s   t jj|ƒ| |< | | S )N)r_   Ú_CÚ	_demangle)r	   r   r   r   r   Ú__missing__y  s    zStringTable.__missing__N)rR   rS   rT   r–   r   r   r   r   r“   x  s   r“   c          	      sb  d}d ‰i ‰ g }g }t ƒ }‡ ‡fdd„}xLtj| Ž D ]>}|jƒ dkrJ|‰q4|jƒ dkr4|jƒ dksft‚|ˆ |jƒ < q4W ˆd k	s‚t‚xÊtj| Ž D ]¼}|jƒ dkr¢qŽqŽ|jƒ dkrÆ|j||fƒ |d7 }qŽ|jƒ d	krŽ|jƒ \}}t	|||jƒ  |j
ƒ ˆj|ƒˆj|ƒ|jƒ d
�}	|jƒ �r@||ƒ}
||ƒ}|	j|jƒ |jƒ |
|ƒ |j|	ƒ qŽW |jdd„ d� |S )Nr   c                s0   | j ƒ dkst‚ˆ | j ƒ  }|j| ƒˆj|ƒ S )Nr   r   )rA   ry   Zcuda_elapsed_usÚcpu_elapsed_us)Zcuda_recordZcuda_time_0)Úcuda_recordsÚstart_recordr   r   Úadjusted_timeŽ  s    z&parse_cpu_trace.<locals>.adjusted_timeZ__start_profileZ__cuda_start_eventr   ÚmarkÚpushr   )r8   r2   r   rŒ   r�   rI   c             S   s   | j jS )N)r   r   )rE   r   r   r   r   ´  s    z!parse_cpu_trace.<locals>.<lambda>)r   r   )r“   r   Úchainr2   rA   ry   Úkindr!   r   rŠ   r$   r—   ZshapesZhas_cudarŽ   Úsort)Zthread_recordsrD   Ú	functionsZrecord_stackZstring_tablerš   ÚrecordZfunction_idr   ZfeZ
cuda_startZcuda_endr   )r˜   r™   r   rf   �  sN    



rf   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 )N)ÚsetÚseen)r	   r   r   r   r   ½  s    zEnforceUnique.__init__c             G   s*   || j krtdt|ƒ ƒ‚| j j|ƒ d S )Nzduplicate key: )r¤   r^   rH   rM   )r	   r   r   r   r   ÚseeÀ  s    
zEnforceUnique.seeN)rR   rS   rT   rU   r   r¥   r   r   r   r   r¢   »  s   r¢   c             C   s6  dd l }|j| ƒ}|j|_i }x*|jdƒD ]}tjj|d ƒ||d < q*W d}g }i }tƒ }xZ|j|ƒD ]L}	|j	|	d ƒ t
|	d ||	d  |	d |	d	 dd
�}
|j|
ƒ |
||
j< qhW d}tƒ }x^|j|ƒD ]P}	|j	|	d |	d ƒ |	d dksöt‚||	d  }
|
j|	d d|	d |	d ƒ qÎW |jdd„ d� |S )Nr   z)SELECT _id_ as id, value FROM StringTableÚvaluer8   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_idr2   Ú
start_timeÚend_time)r8   r2   rŒ   r�   r   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 )N)r   r   )rE   r   r   r   r      s    z$parse_nvprof_trace.<locals>.<lambda>)r   )Úsqlite3ÚconnectZRowZrow_factoryÚexecuter_   r”   r•   r¢   r¥   rŠ   r!   r8   ry   rŽ   rŸ   )rC   rª   ÚconnÚstringsÚrZmarker_queryr    Zfunctions_mapÚuniqueÚrowrE   Zkernel_queryr   r   r   rs   Æ  s>    



rs   r+   c                s$  t | ƒdkrdS ˆdk	r2tt| ‡fdd„dd�ƒ} tdd	„ | D ƒƒ}td
d	„ | D ƒƒd }d}d}ddddddddddg
}d‰ dg‰dg‰ˆ  g‰‡ ‡‡‡fdd„}	|	|ƒ x|dd… D ]}
|	|ƒ qºW |rà|jdƒ |	|ƒ ˆd ‰ˆd ‰ˆd ‰d}	g ‰‡fdd„}tdd	„ | D ƒƒ}td d	„ | D ƒƒ}|dk	�rN|d!ˆ ƒ ||ƒ |ˆƒ |ˆj|Ž ƒ |ˆƒ x€| d|… D ]p}|jt	|j
|ƒ|jt	|j|ƒ|j|jt	|j|ƒ|j|j|jg
}|�rÚ|jt|jƒd|… ƒ |ˆj|Ž ƒ �qzW |ˆƒ |d"jt|ƒƒƒ |d#jt|ƒƒƒ djˆƒS )$zVPrints a summary of events (which can be a list of FunctionEvent or FunctionEventAvg).r   Ú Nc                s
   t | ˆ ƒS )N)r{   )rE   )r,   r   r   r     s    zbuild_table.<locals>.<lambda>T)r   Úreversec             S   s   g | ]}|j d k	‘qS )N)rI   )r(   r   r   r   r   r)     s    zbuild_table.<locals>.<listcomp>c             S   s   g | ]}t |jƒ‘qS r   )r   r   )r(   rE   r   r   r   r)     s    é   é   é#   ÚNamezSelf CPU total %zSelf CPU totalzCPU total %z	CPU totalzCPU time avgzCUDA total %z
CUDA totalzCUDA time avgzNumber of Callsé   c                sL   ˆd  dt | ƒ d 7  < ˆd  d|  d 7  < ˆd  | ˆ  7  < d S )Nr   z{: <z}  ú-z  )rH   )Úpadding)ÚSPACING_SIZEÚ
header_sepÚline_lengthÚ
row_formatr   r   Ú
add_column+  s    zbuild_table.<locals>.add_columnr   zInput Shapesc                s   ˆ j | ƒ ˆ j dƒ d S )NÚ
)r!   )r7   )Úresultr   r   r!   @  s    
zbuild_table.<locals>.appendc             S   s   g | ]
}|j ‘qS r   )r'   )r(   r   r   r   r   r)   D  s    c             S   s   g | ]
}|j ‘qS r   )r�   )r(   rE   r   r   r   r)   E  s    ú=zSelf CPU time total: {}zCUDA time total: {})r   r   r   ÚanyÚmaxr!   r*   ru   r   rz   r'   r‡   r€   r…   rƒ   r�   r†   r„   r‚   rH   rI   rw   Újoin)r"   r,   r.   r-   Zhas_input_shapesÚname_column_widthZDEFAULT_COLUMN_WIDTHZSHAPES_COLUMN_WIDTHÚheadersr¿   Ú_r!   r'   r�   rE   Z
row_valuesr   )r»   r¼   r½   rÁ   r¾   r,   r   r/     s€    



r/   )NNr+   )r   r_   Úcollectionsr   r   Úoperatorr   Úlistr   ÚobjectrX   ro   rp   rt   rw   rz   r|   r}   rˆ   r‰   rŠ   rL   r“   rf   r¢   rs   r/   r   r   r   r   Ú<module>   s,    7y)m	;,	:B