o
    װie                     @   s^   d dl mZ d dlZd dlZd dlmZ G dd dejZG dd deZ	G dd	 d	eZ
dS )
    )pathN)memory_hookc                   @   sn   e Zd ZdZd ZdddZdd Zdd Zdd	d
Zdd Z	dd Z
dd ZejfddZdejfddZdS )LineProfileHookaZ  Code line CuPy memory profiler.

    This profiler shows line-by-line GPU memory consumption using traceback
    module. But, note that it can trace only CPython level, no Cython level.
    ref. https://github.com/cython/cython/issues/1755

    Example:
        Code example::

            from cupy.cuda import memory_hooks
            hook = memory_hooks.LineProfileHook()
            with hook:
                # some CuPy codes
            hook.print_report()

        Output example::

            _root (4.00KB, 4.00KB)
              lib/python3.6/unittest/__main__.py:18:<module> (4.00KB, 4.00KB)
                lib/python3.6/unittest/main.py:255:runTests (4.00KB, 4.00KB)
                  tests/cupy_tests/test.py:37:test (1.00KB, 1.00KB)
                  tests/cupy_tests/test.py:38:test (1.00KB, 1.00KB)
                  tests/cupy_tests/test.py:39:test (2.00KB, 2.00KB)

        Each line shows::

            {filename}:{lineno}:{func_name} ({used_bytes}, {acquired_bytes})

        where *used_bytes* is the memory bytes used from CuPy memory pool, and
        *acquired_bytes* is the actual memory bytes the CuPy memory pool
        acquired from GPU device.
        *_root* is a root node of the stack trace to show total memory usage.

    Args:
        max_depth (int): maximum depth to follow stack traces.
            Default is 0 (no limit).
    r   c                 C   s(   i | _ td d | _tt| _|| _d S N)_memory_framesMemoryFrame_rootr   abspath__file__	_filename
_max_depth)self	max_depth r   W/home/ubuntu/.local/lib/python3.10/site-packages/cupy/cuda/memory_hooks/line_profile.py__init__1   s   
zLineProfileHook.__init__c                 C   s   | j |d d S )N)
used_bytes_create_frame_tree)r   	device_idsizemem_sizer   r   r   malloc_preprocess8      z!LineProfileHook.malloc_preprocessc                 C   s   | j |d d S )N)acquired_bytesr   )r   r   r   r   r   r   alloc_preprocess<   r   z LineProfileHook.alloc_preprocessc                 C   s   | j  j|7  _| j  j|7  _| j }t|  D ]*\}}d| j  k r,|d kr- d S  | ||}| j|7  _| j|7  _|}qd S )Nr      )r   r   r   	enumerate_extract_stackframesr   
_add_frame)r   r   r   parentdepth
stackframememory_framer   r   r   r   ?   s   z"LineProfileHook._create_frame_treec                    s,   t  }dd |D } fdd|D }|S )Nc                 S   s   g | ]}t |qS r   )
StackFrame.0str   r   r   
<listcomp>M   s    z8LineProfileHook._extract_stackframes.<locals>.<listcomp>c                    s   g | ]
}|j  jkr|qS r   )filenamer   r%   r   r   r   r(   N   s    )	tracebackextract_stack)r   stackframesr   r*   r   r   K   s   
z$LineProfileHook._extract_stackframesc                 C   s   ||j |j|jfS r   )r)   linenonamer   r    r"   r   r   r   
_key_frameR   s
   zLineProfileHook._key_framec                 C   s<   |  ||}|| jv r| j| }|S t||}|| j|< |S r   )r1   r   r   )r   r    r"   keyr#   r   r   r   r   X   s   



zLineProfileHook._add_framec                 C   sB   d| j   }|| | j jD ]
}| j|d|d q|  dS )z)Prints a report of line memory profiling.z_root (%s, %s)
r   r!   fileN)r   humanized_byteswritechildren_print_frameflush)r   r4   linechildr   r   r   print_reporta   s
   
zLineProfileHook.print_reportc           
      C   sf   d|d  }|j }| \}}d||j|j|j||f }|| |jD ]}	| j|	|d |d q$d S )N    z%s%s:%s:%s (%s, %s)
r   r3   )r"   r5   r)   r.   r/   r6   r7   r8   )
r   r#   r!   r4   indentr'   r   r   r:   r;   r   r   r   r8   i   s   

zLineProfileHook._print_frameN)r   )r   r   )__name__
__module____qualname____doc__r/   r   r   r   r   r   r1   r   sysstdoutr<   r8   r   r   r   r   r      s    &

	r   c                   @   s   e Zd ZdZdd ZdS )r$   zCompatibility layer for outputs of traceback.extract_stack().

    Attributes:
        filename (string): filename
        lineno (int): line number
        name (string): function name
    c                 C   sH   t |tr|d | _|d | _|d | _d S |j| _|j| _|j| _d S )Nr   r   r>   )
isinstancetupler)   r.   r/   )r   objr   r   r   r   ~   s   


zStackFrame.__init__N)r@   rA   rB   rC   r   r   r   r   r   r$   u   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   a  A single stack frame along with sum of memory usage at the frame.

    Attributes:
        stackframe (FrameSummary): stackframe from traceback.extract_stack().
        parent (MemoryFrame): parent frame, that is, caller.
        children (list of MemoryFrame): child frames, that is, callees.
        used_bytes (int): memory bytes that users used from CuPy memory pool.
        acquired_bytes (int): memory bytes that CuPy memory pool acquired
            from GPU device.
    c                 C   s&   || _ g | _| | d| _d| _d S )Nr   )r"   r7   _set_parentr   r   r0   r   r   r   r      s
   

zMemoryFrame.__init__c                 C   s    |  | j}|  | j}||fS r   )_humanized_sizer   r   )r   r   r   r   r   r   r5      s   zMemoryFrame.humanized_bytesc                 C   s,   |r||j vr|| _|j |  d S d S d S r   )r7   r    append)r   r    r   r   r   rI      s   zMemoryFrame._set_parentc                 C   s6   dD ]}|dk rd||f   S |d }qd|df S )N) KMGTPEg      @z%3.2f%sBz%.2f%sBZr   )r   r   unitr   r   r   rJ      s
   
zMemoryFrame._humanized_sizeN)r@   rA   rB   rC   r   r5   rI   rJ   r   r   r   r   r      s    r   )osr   rD   r+   	cupy.cudar   
MemoryHookr   objectr$   r   r   r   r   r   <module>   s    m