
    .`i*)                         d dl mZ d dlZd dlmc mZ ddZd Z	 ddZ G d d          Z	edd            Z
 G d	 d
          ZdS )    )contextmanagerNc                    |g }t          | t          t          f          r| D ]}t          |||          }nPt          | t          j                  r6t          |                                           }|                    |           |S )zDescends iterators that contains Tensors and prints the Tensor.
    Recursive function that descends iterator type arguments until
    it finds a Tensor object.
    )
isinstancelisttupleprint_tensortorchTensorsizeappend)
tensor_objprefixtensor_listtentensor_dimss        q/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/vllm/utils/nvtx_pytorch_hooks.pyr   r   
   s    
 *tUm,, ( 	A 	AC&sFK@@KK	A	J	-	- (:??,,--;'''    c                    i }t          | t          j        j        t          j        j        t          j        j        f          rji }| j        |d<   | j        |d<   | j        |d<   | j	        |d<   | j
        |d<   | j        |d<   | j        |d<   | j        |d<   | j        |d	<   | j        |d
<   |}nt          | t          j        j        t          j        j        t          j        j        f          rji }| j        |d<   | j        |d<   | j        |d<   | j	        |d<   | j
        |d<   | j        |d<   | j        |d<   | j        |d<   | j        |d	<   | j        |d
<   |}nt          | t          j        j        t          j        j        t          j        j        f          rUd }i } || j                  |d<    || j	                  |d<    || j
                  |d<    || j                  |d<   |}nTt          | t          j        j        t          j        j        t          j        j        f          rMi }| j        | j        g|d<   | j	        | j	        g|d<   | j
        | j
        g|d<   | j        |d<   | j        |d<   |}nt          | t          j        j        t          j        j        t          j        j        f          ri }| j        | j        g|d<   |}npt          | t          j        j                  r| j         |d<   | j!        |d<   n;t          | t          j        j"        t          j        j#        t          j        j$        f          r| j%        |d<   | j&        |d<   | j'        |d<   nt          | t          j        j(                  r| j)        |d<   nt          | t          j        j*                  r| j+        |d<   | j)        |d<   n~t          | t          j        j,                  r| j-        |d<   | j.        |d<   nJt          | t          j        j/        t          j        j0        t          j        j1        f          r
| j2        |d<   |S )zCExtract the static parameters from LLM and VLM relevant layer typesin_chanout_chan
filter_dimstridepaddingdilation
transposedoutput_paddinggroupspadding_modec                     t          | t                    rt          |           S t          | t                    r| | gS d S N)r   r   r   int)	parameters    r   _handle_int_or_tuplez2process_layer_params.<locals>._handle_int_or_tupleD   sG    )U++ .I&Is++ .!9--. .r   	ceil_modecount_include_padoutput_sizein_featuresout_featuresnum_featuresepsilonmomentumin_placepnum_embeddingsembedding_dimscale_factor)3r   r	   nnConv1dConv2dConv3din_channelsout_channelskernel_sizer   r   r   r   r   r   r   ConvTranspose1dConvTranspose2dConvTranspose3d	MaxPool1d	MaxPool2d	MaxPool3d	AvgPool1d	AvgPool2d	AvgPool3dr$   r%   AdaptiveAvgPool1dAdaptiveAvgPool2dAdaptiveAvgPool3dr&   Linearr'   r(   BatchNorm1dBatchNorm2dBatchNorm3dr)   epsr+   ReLUinplaceDropoutr-   	Embeddingr.   r/   UpsampleUpsamplingNearest2dUpsamplingBilinear2dr0   )
module_obj
param_infoconv_paramsconvtranspose_paramsr#   pooling_paramss         r   process_layer_paramsrU      s   J*uxQRR f=!+!7I","9J$.$:L! * 1H!+!3I","5J$.$9L!(2(A$% * 1H&0&=N# 

	H$H$H$	

 
 Y=  "*4*@Y'+5+BZ(-7-C\*)3):X&*4*<Y'+5+>Z(-7-B\*1;1J-.)3):X&/9/F^,)

	UX');UX=OP
 
 E=	. 	. 	. ';';J<R'S'S|$#7#7
8I#J#Jx $8$89K$L$Ly!%9%9*:M%N%Nz"#

	UX');UX=OP
 
 5= ""(
|$ %/$5z7H#Ix %/%79K$Ly!&0&:{#.8.J*+#

	H&H&H&	

 
 (= "")
}% $

	J	0	0 =$.$:
=!%/%<
>""			ux3UX5IJ
 
 = &0%<
>" *
9!+!4
:	J	.	. =!+!3
:	J 0	1	1 =$,
3!+!3
:	J 2	3	3 ='1'@
#$&0&>
?##	HH(H)	

 
 = &0%<
>"r   c                 d   i }| |d<   |                     d          }t          |          D ]=\  }\  }}	|dk    ri |d<   t          |	                                          |d         |<   >t	          |d          }
|
r|
|d<   t	          |d          }|r||d	<   |rX|                                D ]C\  }}t          |t          j        t          t          f          rt	          ||          }|r|||<   Dt          |          }|r||d
<   t          j        d                    |                     d S )NModuleF)recurser   TrainableParamsInputInputsOutputOutputsStaticParamsz{})named_parameters	enumerater   r   r   itemsr   r	   r
   r   rU   nvtx
range_pushformat)module_namerP   	in_tensorkwargs
out_tensormarker_dictmodule_paramsidx
param_name	param_objin_tensor_listout_tensor_listkeyvaluer   rQ   s                   r   construct_marker_dict_and_pushrr      sl    K'K ///>>M(1-(@(@ L L$$j)!88-/K)*59)..:J:J5K5K%&z22!)W55N / .H":x88O 1!0I  3 ,,.. 	3 	3JC%%,e!<== 3*5#66 3'2K$%j11J 1&0N#ODKK,,-----r   c                       e Zd ZdZdZdS )ResultHolderz9Holder for storing results from within a context manager.N)__name__
__module____qualname____doc__result r   r   rt   rt      s        CCFFFr   rt   c           	   #     K   t                      }t          | |||           	 |V  t          j                     |                     dd          }t          ||dd|j                   t          j                     dS # t          j                     |                     dd          }t          ||dd|j                   t          j                     w xY w)a;  Context manager for NVTX markers that automatically pushes on enter
    and pops on exit.

    Example:
        with nvtx_marker_context("Module:MyModule", module, in_tensor=args,
                                 kwargs=kwargs) as ctx:
            ctx.result = module(*args, **kwargs)
        return ctx.result
    )rf   rg   z(input)z(output)Nrf   rg   rh   )rt   rr   rb   	range_popreplacery   )re   rP   rf   rg   holderoutput_names         r   layerwise_nvtx_marker_contextr      s      ^^F #	    	!)))Z@@&}	
 	
 	
 	
 	 	!)))Z@@&}	
 	
 	
 	
 	s   B   ACc                   <     e Zd ZdZ fdZd Zd Zd ZddZ xZ	S )	PytHooksaD  This module contains all the code needed to enable forward hooks
    in a pytorch network.

    To register the hooks for a given network, the user needs to instantiate
    a PytHook object. Then call the register_hooks method.

    Example:

        my_hook = PytHook()
        my_hook.register_hooks(my_network_model)
    c                 V    t                                                       i | _        dS )zInitialize module variables.N)super__init__module_to_name_map)self	__class__s    r   r   zPytHooks.__init__   s'    "$r   c                      t          |          S r    )rU   )r   rP   s     r   _process_layer_paramszPytHooks._process_layer_params   s    #J///r   c                     t          j                     | j                            |d          }t	          ||dd|           t          j                     dS )zCallback function that ends the NVTX marker.
        Records the module name and tensor information.
        Called after the module executes the forward method.
        unknownNr|   )rb   r}   r   getrr   )r   rP   rf   rh   re   s        r   module_fwd_hookzPytHooks.module_fwd_hook   sa    
 	-11*iHH&tDZ	
 	
 	
 	
 	r   c                 d    | j                             |d          }t          ||||d           dS )zwCreates an NVTX marker with the module name in it.
        This function is called before the module executes.
        r   Nr|   )r   r   rr   )r   rP   rf   rg   re   s        r   module_fwd_pre_hookzPytHooks.module_fwd_pre_hook   sF     -11*iHH&yTX	
 	
 	
 	
 	r   topc                    t           j        j        t           j        j        t           j        j        t           j        j        t           j        j        f}|                    |          D ]\  }}t          ||          r|	                    | j
        d           |                    | j                   || j        vr|| j        |<   `t          d                    |                    dS )zUser level function that activates all the hooks.
        The user needs to call this method from the network source code.
        The code descends all the modules in the network and registers their
        respective hooks.
        )r   T)with_kwargsz!Module instance {} is not unique N)r	   r1   IdentityrK   	Dropout1d	Dropout2d	Dropout3dnamed_modulesr   register_forward_pre_hookr   register_forward_hookr   r   
ValueErrorrd   )r   network_modelmodule_prefix
skip_typesnamemodules         r   register_hookszPytHooks.register_hooks  s     HHHHH

 *77}7MM 
	U 
	ULD&&*-- ,,T-ESW,XXX(()=>>>T44426'// !D!K!KF!S!STTTr   )r   )
ru   rv   rw   rx   r   r   r   r   r   __classcell__)r   s   @r   r   r      s        
 
% % % % %
0 0 0           r   r   r    )NN)
contextlibr   r	   torch.cuda.nvtxcudarb   r   rU   rr   rt   r   r   rz   r   r   <module>r      s   & % % % % %             "l l l` AE .  .  .  .F        ! ! ! !HF F F F F F F F F Fr   