
    .`i{9                        d dl Z d dlmZ d dlmZmZ d dlZd dlmZ d dl	m
Z
 d dlmZmZ d dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZ d dlmZmZ d dlmZmZ d dlmZ d dl m!Z!m"Z"  ee#          Z$ G d d          Z%e G d d                      Z&dede'ddfdZ( ed          dej)        dej)        dz  dej)        fd            Z* ed          dej)        dej)        dz  dej)        fd            Z+ded ede'fd!Z,	 d/d"e-e.e.f         d#e/e!         d$e0e.         dz  ddfd%Z1	 d0d'e-e.ej)        f         d(e-e.e
f         d)e/ej)                 d*e'ddf
d+Z2d,ed-e'de3fd.Z4dS )1    N)defaultdict)	dataclassfield)
deprecated)	Attention)CacheConfig
VllmConfig)init_logger)MultiModalEmbeddings)extract_layer_index)MultiModalRegistry)current_platform)MemorySnapshot
format_gib)AttentionBackendAttentionMetadataBuilder)compute_mm_encoder_budget)KVCacheGroupSpecKVCacheSpecc                   t     e Zd ZdZdededdf fdZdefdZde	fdZ
d	ed
e	dee	e	f         fdZddZ xZS )MultiModalBudgetzDHelper class to calculate budget information for multi-modal models.vllm_configmm_registryreturnNc                    t                                                       |j        x| _        }|j        x| _        }|| _        |                    |          x| _        }|j        | _        |j        | _	        |
                    ||          | _        |                    ||| j                  }t          ||          \  }}|| _        || _        t!          t"          t$          f                     }	t!          t"          t$          f                     }
|                                D ](\  }}|                     ||          \  }}||	|<   ||
|<   )|| _        |	| _        |
| _        d S )N)cache)r   profiler_limits)super__init__model_configscheduler_configr    processor_only_cache_from_configr   max_model_lenmax_num_seqsmax_num_reqsget_mm_limits_per_prompt	mm_limits#get_max_tokens_per_item_by_modalityr   encoder_compute_budgetencoder_cache_sizedictstrintitemsget_max_itemsmax_tokens_by_modality max_items_per_prompt_by_modalitymax_items_per_batch_by_modality)selfr   r   r    r!   r   r0   r)   r*   r1   r2   modality
max_tokensmax_items_per_promptmax_items_per_batch	__class__s                  h/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/vllm/v1/worker/utils.pyr   zMultiModalBudget.__init__   s   
 	+6+CCL3>3OO 0&(II+VVV
U)7,9$==lRW=XX!,!P!P N "Q "
 "
 6O"6
 6
2 2
 '=#"4+/S>+;+;(*.sCx.*:*:'$:$@$@$B$B 	L 	L Hj ""8Z88$# :N,X68K+H55&<#0P-/N,,,    c                 b    | j         }t          |                                d           \  }}|S )Nc                     | d         S )N    )xs    r9   <lambda>z?MultiModalBudget.get_modality_with_max_tokens.<locals>.<lambda>M   s
    ! r:   )key)r0   maxr.   )r3   r0   r4   _s       r9   get_modality_with_max_tokensz-MultiModalBudget.get_modality_with_max_tokensK   s5    !%!<06688nnMMM!r:   c                 6    t          | j        | j                  S N)minr)   r*   r3   s    r9   get_encoder_budgetz#MultiModalBudget.get_encoder_budgetQ   s    4.0GHHHr:   r4   max_tokens_per_itemc                 b   |dk    rdS |                                  }|dk    rdS ||z  }| j        |         }t          dt          || j        |z                      }| j        }| j        }|j        st          ||j        |z            }||z  }	t          dt          ||	                    }
||
fS )Nr   )r   r   r=   )	rI   r'   rB   rG   r#   r!   r%   enable_chunked_prefillmax_num_batched_tokens)r3   r4   rJ   encoder_budgetmax_encoder_items_per_batchmm_limitr6   r!   r%   max_decoder_items_per_batchr7   s              r9   r/   zMultiModalBudget.get_max_itemsT   s    
 !##4 0022 Q4&48K&K# >(+"$,0CCDD 
  

  0(6 	 7;NN L
 '35I&I#!+-HII
 

 $%888r:   c                 J    | j         | j                                          d S d S rF   )r   clear_cacherH   s    r9   reset_cachezMultiModalBudget.reset_cache   s,    :!J""$$$$$ "!r:   )r   N)__name__
__module____qualname____doc__r	   r   r   r,   rD   r-   rI   tupler/   rT   __classcell__)r8   s   @r9   r   r      s        NN-O-O (-O 
	-O -O -O -O -O -O^c    IC I I I I+9+9 !+9 
sCx	+9 +9 +9 +9Z% % % % % % % %r:   r   c                       e Zd ZU ee         ed<   ee         ed<   eed<   e	ed<    e
d           Zee         ed<   	 dd	e	d
z  de	fdZdde	defdZd
S )AttentionGroupbackendlayer_nameskv_cache_speckv_cache_group_idc                      g S rF   r>   r>   r:   r9   r@   zAttentionGroup.<lambda>   s     r:   )default_factorymetadata_buildersr=   kernel_block_sizeNnum_metadata_buildersc                      | j                             |          n j          fdt          |          D              _        d S )Nc                 d    g | ],} j                                         j                  -S r>   )r]   get_builder_clsr^   ).0rC   devicekv_cache_spec_builderr3   r   s     r9   
<listcomp>z;AttentionGroup.create_metadata_builders.<locals>.<listcomp>   sT     "
 "
 "
  +DL((**% 	 "
 "
 "
r:   )r_   copy_with_new_block_sizerangerc   )r3   r   rj   rd   re   rk   s   ```  @r9   create_metadata_buildersz'AttentionGroup.create_metadata_builders   s~     !, 778IJJJ# 	
"
 "
 "
 "
 "
 "
 "
 011"
 "
 "
r:   r   	ubatch_idr   c                 P    t          | j                  |k    sJ | j        |         S rF   )lenrc   )r3   rp   s     r9   get_metadata_builderz#AttentionGroup.get_metadata_builder   s,    4)**Y6666%i00r:   r=   )r   )rU   rV   rW   typer   __annotations__listr,   r   r-   r   rc   r   ro   rs   r>   r:   r9   r\   r\      s         "####c 9>"
9 9 9t45    &'
 
 :	

  #
 
 
 
,1 1c 1:R 1 1 1 1 1 1r:   r\   mm_embeddingsexpected_num_itemsr   c                 N   t          | t          t          t          j        f          sJ dt          |            d            t          |           |k    sJ d| dt          |           d            t          d | D                       sJ dd | D              d            dS )	z{
    Perform sanity checks for the result of
    [`vllm.model_executor.models.SupportsMultiModal.embed_multimodal`][].
    z`Expected multimodal embeddings to be a list/tuple of 2D tensors, or a single 3D tensor, but got zg instead. This is most likely due to incorrect implementation of the model's `embed_multimodal` method.zIExpected number of multimodal embeddings to match number of input items: z, but got len(mm_embeddings)=c              3   ,   K   | ]}|j         d k    V  dS )   N)ndimri   es     r9   	<genexpr>z2sanity_check_mm_encoder_outputs.<locals>.<genexpr>   s(      22qqv{222222r:   z[Expected multimodal embeddings to be a sequence of 2D tensors, but got tensors with shapes c                     g | ]	}|j         
S r>   )shaper~   s     r9   rl   z3sanity_check_mm_encoder_outputs.<locals>.<listcomp>   s    'G'G'GA'G'G'Gr:   N)
isinstancerw   rY   torchTensorru   rr   all)rx   ry   s     r9   sanity_check_mm_encoder_outputsr      s    mdE5<%@AA  	4*.}*=*=	4 	4 	4 A }!3333	4*	4 	469-6H6H	4 	4 	4 433 22M22222  	4'G'G'G'G'G	4 	4 	4 2  r:   zG`scatter_mm_placeholders` is deprecated and will be removed in v0.15.0.embedsis_embedc                     || S |                      |j        d         | j        d         ft          j                  }| ||<   |S )a  
    Scatter the multimodal embeddings into a contiguous tensor that represents
    the placeholder tokens.

    [`vllm.multimodal.processing.PromptUpdateDetails.is_embed`][].

    Args:
        embeds: The multimodal embeddings.
            Shape: `(num_embeds, embed_dim)`
        is_embed: A boolean mask indicating which positions in the placeholder
            tokens need to be filled with multimodal embeddings.
            Shape: `(num_placeholders, num_embeds)`
    Nr   )
fill_value)new_fullr   r   nan)r   r   placeholderss      r9   scatter_mm_placeholdersr      sT    $ ??		FL,-9 #  L $Lr:   zF`gather_mm_placeholders` is deprecated and will be removed in v0.15.0.r   c                     || S | |         S )z
    Reconstructs the embeddings from the placeholder tokens.

    This is the operation of [`scatter_mm_placeholders`]
    [vllm.v1.worker.utils.scatter_mm_placeholders].
    r>   )r   r   s     r9   gather_mm_placeholdersr      s     !!r:   init_snapshotcache_configc                    t          j        | j        |j        z            }| j        |k     rZt          d| j         dt          | j                   dt          | j                   d|j         dt          |           d          |S )z
    Calculate the amount of memory required by vLLM, then validate
    that the current amount of free memory is sufficient for that.
    zFree memory on device z (/z> GiB) on startup is less than desired GPU memory utilization (z, zT GiB). Decrease GPU memory utilization or reduce GPU memory used by other processes.)mathceiltotal_memorygpu_memory_utilizationfree_memory
ValueErrordevice_r   )r   r   requested_memorys      r9   request_memoryr      s    
 y"\%HH   #333I]%: I I=455I I-455I I 3	I I
 *++I I I
 
 	
 r:   shared_kv_cache_layerskv_cache_groupsrunner_only_attn_layersc                     i }|D ]}|j         D ]}|||<   |                                 D ]>\  }}||         }|j                             |           ||                    |           ?dS )a  
    Sets up KV cache sharing by reusing the allocated KV caches in `kv_caches`
    for layers that do not allocate its own KV cache, based on the mapping in
    `shared_kv_cache_layers`. Adds these layers to the corresponding KV cache
    group, which is needed to ensure that attention metadata is assigned later.

    Args:
        shared_kv_cache_layers: Layer pairings for cross-layer KV sharing.
            If an Attention layer `layer_name` is in the keys of this dict, it
            means this layer will perform attention using the keys and values
            from the KV cache of `shared_kv_cache_layers[layer_name]`.
        kv_cache_groups: The KV cache groups of the model.
    N)r^   r.   appendadd)r   r   r   layer_to_kv_cache_groupkv_cache_group
layer_nametarget_layer_nametgt_kv_cache_groups           r9   (add_kv_sharing_layers_to_kv_cache_groupsr     s    $ <>) A A(4 	A 	AJ2@#J//	A *@)E)E)G)G 4 4%
%45FG&--j999".#''
3334 4r:   r=   	kv_cachesforward_contextrunner_kv_cachesnum_attn_modulec                 D   t          |          dk    sJ t          t                    }| D ]+}|t          ||                                       |           ,t          |                                          D ]~}||         }t          |          dk    rAt          j                    s&t          j	                    st          j
                    rnt          |D ]}|                    | |                    |                                 D ]\  }}|g||         _        dS )a{  
    Bind the allocated KV cache to both ModelRunner and forward context so
    that the KV cache can be used in the forward pass.

    This function:
      1) Fills the ModelRunner's kv cache list (`runner_kv_caches`) with
         kv_caches.
      2) Associates each attention layer in the `forward_context` with its
         corresponding KV cache in kv_caches.

    Args:
        kv_caches: The allocated kv_caches with layer names as keys.
        forward_context: The global forward context containing all Attention
            layers with layer names as keys.
        runner_kv_caches: The kv_cache declared by ModelRunner.
    r   r=   N)rr   r   rw   r   r   sortedkeysr   is_cuda_alikeis_xpuis_cpuNotImplementedErrorr.   kv_cache)	r   r   r   r   
index2namer   layer_indexr^   r   s	            r9   bind_kv_cacher   0  sQ   .   A%%%% T""J X X
&z?CCDKKJWWWWjoo//00 ; ; -{a !.00
*#*,,
* $*,,
* ))% 	; 	;J##Ij$9::::	; !* 1 1 : :
H08z
#,,: :r:   r   num_input_tokensc                     | j         j        j        sdS | j        j        }|dk    rdS ||z  dk    sJ | j         j        r| j         j        rdS | j         j        }|dS ||v S )a  Check if the residual tensor is scattered for sequence parallelism.

    The residual tensor is scattered across tensor parallel ranks when sequence
    parallelism and tensor parallelism is enabled.

    This follows the same logic as SequenceParallelismPass.is_applicable_for_range():
    - In full-graph compilation mode (no splitting ops or using inductor graph
      partition), SP is always applied
    - Otherwise, SP is only applied for specific shapes in compile_sizes
    Fr=   r   T)compilation_configpass_config	enable_spparallel_configtensor_parallel_sizesplitting_opsuse_inductor_graph_partitioncompile_sizes)r   r   tpr   s       r9   is_residual_scattered_for_spr   l  s     )5? u		$	9B	Qwwu b A%%%% *8)F t2@Mu},,r:   rF   rt   )5r   collectionsr   dataclassesr   r   r   typing_extensionsr   vllm.attention.layerr   vllm.configr   r	   vllm.loggerr
   %vllm.model_executor.models.interfacesr    vllm.model_executor.models.utilsr   vllm.multimodal.registryr   vllm.platformsr   vllm.utils.mem_utilsr   r   vllm.v1.attention.backendr   r   "vllm.v1.core.encoder_cache_managerr   vllm.v1.kv_cache_interfacer   r   rU   loggerr   r\   r-   r   r   r   r   r   r+   r,   rw   setr   r   boolr   r>   r:   r9   <module>r      s    # # # # # # ( ( ( ( ( ( ( (  ( ( ( ( ( ( * * * * * * / / / / / / / / # # # # # # F F F F F F @ @ @ @ @ @ 7 7 7 7 7 7 + + + + + + ; ; ; ; ; ; ; ; P P P P P P P P H H H H H H D D D D D D D D	X		j% j% j% j% j% j% j% j%Z $1 $1 $1 $1 $1 $1 $1 $1N' 
   < UVVLlT! \   WV8 TUU","lT!" \" " " VU" .  PS    4 044 4 cN4*+4 !X_4 
	4 4 4 4F 	9: 9:C%&9:#y.)9: 5<(9: 	9:
 
9: 9: 9: 9:x!-!-/2!-	!- !- !- !- !- !-r:   