o
    Xi                     @  sh   d dl mZ d dlZd dlZdddZG dd	 d	Zd
d ZG dd dZ	d d!ddZd"d#ddZ	dS )$    )annotationsNpidintreturnc                 C  s    ddl }|| }| j}|S )z
    Returns the physical memory used by a process.

    Args:
        pid: Process id, current one is `os.getpid()`.

    Returns:
         Physical memory.

    It relies on the module *psutil*.
    r   N)psutilProcessmemory_inforss)r   r   processmem r   P/home/ubuntu/.local/lib/python3.10/site-packages/onnxscript/tools/memory_peak.pyget_memory_rss
   s   

r   c                   @  sJ   e Zd Zdd Zdddd	ZdddZdddZdd ZedddZ	dS )Monitorc                 C  s"   d| _ d| _d| _d| _d| _d S )Nr   )max_peakaverage
n_measuresbeginendselfr   r   r   __init__   s
   
zMonitor.__init__   unitr   r   dict[str, float]c                 C  sB   t |}t| j| | jd | j | | j| | j| | j| dS )Ng      ?)peakmeannr   r   )floatdictr   r   r   r   r   )r   r   funitr   r   r   to_dict%   s   zMonitor.to_dictstrc                 C  s&   | j j d| j d| j d| j dS )Nz(peak=z
, average=z, n=))	__class____name__r   r   r   r   r   r   r   __repr__/   s   zMonitor.__repr__r   r   c                 C  sD   | j dkr|| _t|| j| _|  j|7  _|| _|  j d7  _ d S )Nr   r   )r   r   maxr   r   r   )r   r   r   r   r   update5   s   
zMonitor.updatec                 C  s@   | | j | | j | | j | | j | | j d S N)sendr   r   r   r   r   )r   connr   r   r   r*   =   s
   zMonitor.sendc                 C  s<   |  }|  |_|  |_|  |_|  |_|  |_|S r)   )recvr   r   r   r   r   )clsr+   mr   r   r   r,   D   s   




zMonitor.recvN)r   )r   r   r   r   )r   r"   )r   r   )r   r   )
r%   
__module____qualname__r   r!   r&   r(   r*   classmethodr,   r   r   r   r   r      s    


r   c                   s  |  d |  }|  }|  }dd l}||}|rLddlm}mmm}m	} |  | }	fddt
|	D   fdd}
dd t
|	D }ng }t }|  d 	 | j}|| |rst|
 |D ]	\}}|| qi| j|d
r|  }|dkrnqW| j}|| |rt|
 |D ]	\}}|| q| |  |  t| |D ]}| |  q|r|  |   d S )Nr   )nvmlDeviceGetCountnvmlDeviceGetHandleByIndexnvmlDeviceGetMemoryInfonvmlInitnvmlShutdownc                   s   g | ]} |qS r   r   .0i)r4   r   r   
<listcomp>k   s    z'_process_memory_spy.<locals>.<listcomp>c                     s   fdd D S )Nc                   s   g | ]} |j qS r   )used)r9   h)r5   r   r   r;   n   s    z9_process_memory_spy.<locals>.gpu_used.<locals>.<listcomp>r   r   )handlesr5   r   r   gpu_usedm   s   z%_process_memory_spy.<locals>.gpu_usedc                 S  s   g | ]}t  qS r   )r   r8   r   r   r   r;   p   s    T)timeout)r*   r,   r   r   pynvmlr3   r4   r5   r6   r7   ranger   r   r	   r(   zippolllenclose)r+   r   r@   cudar   r
   r3   r6   r7   n_gpusr?   gpuscpur   rgcoder   r   )r>   r4   r5   r   _process_memory_spyO   sN   







rO   c                   @  s0   e Zd ZdZddd
dZdddZdddZdS )	MemorySpyz
    Information about the spy. It class method `start`.
    Method `stop` can be called to end the measure.

    Args:
        pid: process id  of the process to spy on
        delay: spy on every delay seconds
        cuda: enable cuda monitoring
    {Gz?Fr   r   delayr   rH   boolc                 C  s   || _ || _|| _|   d S r)   )r   rR   rH   start)r   r   rR   rH   r   r   r   r      s   zMemorySpy.__init__r   c                 C  s   t  \| _| _t jt| jfd| _| j  | j }|dkr(t	d| d| j
| j | j
| j | j
| jr>dnd | j }|dkrRt	d| d| S )z+Starts another process and tells it to spy.)targetargsr2   z0The child processing is supposed to send -2 not .r   r   z6The child processing is supposed to send -2 again not )multiprocessingPipeparent_conn
child_connr   rO   child_processrT   r,   RuntimeErrorr*   r   rR   rH   )r   datar   r   r   rT      s"   



zMemorySpy.startdict[str, list[Monitor]]c                 C  sx   | j d t| j g}| j  }g }t|D ]}|t| j  q| j   | j  t	|d}| j
r:||d< |S )zStops spying on.rA   )rK   rJ   )rZ   r*   r   r,   rC   appendrG   r\   joinr   rH   )r   rK   rI   rJ   _resr   r   r   stop   s   



zMemorySpy.stopN)rQ   F)r   r   rR   r   rH   rS   )r   rP   )r   r_   )r%   r/   r0   __doc__r   rT   rd   r   r   r   r   rP      s
    

rP   rQ   F
int | NonerR   r   rH   rS   c                 C  s   | du rt  } t| ||S )a&  Starts the memory spy. The function starts another
    process spying on the one sent as an argument.

    Example::

    .. code-block:: python

        from onnxscript.tools.memory_peak import start_spying_on, flatten

        p = start_spying_on()
        # ...
        # code to measure
        # ...
        stat = p.stop()
        print(stat)
        print(flatten(stat))

    Args:
        pid: process id to spy or the the current one.
        delay: delay between two measures.
        cuda: True or False to get memory for cuda devices
    N)osgetpidrP   )r   rR   rH   r   r   r   start_spying_on   s   ri    psr_   prefixr"   r   c                   s~   | d d j dd}d| v r0t| d D ]\}}|j dd D ]\}}||d| d| < q q r= fdd	| D }|S )
z9Flattens a dictionary produced by :meth:`MemorySpy.stop`.rK   r   i   )r   rJ   gpurb   c                   s   i | ]\}}  | |qS r   r   )r9   kvrl   r   r   
<dictcomp>   s    zflatten.<locals>.<dictcomp>)r!   	enumerateitems)rk   rl   obsr:   rM   rn   ro   r   rp   r   flatten   s   ru   )r   r   r   r   )NrQ   F)r   rf   rR   r   rH   rS   r   rP   )rj   )rk   r_   rl   r"   r   r   )

__future__r   rX   rg   r   r   rO   rP   ri   ru   r   r   r   r   <module>   s   
2F9