
    ^j                        d dl Z d dlmZmZmZ d dlmZ d dlZddlm	Z	 ddl
mZ ddlmZ dd	lmZmZmZmZ dd
lmZ ddlmZ ddlmZmZmZmZ de	defdZde	defdZde	dee e e      e e!   f   fdZ" G d d      Z# G d d      Z$y)    N)floorgcdsqrt)Any   )PreTrainedConfig)ContinuousBatchingConfig)is_flash_attention_requested   )BlockManagerCacheAllocatorFullAttentionCacheAllocatorSlidingAttentionCacheAllocator)DistributedHelper)resolve_max_memory_percent)RequestStateRequestStatusget_device_and_memory_breakdownloggerconfigreturnc                 b    t        | dd      }||S t        | dd      }||S t        d|        )z9Finds the number of key-value heads for the given config.num_key_value_headsNnum_attention_headszMnum_key_value_heads or num_attention_heads could not be found in the config:
getattr
ValueError)r   kv_headss     |/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/generation/continuous_batching/cache.pyfind_num_kv_headsr       sM     v4d;Hv4d;H
eflemn
oo    c                     t        | dd      }||S t        | dd      }t        | dd      }||||z  S t        d|        )z.Finds the head dimension for the given config.head_dimNhidden_sizer   zThead_dim or (hidden_size and num_attention_heads) could not be found in the config:
r   )r   r#   r$   r   s       r   find_head_dimr%   *   sh     vz40H&-6K!&*?F#6#B111
lmsltu
vvr!   c                 $   t        | dd      }|3t        | dd      dnd}t        | j                        D cg c]  }| }}i }t        |      D ]  \  }}|j	                  |g       |gz   ||<     t        |j                         D cg c]  }t        |       c} }g }	|j                         D ]7  \  }}t        dt        |      |      D ]  }|	j                  ||||z            9 |	D 
cg c]
  }
||
d       }}
|	|fS c c}w c c}w c c}
w )a  
    Group layers depending on the attention mix, according to VLLM's hybrid allocator rules:
        - Layers in each group need to have the same type of attention
        - All groups have the same number of layers

    For a model with the following layer types: ["sliding", "full", "full", "sliding", "full", "full", "full", "full"]
    We would get four groups: [0, 3], [1, 2], [4,5] and [6,7].
    layer_typesNsliding_windowsliding_attentionfull_attentionr   )
r   rangenum_hidden_layers	enumerategetr   valueslenitemsappend)r   r'   	attn_type_layer_countsi
layer_typeindices
group_sizelayer_groupslggroup_typess               r   group_layers_by_attn_typer=   8   sD    &-6K+26;KT+R+^'dt	*/0H0H*IJQyJJ L";/ J:#/#3#3J#Cqc#IZ J <3F3F3HIs7|IJJ L+113 =
Gq#g,
3 	=AA
N ;<	== 1==";r!u%=K=$$# K J >s   	DD.Dc                      e Zd ZdZdZej                  fdededej                  e
z  dedee
ef   dej                  d	d
fdZdeded	efdZdeded	efdZde
d	efdZdede
ded	ed
z  fdZde
d	d
fdZd	efdZde
dededeee      d
z  deee      d	d
fdZde
dededej4                  d	d
f
dZdeded	ee
ef   fdZdej4                  dej4                  d edeej4                     deej4                     d	eej4                  ej4                  f   fd!Zd"ed	e
fd#Zde
d$ee   d	efd%Z d&e!d'ed	d
fd(Z"d)ee   d*ee   d	d
fd+Z#d,e
d	efd-Z$d,e
d.ee
   d	eee   ee   f   fd/Z%d1d0Z&y
)2PagedAttentionCacheu  
    Manages the cache for a paged attention mechanism, inspired by VLLM's hybrid allocator. The cache relies on making
    groups of layers to reduce the complexity of cache management and fragmentation.

    The cache uses a three-level hierarchy:
    - Pages: The smallest unit of cache, a page has a size of [num_heads, head_size], which is the space needed to
        store the key or value states for one token and one layer. For a model with only full-attention layers, to store
        the KV cache of one token, we need `2 * num_layers` pages: key and values each take `num_layers` pages.
        Pages are grouped into blocks:
    - Blocks: A block is a collection of `block_size` pages, serving as the allocation unit to reduce management
        complexity and fragmentation. Cache is allocated and freed block by block, not page by page. One block is
        allocated to one layer group, which only has one attention type, like full-attention or sliding-attention.
        If all layers in the model have the same attention type, then all layers will be in the same group. There is
        more than one group if and only if the model has a mixed attention types, like layers with full-attention and
        layers with sliding-attention.
    - Cache tensors: The physical supports for the cache. There are as many cache tensors as there are layer in a
        layer group, and the shape of the cache tensor is `[num_blocks * block_size, num_heads, head_size]`.

    Grouping layers into groups is useful because when we allocate one block to a group N, the block allocated is the
        same for all layers in group N, equivalently it is allocated across all cache tensors. This allows us to
        efficiently allocate and free blocks, and to efficiently read and write key and value states.

    For instance, imagine we have 8 blocks of cache and a model with two layer groups: a full-attention group with 3
    layers and a sliding-attention group with 3 layers. At creation time, the physical cache tensors look like this:

    cache_tensor_0: □ □ □ □ □ □ □ □
    cache_tensor_1: □ □ □ □ □ □ □ □
    cache_tensor_2: □ □ □ □ □ □ □ □

    where □ means the blocks is not allocated to any layer group yet. We have 3 cache tensors because there are
    3 layers per group.
    We allocate 1 block to each group, after allocation, the cache tensors look like this:

    cache_tensor_0: ✖ ◉ □ □ □ □ □ □
    cache_tensor_1: ✖ ◉ □ □ □ □ □ □
    cache_tensor_2: ✖ ◉ □ □ □ □ □ □

    where ✖ means the block is allocated to the full-attention group, and ◉ means the block is allocated to the
    sliding-attention group.
    Now, if we continue to generate, and the sliding window has been reached, we only need to allocate a new block
    for the full-attention group, and the cache tensors look like this:

    cache_tensor_0: ✖ ◉ ✖ □ □ □ □ □
    cache_tensor_1: ✖ ◉ ✖ □ □ □ □ □
    cache_tensor_2: ✖ ◉ ✖ □ □ □ □ □

    And after further generation, when we need a new block allocated:

    cache_tensor_0: ✖ ◉ ✖ ✖ □ □ □ □
    cache_tensor_1: ✖ ◉ ✖ ✖ □ □ □ □
    cache_tensor_2: ✖ ◉ ✖ ✖ □ □ □ □

    This would not have been possible if all layers were in the same group: we would have had to allocate a new block
    for the sliding-attention group, although it is not needed.
       r   continuous_batching_configdevicedistributed_helpertp_plandtyper   Nc           	         || _         || _        || _        t        |      | _        t        |      | _        |j                  | _        | j                  | j                  k  r%t        d| j                   d| j                         t        |      \  }}t        |d         }	t        |      | _        i | _        i | _        t        |      D ]N  \  }
}||
   dk(  r|j                   nd}t        |      D ]%  \  }}|
|f| j                  |<   || j                  |<   ' P d}dD ]  }||v rd|z   |v rd	} n |j"                  }|dkD  rE|rC| j                  |z  dk7  rt        d
| j                   d| d      | xj                  |z  c_        |j$                  t'        |d       t)        ||| j                  ||	      j+                         \  }}|dkD  r{t-        j.                  ||g| j                  t,        j0                        }|j3                  |       t5        |d   j7                               t5        |d   j7                               }}|| _        || _        | j:                  | j                  z  | _        t?        j@                  d| j8                  d| j:                  d| j                         |jB                  }||jD                  }|| _!        g | _#        g | _$        |dz   | j                  | j                  | j                  f}|dz   | j                  z  | j                  | j                  f| _%        || j                  z  | _&        || j                  z  dz   | _'        |dz   | j                  z  | _(        tS        |	      D ])  }t-        jT                  | jJ                  | j                  | j                        }t-        jT                  | jJ                  | j                  | j                        }t,        jV                  jY                  |       t,        jV                  jY                  |       | jF                  j[                  |       | jH                  j[                  |       |j]                  |      |   j_                  d       |j]                  |      |   j_                  d       , t?        j@                  d| jJ                  d| jF                  d   j`                  d| jF                  d   jc                                |jd                  | _2        g | _3        d| _4        d| _5        d| _6        t        |      D ]  \  }
}|dk(  r8to        |
| j                  | jd                        }| xjh                  dz  c_4        nq|dk(  r^tq        |
| j                  |j                   | jN                  | jP                        }| xjj                  dz  c_5        |jr                  | _6        nt        d|       | jf                  j[                  |        | jd                  xr |dgk(  | _:        tw        || j                  |dkD        | _<        d| _=        d| _>        y)a`  Initialize a paged attention cache for efficient memory usage. Also turns in prefix sharing if the model has
        only full attention layers.

        Args:
            config: Model configuration
            continuous_batching_config: Continuous batching configuration containing cache parameters
            device: Device for the cache tensors
            distributed_helper: TP-aware helper. Used to dispatch attention heads and ensure coherent cache size
            tp_plan: Tensor parallelism plan
            dtype: Data type of the activation and the cache (for now, these are the same)
        zBlock size must be at least z
, but got r   r)   r   T)zlayers.*.self_attn.k_projzlayers.*.self_attn.v_projzmodel.FzNumber of key value heads z+ must be divisible by tensor parallel size .N)	cb_confighas_logit_processors)r   rA   rE   r<   r9   rB   rE   z1Paged cache initialized: self.max_batch_tokens = z, self.num_blocks = z, self.block_size =    )rE   rB   zself.cache_shape = z self.key_cache[0].shape = z self.key_cache[0].numel() = r*   )allow_block_sharingzInvalid group type: )tp_on)?r   rE   rB   r    r   r%   r#   
block_size_min_block_sizer   r=   r0   
num_groupssliding_windowslayer_index_to_group_indicesr-   r(   tp_sizemax_memory_percentr   PagedAttentionMemoryHandler%infer_max_batch_tokens_and_num_blockstorchtensorint64tp_all_reduce_minintitemmax_batch_tokens
num_blocks	num_pagesr   infomax_blocks_per_requestfallback_max_blocks_per_request	key_cachevalue_cachecache_shaperead_trash_indexsentinel_indexwrite_trash_indexr+   empty_dynamomark_static_addressr2   viewfill_shapenumelrL   group_cache_managersnum_full_attention_groupsnum_sliding_attention_groups%max_sliding_window_blocks_per_requestr   r   _max_blocks_per_requestuse_prefix_sharingr   _block_manager_total_prefix_length_block_table_key)selfr   rA   rB   rC   rD   rE   r:   r<   r9   r6   groupr(   jlayerkv_is_tpkeyrS   r]   r^   syncra   block_based_shaper4   new_layer_key_cachenew_layer_value_cache
group_typecms                               r   __init__zPagedAttentionCache.__init__   s   ( 
 ):&(A *62 5????T111;D<P<P;QQ[\`\k\k[lmnn %>f$E!ka)
l+!,.)!,/ 	=HAu6A!nH[6[V22abN%e, =5<=q611%8.<$$U+=	= M 	C7Nhn&? 	 %,,Q;8'''1Q6 01I1I0JJuv}u~~  A  $$0$ &88@&1Kbfg'B'A**#!(
 0
/
1 	%* Q;<<!1: >t{{Z_ZeZefD006+.tAw||~+>DGLLN@Sj !1$4??:H0E0E/II^DOOK__tbfbqbqauvw "<!R!R!)%?%_%_"&<# .0/1 (!^T__d>V>VX\XeXef'!^t>@X@XZ^ZgZgh *T__ <(4??:Q>",q.DOO!Cz" 		OA"'++d.>.>djjY]YdYd"e$)KK0@0@

[_[f[f$g!MM--.ABMM--.CDNN!!"56##$9:$$%67
CII!L!&&'89*EKKAN		O 	*t''++GT^^A->-D-D,HHf$..YZJ[JaJaJcIghi $>#Q#Q :<!)*&,-)562&{3 	1MAz--0DOOY]YqYqr..!3.223t(=(=t?R?RTXTjTj 11Q61=?=W=W: #7
|!DEE%%,,R0	1 #'":":"`{O_N`?`*:tgXYkZ)*! !%r!   num_requested_blocksallocated_blocksc                     || j                   z  }| j                  r5t        | j                  |z
  d      }|t	        ||      | j                  z  z  }|S )a  Returns the number of physical blocks needed to allocate (num_requested_blocks) blocks to a request that
        already has (allocated_blocks) blocks. The number of newly allocated blocks needed is predicted by the
        following rules:
        - for full attention groups: since there is no sliding window for full attention layers, one requested block is
            always equivalent to one newly allocated block for EACH full attention group
        - for sliding window groups: because of the sliding window, the number of blocks allocated to a request is
            capped. Using the number of already (allocated_blocks) we can compute the number of new blocks to actually
            allocate to the request, which can be lower than the number of requested blocks. That number is the same for
            all sliding window groups, as only one sliding window size is supported.
        r   )rq   rr   maxrs   min)ry   r   r   needed_blocksblocks_lefts        r   blocks_neededz!PagedAttentionCache.blocks_needed)  sY     -t/M/MM,,dHHK[[]^_KS.BCdFgFgggMr!   c                 H    | j                  ||      | j                         k  S )zcReturns a boolean indicating if the allocation of (num_requested_blocks) blocks will be successful.)r   get_num_free_blocks)ry   r   r   s      r   will_allocation_be_successfulz1PagedAttentionCache.will_allocation_be_successful<  s%    !!"68HITMeMeMgggr!   
request_idc                 @    t        fd| j                  D              S )zfReturns the total number of physical blocks currently referenced by a request across all layer groups.c              3   h   K   | ])  }t        |j                  j                  d              + yw) N)r0   block_tabler.   ).0r   r   s     r   	<genexpr>z4PagedAttentionCache.blocks_in_use.<locals>.<genexpr>B  s'     _r3r~~))*b9:_s   /2)sumrp   )ry   r   s    `r   blocks_in_usez!PagedAttentionCache.blocks_in_use@  s    _TE^E^___r!   n_blocksc                     | j                  ||      syd}| j                  D ]>  }|j                  ||| j                        }|t	        d| d|       t        ||      }@ |S )zAllocate cache blocks across all layer groups for a given request. Actual allocation is done by the cache
        managers, and this method only returns the maximum number of blocks actually allocated across all managers.Nr   zFailed to allocate z blocks for request )r   rp   allocate_blocksrv   r   r   )ry   r   r   r   max_allocatedr   num_allocated_blockss          r   r   z#PagedAttentionCache.allocate_blocksD  s     11(<LM++ 	EB#%#5#5h
DL_L_#` #+ #6xj@TU_T`!abb/CDM		E
 r!   c                 ^    | j                   D ]  }|j                  || j                           y)zFree all allocated cache blocks for a given request across all layer groups. Actual deallocation is done
        by the cache managers.N)rp   free_blocksrv   )ry   r   r   s      r   r   zPagedAttentionCache.free_blocksS  s-     ++ 	<BNN:t':':;	<r!   c                 .    | j                   j                  S )zHGet the current number of unallocated blocks available for new requests.)rv   num_free_blocks)ry   s    r   r   z'PagedAttentionCache.get_num_free_blocksY  s    ""222r!   past_lengthquery_length
read_indexwrite_indexc                 
   t        | j                  |      D ]'  \  }}|j                  |j                  |||             ) |At        | j                  |      D ]'  \  }}|j                  |j	                  |||             ) yy)aM  Retrieve physical cache indices for reading KV states in the cache across all layer groups. This method
        coordinates with all cache managers to build the complete set of read indices needed for attention computation.
        When read_index is None, the batch has no cache reads and we only compute the write indices.
        N)ziprp   extendget_write_indicesget_read_indices)	ry   r   r   r   r   r   r   write_indicesread_indicess	            r   extend_read_and_write_indicesz1PagedAttentionCache.extend_read_and_write_indices]  s     "%T%>%>!L 	^B  !5!5j+|!\]	^ !$'(A(A:$N ` L##B$7$7
KQ]$^_` "r!   r   c                 l    t        | j                        D ]  \  }}|j                  |||||           y )N)r-   rp   fill_block_table)ry   r   r   r   r   r6   r   s          r   r   z$PagedAttentionCache.fill_block_tableq  s=     t889 	WEAr
K{ST~V	Wr!   c                     i }| j                   dkD  r||z   |d<   | j                  dkD  r)|t        || j                  j                  dz
        z   |d<   |S )zRetrieve the key sequence length for the given request_id across all layer types. Returns a dictionary of
        layer types to their corresponding key sequence lengths.r   r*   r   r)   )rq   rr   r   r   r(   )ry   r   r   	seqlens_ks       r   get_seqlens_kz!PagedAttentionCache.get_seqlens_kw  sb     	))A-*5*DI&',,q0-9CT[[MgMgjkMk<l-lI)*r!   
key_statesvalue_states	layer_idxc                    | j                   |   \  }}||   }||   }	| j                  |   }
| j                  |   }|j                  dd      j	                  d      }|j                  dd      j	                  d      }|j                         dk(  r*|
j                  d|	|       |j                  d|	|       ||fS | j                  |   }|dk(  rX|
j                  d|	|       |j                  d|	|       t        j                  |
d|      }t        j                  |d|      }||fS || j                  k(  j                  d      j                  d      }t        j                  |
d|      }|j                  ||       t        j                  |d|      }|j                  ||       |
j                  d|	|       |j                  d|	|       ||fS )a\  Update the cache with new key-value states for a specific layer, and retrieves the relevant KV states from
        the cache for attention computation. The behavior differs based on the layer's attention type:

        - Full attention: New KV states are written to cache, then complete sequence is read from cache
        - Sliding window: Old KV is read from cache along with extra spaces for the new KV, then new KV is written to
            cache. This is because new KV might overwrite the old KV, so we need to read the old KV first.

        When the layer's read index is empty, the batch has no cache reads (all requests are non-chunked prefills): we
        only write to the cache and return the input KV states directly, skipping the index_select read-back.

        Returns the complete KV states (cached + new) for attention computation.
        r   rK   r   )rR   rc   rd   	transposesqueezero   index_copy_rQ   rW   index_selectrg   	unsqueezemasked_scatter_)ry   r   r   r   r   r   	group_idxlayer_idx_in_grouplayer_read_indexlayer_write_indexk_cachev_cacher(   key_states_with_cachevalue_states_with_cachemasks                   r   updatezPagedAttentionCache.update  s   * )-(I(I)(T%	%%i0'	2..!34""#56))!Q/77:
#--a3;;A> !!#q(#4jA#4lC|++ --i8Q#4jA#4lC$)$6$6wCS$T!&+&8&8!EU&V#" %&=== %(;(;;FFrJTTUWXD$)$6$6wCS$T!!11$
C&+&8&8!EU&V##33D,G#4jA#4lC %&===r!   flash_attn_with_kvcache_fnc                 *   | j                   |t        j                  |      j                  j	                         }d|v rd| _         | j                   S d|v rd| _         | j                   S t        dt        j                  |             | j                   S )zA function to get the name of the block table key for the given flash_attn_with_kvcache_fn. The function's
        signature is only inspected once. This is necessary because different version of flash have different names for
        the block table key.r   
page_tablezOflash_attn_with_kvcache_fn does not have a block_table or page_table argument: )rx   inspect	signature
parameterskeysr   )ry   r   kwarg_namess      r   get_block_table_keyz'PagedAttentionCache.get_block_table_key  s       (!++,FGRRWWYK+(5% $$$ ,(4%
 $$$ !efmfwfw  yS  gT  fU  V  $$$r!   
prompt_idsc                 h   d}g }t        t        |      | j                  z        D ]  }||| j                  z  |dz   | j                  z   }| j                  j	                  ||d      }| j                  j
                  j                  |      }|-|j                  |       | j                  j                  |        n |rCt        j                  d| dt        |       d       | j                  d   }||j                  |<   t        |      | j                  z  }	| xj                  |	z  c_        |	S )a  Searches for a prefix match in the cache for the given (prompts_ids). If one is found, we reference the
        matching blocks in the (request_id), increase the reference count of the blocks and return the number of blocks
        that match. If no prefix match is found, we return 0.Nr   r   )group_idzFound prefix match for request z with z blocks)r+   r0   rN   rv   compute_hash_hash_to_idr.   r2   increase_ref_countr   debugrp   r   rw   )
ry   r   r   current_hashr   btokensblock_idr   prefix_lengths
             r   search_prefix_matchz'PagedAttentionCache.search_prefix_match  s)    s:$//9: 		ADOO 3q1u6OPF..;;L&[\;]L**66::<HH# ''1##66x@		 LL::,fSQaMbLccjkl**1-B)9BNN:&,-?!!]2!r!   statenum_complete_blocksc                    |dk(  s|j                   t        j                  k(  ry| j                  D ][  }|j                  s| j
                  j                  ||j                  |j                     |j                  |j                  z          ] y)a  Marks the blocks allocated to a request (state) as complete if they are shareable and they have been computed
        in the forward pass. A complete block is a block where the KV cache has been fully computed: if the block has
        enough space to hold the cache for N tokens, the block is marked as complete when the cache data is present for
        the N tokens. If block sharing is off, this is a no-op.r   N)r   r   r   )statusr   FINISHEDrp   uses_block_sharingrv   !mark_shareable_blocks_as_completer   r   initial_tokensgenerated_tokens)ry   r   r   r   s       r   r   z5PagedAttentionCache.mark_shareable_blocks_as_complete  s     !#u||}7M7M'M++ 	B$$##EE(;%'^^E4D4D%E % 4 4u7M7M M F 	r!   list_source_blockslist_forked_blocksc                    t        j                  || j                  t         j                        }t        j                  || j                  t         j                        }t	        | j
                  | j                        D ]y  \  }}|j                  d| j                  | j                  | j                        }|j                  d| j                  | j                  | j                        }||   ||<   ||   ||<   { y)z;Copy the cache from the source blocks to the forked blocks.rJ   r   N)rW   rX   rB   int32r   rc   rd   rl   rN   r   r#   )ry   r   r   source_blocksforked_blocksrc   rd   s          r   
copy_cachezPagedAttentionCache.copy_cache  s    %7SXS^S^_%7SXS^S^_&)$..$:J:J&K 	D"I{!r4??D<T<TVZVcVcdI%**2t@X@XZ^ZgZghK'0'?Im$)4])CK&		Dr!   source_request_idc                    d}| j                   D ]a  }|j                  |   }d}|j                  r1|D ],  }| j                  j                  |   j
                  s n|dz  }. |t        |      |z
  z  }c |dk(  ry| j                         |z  S )z\Computes the maximum number of children requests that can be forked from the source request.r   r   l        )rp   r   r   rv   _id_to_blockis_completer0   r   )ry   r   blocks_needed_per_forkr   	block_idsshareable_blocksr   s          r   compute_max_num_forksz)PagedAttentionCache.compute_max_num_forks  s     "#++ 	HB'89I $$ ) *H..;;HEQQ$)$* #c)n7G&GG"	H "Q&'')-CCCr!   destination_request_idsc                     g g }}| j                   D ]D  }|j                  ||| j                        \  }}|j                  |       |j                  |       F ||fS )zhFork the cache of a request (state) into the one of a list of requests with the given (dst_request_ids).)rp   fork_blocksrv   r   )ry   r   r   r   destination_blocksr   
src_blocks
dst_blockss           r   fork_requestz PagedAttentionCache.fork_request  sm     -/)++ 	2B%'^^4EG^`d`s`s%t"J
  ,%%j1	2 000r!   c                     t               }| j                  D ]+  }|j                  |j                  j	                                - |D ]  }| j                  |        y)a  Free all blocks allocated to requests across all cache managers. This preserves prefix hashes in the block
        manager (blocks become initialized rather than uninitialized if they were complete), allowing prefix sharing
        to work across generation sessions.N)setrp   r   r   r   r   )ry   all_request_idsr   r   s       r   free_all_requestsz%PagedAttentionCache.free_all_requests#  sX     %++ 	:B""2>>#6#6#89	:) 	)JZ(	)r!   )r   N)'__name__
__module____qualname____doc__rO   rW   float16r   r	   rB   strr   dictr   rE   r   r[   r   boolr   r   r   r   r   listr   Tensorr   r   tupler   r   r   r   r   r   r   r   r  r   r!   r   r?   r?   Y   s   6p O #]]S% S% %=S% s"	S%
 .S% c3hS% {{S% 
S%j#  QT &h# hY\ hae h` ` `  PS X[^bXb <c <d <3S 3`` ` 	`
 cOd*` $s)_` 
`(WW,/W?BWQVQ]Q]W	W	 	C 	DcN 	;>LL;> ll;> 	;>
 &;> %,,';> 
u||U\\)	*;>z%c %c % c tCy S 4| Z] bf "DT#Y DDQTI DZ^ DDs Ds D$	1c 	1DQTI 	1Z_`deh`ikopskt`tZu 	1)r!   r?   c                      e Zd ZdZdZdZdededej                  de
e   ded	d
fdZed	eeeedf   f   fd       Zd	efdZd	eeef   fdZded
z  ded
z  ded
z  d	eeef   fdZdeedf   ded
z  ded
z  ded
z  d	eeef   f
dZdeded	eeef   fdZdededed	efdZdeedf   d	eedf   fdZdeded	efdZy
)rU   u  Determines the optimal max batch tokens (M) and number of blocks (N) for the paged attention cache, given
    available GPU memory. The relation between N and number of blocks is: num_blocks = N // block_size.

    The memory footprint is a polynomial in M and N, where each term maps to a tensor allocated in
    ``ContinuousBatchingIOs._setup_static_tensors`` or ``PagedAttentionCache.__init__``:

        memory(M, N)  =  coeff_m · M  +  coeff_n · N  +  coeff_mn · M·N  +  coeff_mm · M²

    See ``_equation_coefficients`` for the breakdown.  All three solving modes (auto, fixed-N, fixed-M) reduce to
    solving this equation, which is at most quadratic in one variable.
       i    r   rA   rE   r<   r9   r   Nc                    || _         || _        || _        || _        |j                  | _        t        |      t        |      z  | _        t        |      | _	        || _
        t        | j                         rd| _        nd|v rdnd| _        |j                  | _        | j                  |j                  | _        |j                  rdnd| _        |j"                  rdnd| _        | j'                         | _        y)av  Initialize the memory handler. Args:
        - config: the model configuration
        - continuous_batching_config: the continuous batching configuration
        - dtype: the data type of the activation and the cache
        - group_types: the list of all attention group types, formatted as strings
        - group_size: the size (in layers) of an attention group
        r   r)   rK   r   N)r   rH   cache_dtypeactivation_dtyperN   r%   r    	page_sizer0   rP   r9   r
   num_attention_masksra   rb   return_logprobsnum_output_rowsuse_async_batchingio_multiplierget_available_memoryavailable_memory)ry   r   rA   rE   r<   r9   s         r   r   z$PagedAttentionMemoryHandler.__init__>  s     3  %4??&v.1B61JJk*$ (4'(D$,?;,NqTUD$&@&W&W#&&.*D*d*dD'$>$N$NqTU"<"O"OQUV $ 9 9 ;r!   .c                    | j                   j                  t        | j                         z  }| j                  }i }| j                   j                  | j
                  j                  z  }|| j                   j                  t        j                  j                  z  z  }|dddf|d<   | j
                  j                  | j                   j                  |z   d|z  z   z  }d|z  | j
                  j                  z  }||ddf|d<   |S )Nr   lm_headrK   	attention)
r   r   r%   r  r$   r  itemsize
vocab_sizerW   float32)ry   mem_per_q_tokenmem_per_k_or_v_tokenpeaksdelta_mdelta_ns         r   activation_peakz+PagedAttentionMemoryHandler.activation_peake  s    ++99M$++<VV#~~ ++))D,A,A,J,JJ4;;))EMM,B,BBB#Q1-i ''00KK##&&'
 **T-B-B-K-KK%w15kr!   c                     t               \  }}}}|t        ||      z
  }t        || j                  j                  z        }t        j                  d|dz   d       |S )zCalculate available GPU memory for cache allocation in bytes, accouting for the maximum memory percent limit
        fixed by the continuous batching config.z'Memory available for cache allocation: i   z MB)r   r   r[   rH   rT   r   r`   )ry   r4   totalreserved	allocatedr  s         r   r  z0PagedAttentionMemoryHandler.get_available_memory|  sh     )H(I%5(I 3y(#;;/$..2S2SST=>NRY>Y=ZZ]^_r!   c                    | j                   j                  }| j                   j                  }||| j                  ||      S ||)| j	                  ||d      \  }}| j                  ||      S | j	                  ddd      \  }}t        | j                  |      }t        || j                        }| j	                  ||d      \  }}| j                  ||      S )aX  Infers max_batch_tokens and num_blocks based on the available memory and the size of the activation peaks.
        If neither value is provided, we use a default value of 8192 for max_batch_tokens, apply bounds depending on the
        available VRAM, and solve for num_blocks. If one value is provided, the other is found using a linear solve.N)cache_fill_per_batchg?)r]   r^   r+  )	rH   r]   r^   _check_footprint_solve_for_peaksr   _default_max_batch_tokensr   _min_max_batch_tokens)ry   r]   r^   upper_bound_vramr4   s        r   rV   zAPagedAttentionMemoryHandler.infer_max_batch_tokens_and_num_blocks  s     >>::^^..
 'J,B(()9:FF ':+A+/+@+@ *4 ,A ,(j (()9:FF #33!!$ 4 
!
 t==?OP/1K1KL'+'<'<=Mzpt'<'u$*$$%5zBBr!   r]   r^   r+  c                 $   g }| j                   j                         D ],  }| j                  ||||      \  }}|j                  ||f       . t	        |D cg c]  }|d   	 c}      }	t	        |D cg c]  }|d   	 c}      }
|	|
fS c c}w c c}w )a  Returns max_batch_tokens and num_blocks so that their memory footprint is within the available memory for all
        activation peaks. If neither value is given, a value must be provided for cache_fill_per_batch: this means we
        solve for both varibles by saying each batch fill a certain percentage of the cache (eg, if cache_fill_per_batch
        is 0.01, each batch will fill 1% of the cache).r   r   )r%  r/   _solve_for_peakr2   r   )ry   r]   r^   r+  	solutionspeak_deltasmnsolutionfinal_mfinal_ns              r   r-  z,PagedAttentionMemoryHandler._solve_for_peaks  s     	//668 	%K''5EzSghDAqaV$	% 9=xx{=>9=xx{=> >=s   B1Bpeakc                    | j                  |      \  }}}}|k|i|t        d      |}	| j                  ||	z  ||	dz  z  z   |||	z  z   | j                         }
t	        |
|	z        }t	        |
      | j
                  z  }||fS |B|}t        | j                  ||z  z
  ||dz  z  z
  |||z  z   z        }
|
| j
                  z  }||fS |A|| j
                  z  }t	        | j                  ||||z  z   ||z  | j                  z
              }||fS )z~Returns a couple of `(max_batch_tokens, num_blocks)` that satisfy the memory constraint for the given
        activation peak.z>m must be provided if max_batch_tokens and num_blocks are NonerK   )_equation_coefficientsr   _solve_quadraticr  r[   rN   r   )ry   r:  r]   r^   r+  r   cncmncmmr5  r_   MNs                r   r2  z+PagedAttentionMemoryHandler._solve_for_peak  sX     66t<BS #
(:#+ !abb$A--cAgad
.BBaKRVRgRgQghI"9q=1Y4??:J  ++  At44rAv=ad
JrTWZ[T[|\]I"doo5J  ++ %T__,A"4#8#8b37lBQRFUYUjUjLj#kl++r!   c                     | j                  ||      }|| j                  kD  rt        d| d| j                         |dk  s|dk  rt        d| d|       ||fS )zDChecks if the footprint of the cache is within the available memory.zMemory footprint z is more than available memory r   z#Invalid values: max_batch_tokens = z, num_blocks = )compute_memory_footprintr  MemoryErrorr   )ry   r]   r^   memory_footprints       r   r,  z,PagedAttentionMemoryHandler._check_footprint  s    889I:Vd333#$4#55TUYUjUjTkl  q J!OBCSBTTcdncopqq++r!   ar   cc                     |dk(  rt        | |z        S |dz  d|z  |z  z
  }|dk  rt        d| d      | t        |      z   d|z  z  }|dk  rt        d| d      t        t        |            S )u_   Largest positive root of a·x² + b·x + c = 0. Falls back to linear when a == 0. Rounded down.r   rK   r@   z!No real solution (discriminant = )zNo positive solution (root = )r[   r   r   r   )ry   rG  r   rH  discriminantroots         r   r=  z,PagedAttentionMemoryHandler._solve_quadratic  s    6rAv;!ta!eai'!@aPQQT,''AE2!8<TF!DEE5;r!   r4  c                 F   |\  }}}}t         j                  j                  }| j                  j                  }| j                  j                  }| j
                  }	|d| j                  z  | j                  z  |z  z   |	| j                  z  dz  z   }
||	dz  |z  z   |	| j                  z  |z  z   |	| j                  z  | j                  z  |z  z   |	| j                  z  dz  z   |	| j                  z  dz  z   }||	| j                  z  |z  z   }||	| j                  z  |z  z   }||
||fS )zGiven some deltas corresponding to an activation peak, returns the coefficients for the memory polynomial of
        that peak. The memory polynomial is described in that class docstring.rK         )rW   r   r  r  r  r  r9   r  rP   r  ra   r  )ry   r4  r#  r$  delta_mmdelta_mnr6   rG  rH  kcoeff_ncoeff_mcoeff_mncoeff_mms                 r   r<  z2PagedAttentionMemoryHandler._equation_coefficients  sm    0;,(HKK  !!**%% $//!DNN2Q67$//!A%& 	 !eai$&&&*+ $//!))*,-..
 $//!A%& $//!A%& 	 $***Q./ 	 $***Q./ 	
 833r!   c                     |}|| j                   z  }d}| j                  j                         D ]A  }| j                  |      \  }}}	}
||z  ||z  z   |	|z  |z  z   |
|z  |z  z   }t	        ||      }C |S )zaEvaluate the memory polynomial at concrete (N, M) values, taking the max across activation peaks.r   )rN   r%  r/   r<  r   )ry   r]   r^   rA  rB  max_memory_footprintr:  r   r>  r?  r@  rF  s               r   rD  z4PagedAttentionMemoryHandler.compute_memory_footprint  s    ( ((//1 	OD#::4@BC!AvQq1<sQw{J#&';=M#N 	O $#r!   )r  r  r  r  r/  r.  r   r	   rW   rE   r
  r  r[   r   propertyr  r  r%  r  rV   floatr-  r2  r,  r=  r<  rD  r   r!   r   rU   rU   .  s   
   $%< %< %=%< {{	%<
 #Y%< %< 
%<N c5c?&:!;  , c  CuS#X C< *  $J  $dl	 
 
sCx (!,CHo!, *!, $J	!,
 $dl!, 
sCx!,F	, 	,# 	,%PSUXPX/ 	,
 % 
 E 
 e 
  
 '4%S/ '4eCQTHo '4T
$ 
$# 
$RU 
$r!   rU   )%r   mathr   r   r   typingr   rW   configuration_utilsr   generation.configuration_utilsr	   utils.genericr
   cache_managerr   r   r   r   distributedr   initializationr   requestsr   r   r   r   r[   r    r%   r  r
  r  r=   r?   rU   r   r!   r   <module>rd     s     ! !   3 F 9 t t * 6 Z Z
p. 
p3 
pw* ws w%&6 %5d3iRVWZR[A[;\ %BR) R)jy$ y$r!   