
    .`i-(                     z   d dl Z d dl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
Z
d dlZd dlZd dlmZ ddlmZmZ ded	efd
Zded	efdZe	dded	efd            Zd	efdZ G d d          Ze G d d                      Ze G d d                      Ze j        	 ddeded	eeddf         fd            ZdS )    N)	Generator)	dataclassfield)cache)current_platform   )	GiB_bytes	MiB_bytesbreturnc                 4    t          | t          z  d           S N   )roundr
   r   s    h/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/vllm/utils/mem_utils.py
format_mibr          A	M1%%''    c                 4    t          | t          z  d           S r   )r   r	   r   s    r   
format_gibr      r   r   gpuc                 v    ddl m} |                    |           }|dk    s
J d            t          |          S )z<Returns the maximum shared memory per thread block in bytes.r   )_custom_opszmax_shared_mem cannot be zero)vllmr   0get_max_shared_memory_per_block_device_attributeint)r   opsmax_shared_mems      r   get_max_shared_memory_bytesr       sS     ('''''II#NNN A>~r   c                  2    t          j                    j        S )z2Returns the total CPU memory of the node in bytes.)psutilvirtual_memorytotal r   r   get_cpu_memoryr&   '   s     ""((r   c                   N    e Zd Zddej        j        dz  fdZdefdZd Z	d Z
dS )	DeviceMemoryProfilerNdevicec                     || _         d S N)r)   selfr)   s     r   __init__zDeviceMemoryProfiler.__init__-   s    r   r   c                 Z    t          j                     t          j        | j                  S r+   )gccollectr   get_current_memory_usager)   r-   s    r   current_memory_usagez)DeviceMemoryProfiler.current_memory_usage0   s     

8EEEr   c                 8    |                                  | _        | S r+   )r4   initial_memoryr3   s    r   	__enter__zDeviceMemoryProfiler.__enter__5   s    "7799r   c                     |                                  | _        | j        | j        z
  | _        t	          j                     d S r+   )r4   final_memoryr6   consumed_memoryr0   r1   )r-   exc_typeexc_valexc_tbs       r   __exit__zDeviceMemoryProfiler.__exit__:   s:     5577#043FF 	
r   r+   )__name__
__module____qualname__torchtypesDevicer.   floatr4   r7   r>   r%   r   r   r(   r(   ,   s|         u{1D8    Fe F F F F
  
    r   r(   c                       e Zd ZU dZdZeed<   dZeed<   dZeed<   dZ	eed<   dZ
eed<   dZeed<   d	Zeed
<   dZej        j        ed<   dZeed<   ddZddZddZdefdZdS )MemorySnapshotzMemory snapshot.r   
torch_peakfree_memorytotal_memorycuda_memorytorch_memorynon_torch_memory        	timestampNr)   Tauto_measurer   c                     | j         2t          j        }|J t          j          |                      | _        nt          j         | j                   | _        | j        r|                                  d S d S r+   )r)   r   current_devicerB   device_rP   measure)r-   	device_fns     r   __post_init__zMemorySnapshot.__post_init__Q   sp    ;(7I((( <		44DLL <44DL 	LLNNNNN	 	r   c                    | j         }t          j        |                              dd          | _        t          j        |          \  | _        | _        d}t          j                    r8t          j	        |j
                  |v rt          j                    j        | _        | j        | j        z
  | _        t          j        |          | _        | j        | j        z
  | _        t%          j                    | _        d S )Nzallocated_bytes.all.peakr   ))      )   r   )   r   )rS   r   memory_statsgetrH   mem_get_inforI   rJ   is_cudaget_device_capabilityindexr"   r#   	availablerK   memory_reservedrL   rM   timerO   )r-   r)   shared_sysmem_device_mem_smss      r   rT   zMemorySnapshot.measure\   s     +7??CC&
 
 /?.KF.S.S+$+'A$$&&	A 6v|DD+, ,  &466@D,t/??
 -<VDD $ 043D Dr   otherc                 P   | j         |j         k    rt          d| j          d|j                    t          | j        |j        z
  | j        |j        z
  | j        |j        z
  | j        |j        z
  | j        |j        z
  | j        |j        z
  | j	        |j	        z
  | j         d	  	        S )Nz9The two snapshots should be from the same device! Found: z vs. F)	rH   rI   rJ   rK   rL   rM   rO   r)   rP   )
rS   
ValueErrorrG   rH   rI   rJ   rK   rL   rM   rO   )r-   rf   s     r   __sub__zMemorySnapshot.__sub__   s    <5=((=,= =-2]= =  
 )99(5+<<*U-??(5+<<*U-??!2U5KKnu6<

 

 

 
	
r   c                 <   dt          | j                   dt          | j                   dt          | j                   dt          j         dt          | j                   dt          | j                   dt          | j                   d| j	         d	| j
         S )
Nztorch_peak=zGiB, free_memory=zGiB, total_memory=zGiB, z_memory=zGiB, torch_memory=zGiB, non_torch_memory=zGiB, timestamp=z, auto_measure=)r   rH   rI   rJ   r   device_namerK   rL   rM   rO   rP   r3   s    r   __repr__zMemorySnapshot.__repr__   s    0*T_55 0 0%d&6770 0&t'8990 0  +0 0 6@@P5Q5Q0 0 't'899	0 0
 !+4+@ A A0 0 0 0 !-0 0		
r   r   N)rf   rG   r   rG   )r?   r@   rA   __doc__rH   r   __annotations__rI   rJ   rK   rL   rM   rO   rE   r)   rB   rC   rD   rP   boolrV   rT   ri   strrl   r%   r   r   rG   rG   B   s
        JKL#KL#cIu!%FEK%%%L$	 	 	 	(% (% (% (%T
 
 
 
&

# 

 

 

 

 

 

r   rG   c                       e Zd ZU dZdZeed<   dZeed<   dZeed<   dZ	eed<    e
e          Zeed<   d	Zeed
<   ddZdefdZdS )MemoryProfilingResultz2Memory profiling result. All numbers are in bytes.r   non_kv_cache_memorytorch_peak_increasenon_torch_increaseweights_memory)default_factorybefore_createrN   profile_timer   Nc                 v    | j         j        }t          |d          | _        t          |d          | _        d S )NF)r)   rP   )ry   rS   rG   before_profileafter_profiler,   s     r   rV   z#MemoryProfilingResult.__post_init__   s=    #+,FOOO+6NNNr   c                     d| j         ddt          | j                   dt          | j                   dt          | j                   dt          | j                   dS )NzMemory profiling takes z.2fz% seconds. Total non KV cache memory: z!GiB; torch peak memory increase: z(GiB; non-torch forward increase memory: zGiB; weights memory: zGiB.)rz   r   rt   ru   rv   rw   r3   s    r   rl   zMemoryProfilingResult.__repr__   s    Ed&7G E E$233E E $233	E E $122E E  *$*=>>E E E		
r   rm   )r?   r@   rA   rn   rt   r   ro   ru   rv   rw   r   rG   ry   rz   rE   rV   rq   rl   r%   r   r   rs   rs      s         <<        NC$)E.$I$I$IM>IIIL%O O O O

# 

 

 

 

 

 

r   rs   baseline_snapshotrw   c              #   &  K   t          j                     t          j                     t          j        | j                   t          | |          }|j                                         |V  t          j                     t          j                     |j	                                         |j	        |j        z
  }|j	        |j
        z
  }|j        |_        |j        |_        |j        |_        |j        }|j        }||z   |j        z   |_        dS )a  
    Memory profiling context manager.

    baseline_snapshot: the memory snapshot before the current vLLM instance.
    weights_memory: memory used by PyTorch when loading the model weights.
        Note that, before loading the model weights, we also initialize the device
        and distributed environment, which may consume some memory. This part is not
        included in the weights_memory because PyTorch does not control it.

    The memory in one GPU can be classified into 3 categories:
    1. memory used by anything other than the current vLLM instance.
    2. memory used by torch in the current vLLM instance.
    3. memory used in the current vLLM instance, but not by torch.

    A quantitive example:

    Before creating the current vLLM instance:
        category 1: 1 GiB
        category 2: 0 GiB
        category 3: 0 GiB

    After creating the current vLLM instance and loading the model,
    (i.e. before profiling):
        category 1: 1 GiB
        category 2: 2 GiB (model weights take 2 GiB)
        category 3: 0.5 GiB (memory used by NCCL)

    During profiling (peak):
        category 1: 1 GiB
        category 2: 4 GiB (peak activation tensors take 2 GiB)
        category 3: 1 GiB (memory used by NCCL + buffers for some attention backends)

    After profiling:
        category 1: 1 GiB
        category 2: 3 GiB (after garbage-collecting activation tensors)
        category 3: 1 GiB (memory used by NCCL + buffers for some attention backends)

    In this case, non-kv cache takes 5 GiB in total, including:
    a. 2 GiB used by the model weights (category 2)
    b. 2 GiB reserved for the peak activation tensors (category 2)
    c. 1 GiB used by non-torch components (category 3)

    The memory used for loading weights (a.) is directly given from the
    argument `weights_memory`.

    The increase of `torch.cuda.memory_stats()["allocated_bytes.all.peak"]`
    during profiling gives (b.).

    The increase of `non_torch_memory` from creating the current vLLM instance
    until after profiling to get (c.).
    )ry   rw   N)r0   r1   r   empty_cachereset_peak_memory_statsrS   rs   r|   rT   r}   ry   rH   ru   rM   rv   rO   rz   rw   rt   )r   rw   resultdiff_profilediff_from_createrM   peak_activation_memorys          r   memory_profilingr      s     p JLLL """,->-FGGG"'%  F !!###
LLLJLLL """
  """'&*??L+f.BB!-!8F 0 AF&0F0#711F4II r   )r   )
contextlibr0   rd   collections.abcr   dataclassesr   r   	functoolsr   r"   rB   torch.typesvllm.platformsr   mem_constantsr	   r
   r   rq   r   r   r    r&   r(   rG   rs   contextmanagerr   r%   r   r   <module>r      s=       				  % % % % % % ( ( ( ( ( ( ( (             + + + + + + / / / / / / / /(# (# ( ( ( ((# (# ( ( ( (  S     ) ) ) ) )
       , `
 `
 `
 `
 `
 `
 `
 `
F 
 
 
 
 
 
 
 
:  T T%TT $dD01T T T T T Tr   