o
    
۾iS4                     @   sZ   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
 eeZG dd dZdS )	    )product)CUDAGraphMode
VllmConfig)BatchDescriptor)init_logger)get_captured_lora_countsc                   @   s   e Zd ZdZdefddZd!ddZdee fd	d
Z		d"dede
de
dedef
ddZdedefddZ	d#dedefddZ				d$dede
de
de
dedeeef fddZdeeeee f  fdd ZdS )%CudagraphDispatchera  
    Runtime cudagraph dispatcher to dispatch keys for multiple set of
    cudagraphs.

    The dispatcher stores two sets of dispatch keys, one for PIECEWISE and one
    for FULL cudagraph runtime mode. The keys are initialized depending on
    attention support and what cudagraph mode is set in CompilationConfig. The
    keys stored in dispatcher are the only source of truth for valid
    cudagraphs that can be dispatched at runtime.

    At runtime, the dispatch method generates the runtime cudagraph mode (FULL,
    PIECEWISE, or NONE for no cudagraph) and the valid key (batch descriptor)
    based on the input key. After dispatching (communicated via forward
    context), the cudagraph wrappers will trust the dispatch key to either
    capture or replay (if the mode matches), or pass through to the underlying
    runnable without cudagraph (if the mode does not match or mode is NONE).
    vllm_configc                 C   s   || _ |j| _| j jsdnd| j jj | _tjt tjt i| _	| jj
 r>| j s>J d| jj
 d| jj d| jj d| _| j jd urL| j jjnd| _tj| _
d S )N   zCompilation mode should be CompilationMode.VLLM_COMPILE when cudagraph_mode piecewise cudagraphs is used, and attention should be in splitting_ops or inductor splitting should be used. cudagraph_mode=z, compilation_mode=z, splitting_ops=F)r	   compilation_configspeculative_confignum_speculative_tokensuniform_decode_query_lenr   	PIECEWISEsetFULLcudagraph_keyscudagraph_moderequires_piecewise_compilationis_attention_compiled_piecewisemodesplitting_opskeys_initializedlora_configspecialize_active_loraspecialize_lora_countNONE)selfr	    r   P/home/ubuntu/.local/lib/python3.10/site-packages/vllm/v1/cudagraph_dispatcher.py__init__    s6   

zCudagraphDispatcher.__init__returnNc                 C   s   | j j}| j j}dg|d  | _t||d g dg| D ]\}}t||D ]}||kr2|| j|< q&|| j|< q&q| j jrd| jtj	krf| j jD ] }|| j jkrc| j| }||krct
d| d| dqGdS dS dS )z=Pre-compute the mapping from batch size to padded graph size.r   r
   zcompile_sizes contains z which would be padded to zw. All compile_sizes must be values that won't be changed by cudagraph padding. Use values from cudagraph_capture_sizes.N)r   max_cudagraph_capture_sizecudagraph_capture_sizes_bs_to_padded_graph_sizeziprangecompile_sizesr   r   r   
ValueError)r   max_sizecapture_sizesendstartbssizepaddedr   r   r    _compute_bs_to_padded_graph_sizeE   s8   	
z4CudagraphDispatcher._compute_bs_to_padded_graph_sizec                 C   sB   | j j}|du rdgS | jjrt|j| j}dg| S |jd gS )z
        Returns list of has_lora values for CUDA graph capture.
        This is the single source of truth for LoRA capture cases.
        Nr   r
   )r	   r   r   cudagraph_specialize_lorar   	max_lorasr   )r   r   captured_countsr   r   r   _get_lora_casese   s   
z#CudagraphDispatcher._get_lora_casesr   
num_tokensuniform_decodehas_loranum_active_lorasc           	      C   sf   | j jj}| j}| j| }|r#| jtjr#|| }|| dks"J nd}t	||}t
|||||dS )Nr   F)r5   num_reqsuniformr7   r8   )r	   scheduler_configmax_num_seqsr   r$   r   has_moder   r   minr   )	r   r5   r6   r7   r8   r<   r   num_tokens_paddedr9   r   r   r   _create_padded_batch_descriptorz   s   


z3CudagraphDispatcher._create_padded_batch_descriptorruntime_modebatch_descriptorc                 C   s2   |t jt jfv sJ d| | j| | d S )Nz)Invalid cudagraph runtime mode for keys: )r   r   r   r   add)r   rA   rB   r   r   r   add_cudagraph_key   s   z%CudagraphDispatcher.add_cudagraph_keyr
   r   r   c              
      s   || _ |tjkrd| _d S |   |  }dd |D | _| tjkrBt| j	j
|D ]\}}| | | |d|dk|  q+| tjkry| ry| jjj   fdd| j	j
D }t||D ]\}}| tj| |d|dk| qed| _d S )NTc                 S   s   g | ]}|r|qS r   r   ).0
lora_countr   r   r   
<listcomp>   s
    zACudagraphDispatcher.initialize_cudagraph_keys.<locals>.<listcomp>Fr   c                    s    g | ]}| kr|kr|qS r   r   )rE   xmax_num_tokensr   r   r   rG      s
    )r   r   r   r   r0   r4   captured_lora_counts
mixed_moder   r   r#   rD   r@    relax_for_mixed_batch_cudagraphsdecode_moder   separate_routiner	   r;   r<   )r   r   r   
lora_casesr-   r8   "cudagraph_capture_sizes_for_decoder   rI   r   initialize_cudagraph_keys   sP   


z-CudagraphDispatcher.initialize_cudagraph_keysFdisable_fullc                 C   s   | j r| jtjks|| jjkrtjt|fS |}|r@|dkr@| jr9ddl}|	| j
|}|t| j
k r8| j
| }n| jjjd }| ||||}	|	 }
|sh|	| jtj v r[tj|	fS |
| jtj v rhtj|
fS |
| jtj v rutj|
fS tjt|fS )ah  
        Given conditions(e.g.,batch descriptor and if using piecewise only),
        dispatch to a cudagraph runtime mode and the valid batch descriptor.
        A new batch descriptor is returned as we might dispatch a uniform batch
        to a graph that supports a more general batch (uniform to non-uniform).

        Args:
            num_tokens: Number of tokens in the batch.
            uniform_decode: Whether the batch is uniform decode (i.e. uniform and query
                length is uniform_decode_query_len).
            has_lora: Whether LoRA is active.
            disable_full: If True, skip FULL cudagraph checks and
                return PIECEWISE or NONE only. (can be used for features like
                cascade attention that are not supported by full cudagraphs)
            num_active_loras: Number of distinct active LoRA adapters.
        r   Nr
   )r   r   r   r   r   r"   r   r   bisectbisect_leftrK   lenr	   r   r2   r@   rM   r   r   r   )r   r5   r6   r7   rS   r8   effective_num_active_lorasrT   idx
batch_descrelaxed_batch_descr   r   r   dispatch   s4   



zCudagraphDispatcher.dispatchc                 C   sb   | j r	| jtjkrg S g }tjtjfD ]}t| j| }|r.|jdd dd |	||f q|S )a  
        Returns capture descriptors for cudagraph capturing.

        Returns:
            List of (runtime_mode, batch_descriptors) tuples, ordered PIECEWISE
            first then FULL. Batch descriptors are sorted largest-first for
            memory efficiency.
        c                 S   s   | j S )N)r5   )dr   r   r   <lambda>0  s    z7CudagraphDispatcher.get_capture_descs.<locals>.<lambda>T)keyreverse)
r   r   r   r   r   r   listr   sortappend)r   resultr   descsr   r   r   get_capture_descs  s   	z%CudagraphDispatcher.get_capture_descs)r!   N)r   )r
   )FFFr   )__name__
__module____qualname____doc__r   r    r0   r`   intr4   boolr   r@   r   rD   rR   tupler[   re   r   r   r   r   r      s\    
% 

	
@

"Er   N)	itertoolsr   vllm.configr   r   vllm.forward_contextr   vllm.loggerr   vllm.lora.utilsr   rf   loggerr   r   r   r   r   <module>   s   