
    ^j                         d dl mZ d dlmZ d dl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 d
dlmZ d
dlmZmZmZ d
dlmZmZmZmZmZ  G d de      Z G d d      Z G d d      Z G d d      Zy)    )nullcontext)partial)repeat)	TypedDictN)PretrainedConfig)ContinuousBatchingConfig   )get_available_devices   )PagedAttentionCache)%ContinuousBatchingLogitsProcessorList)TMP_TOKEN_IDFutureRequestStatelogger)CudaGraphBufferaligned_divideattn_mask_is_neededbuild_attention_maskpad_to_pow2c                      e Zd ZU dZej
                  ed<   ej
                  eeej
                  f   z  dz  ed<   ej
                  ed<   ej
                  ed<   ej
                  eeej
                  f   z  ed<   e	ed<   e	eee	f   z  ed	<   e
ej
                     ed
<   e
ej
                     ed<   ej
                  ed<   eed<   ej
                  dz  ed<   ej
                  ed<   eed<   y)PagedAttentionArgsa  The keyword arguments for a forward pass using paged attention, passed directly as model forward kwargs.

    Attributes:
        input_ids: Input token IDs tensor of shape `(1, total_query_tokens)`.
        attention_mask: Attention mask tensor or dictionary mapping layer types to masks. Can be `None` if the
            attention implementation doesn't require explicit masks.
        position_ids: Position IDs tensor of shape `(1, total_query_tokens)`.
        cu_seq_lens_q: Cumulative sequence lengths for queries, used for variable-length batching.
        cu_seq_lens_k: Cumulative sequence lengths for keys/values. Can be a tensor or dictionary mapping layer
            types (e.g., "full_attention", "sliding_attention") to tensors for hybrid models.
        max_seqlen_q: Maximum query sequence length in the batch.
        max_seqlen_k: Maximum key/value sequence length. Can be an int or dictionary for hybrid models.
        write_index: List of tensors indicating where to write new KV states in the cache, one per attention group.
        read_index: List of tensors indicating which cache positions to read from, one per attention group.
        logits_indices: Tensor indicating which positions in the output should be used for next-token prediction.
        cache: The [`PagedAttentionCache`] instance managing the KV cache.
        block_table: Block table for paged KV cache. If provided, uses `flash_attn_with_kvcache` for fused attention +
            cache update. More information in src/transformers/integrations/flash_paged.py
        logits_processor_args: List of tensors containing the arguments for the logits processors, one per request.
        use_cache: Whether to use caching (always `False` in continuous batching as the cache is managed externally).
    	input_idsNattention_maskposition_idscu_seq_lens_qcu_seq_lens_kmax_seqlen_qmax_seqlen_kwrite_index
read_indexlogits_indicescacheblock_tablelogits_processor_args	use_cache)__name__
__module____qualname____doc__torchTensor__annotations__dictstrintlistr   bool     /var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/generation/continuous_batching/input_outputs.pyr   r      s    , ||LL4U\\(9#::TAA,,<<<<$sELL'8"999S#X&&ell##U\\""LL $$ <<'Or3   r   c                      e Zd ZU dZdZeed<   dedede	de
j                  de
j                  d	ed
dfdZd	ed
dfdZ	 d,dd de
j                   j"                  ded
dfdZ e
j(                         d,ded
dfd       Zd-dZd
ee
j0                  eee
j0                  f   f   fdZde
j0                  de
j0                  de
j0                  d
dfdZd-dZd
eee   ee   ee    dz  f   fdZ!dee   dededed ed!ed
dfd"Z"d!ed
efd#Z#d,d!ed
e$fd$Z%d
ee
j0                  e
j0                  e
j0                  f   fd%Z&d
eed&f   fd'Z'd.d(ed
e
j                   jP                  dz  fd)Z)d*e
j                   jP                  d
dfd+Z*y)/ContinuousBatchingIOszA class to hold inputs and outputs for a continuous batching forward pass, using static tensors as storage. The
    class is meant to be self-contained, so once a set of inputs have been created, the class can be used to update the
    batch alone.
       static_inputsr"   configcontinuous_batching_configdevicemodel_dtypelogit_processorreturnNc                 &   || _         || _        || _        || _        |j                  | _        |j
                  d   | _        t        |dd      dn|j                  | _        |j                  | _	        d| _
        d| _        d| _        t        |j                        D cg c]  }d c}| _        t        |j                        D cg c]  }d c}| _        d| _        g | _        i | _        t)               | _        |j,                  | _        |j0                  | _        | j5                  |       | j7                  d       |j8                  d	k(  r0t:        j<                  j?                  | j                  
      | _         yd| _         yc c}w c c}w )a3  Initialize the continuous batching I/O manager. Args:
        - cache: The [`PagedAttentionCache`] instance managing the KV cache. Meant to be unique.
        - config: The model's pretrained configuration.
        - continuous_batching_config: The continuous batching configuration.
        - device: The device to allocate tensors on. If the device is CPU, then the memory is pinned.
        - model_dtype: The data type for model computations.
        - logit_processor: The [`ContinuousBatchingLogitsProcessorList`] object used to process the logits.
        r   sliding_windowNr   F)r=   T
full_resetcudar;   )!r"   r;   r9   r<   max_requests_per_batchcuda_graph_booleansuse_cuda_graph_varlengetattrr@   return_logprobsnum_q_tokensmax_kv_readnum_request_in_batchrange
num_groupstrue_read_sizestrue_write_sizesuse_block_tablerequests_in_batchreq_id_to_new_token_positionr   graphsread_trash_index_read_trash_indexwrite_trash_index_write_trash_index_setup_static_tensors_reset_static_tensorstyper*   rC   Streamcompute_streamselfr"   r9   r:   r;   r<   r=   _s           r4   __init__zContinuousBatchingIOs.__init__N   s`   $ 
&&@&W&W#%?%S%STU%V"#*63CT#J#RaX^XmXm9II$%!+01A1A+BCaC,1%2B2B,C Dq D$;=<>)'6'8!&!7!7"'"9"9""?"C""d"3GM{{V\G\ejj//t{{/Cbf  D Ds   	F		Fc                 	   | j                   j                  }| j                   j                  }| j                  }| j                   j                  | j                   j
                  z  }| j                  j                  dk(  xr t        t                     dkD  }| j                  |j                  z   }t        |dz   dd      }t        j                  ||ft        j                  | j                  |      | _        t        j                  |j                  dft        j                  | j                        | _        |j%                  | j"                         | j                   dd|f   | _        | j                   dd|f   | _        | j                   dd|dz   f   | _        | j                   d	d|f   | _        | j                   d
d|dz   f   }	| j                   dd|dz   f   }
| j                   dd|f   | _        i | _        | j                   j2                  r|	| j0                  d<   | j                   j4                  r|
| j0                  d<   | j6                  rdnd}t        j                  ||dz   ft        j                  | j                  |      | _        | j8                  j;                          d| _        t>        jA                  | j0                  jC                         d      | _"        d| _#        t>        jA                  | j0                  jC                         d      | _$        tK        | jL                        rhi | _'        | j0                  jC                         D ]C  }t        j                  dd|||z   f| jP                  | j                  |      | jN                  |<   E nd| _'        | j                   jR                  dkD  r|nd}t        j                  ||| j                   jR                  ft        j                  | j                  |      | _*        t        j                  ||ft        jV                  | j                  |      | _,        t        j                  |||z   ft        jV                  | j                  |      | _-        y)a  Allocates static tensors for generation inputs and outputs. This is called only once at init time, to avoid
        repeated allocations and enable CUDA graphs. All tensors are allocated with maximum possible sizes.
        The allocated tensors are:

        - `_bulk_input_tensor`: Storage for all the small inputs: `input_ids`, `position_ids`, `cumulative_seqlens_q`,
          `logits_indices`, `cumulative_seqlens_k`, `carry_over_ids`.
        - `attention_mask`: Optional attention masks (only for eager/SDPA implementations)
        - `write_index` and `read_index` storage: Cache indexing tensors for each attention group
        - `output_ids`: Storage for generated token IDs and maybe log probabilities if return_logprobs is True
        cpur       )dtyper;   
pin_memoryre   r;   r   N   r	            full_attentionsliding_attention)sizere   r;   rf   ).r"   rN   max_batch_tokensrE   
num_blocks
block_sizer;   r[   lenr
   r8   tensors_requiredr   r*   emptyint32_bulk_input_tensorlogits_processors_defaultsfill_defaultsr   r   cumulative_seqlens_qr!   carry_over_idscumulative_seqlens_knum_full_attention_groupsnum_sliding_attention_groupsrI   
output_idszero_total_seqlen_qr-   fromkeyskeystotal_seqlen_kr   r   r   r9   r   r<   max_blocks_per_requestr#   int64write_index_storageread_index_storage)r_   r=   rN   ro   rE   	num_pagesrf   
bulk_linesbulk_columns#full_attention_cumulative_seqlens_k&sliding_attention_cumulative_seqlens_knum_output_rows
layer_typens                 r4   rY   z+ContinuousBatchingIOs._setup_static_tensorsz   s    ZZ**
::66!%!<!<JJ))DJJ,A,AA	[[%%.S37L7N3ORS3S
 ''/*J*JJ
%&6&:ArB"'++&ekk$++Zd#
 +0++--q1T[[+
' 	%%d&E&EF 004E5E4E1EF 33A7H8H7H4HI$($;$;A?[AWZ[A[?[<[$\!"55a9P:P9P6PQ.2.E.EaIeKadeKeIeFe.f+151H1HLhNdghNhLhIh1i."55a9J:J9J6JK >@!:://:]D%%&67::22=cD%%&9:  $33!++.235;;t{{gq
 	.2mmD<U<U<Z<Z<\^_.`,0MM$:S:S:X:X:Z\],^ t{{+"$D"77<<> 
27++Q 0)>N2NO**;;)	3##J/ #'D **;;a?JQ ;;&

(I(IJ++;;!	
 $);;)*%++dkk^h$
  #(++%556ekkRVR]R]jt#
r3   otherstreamnon_blockingc                 D   | j                   |_         | j                  |_        | j                  |_        | j                  d d  |_        | j                  d d  |_        | j
                  |_        | j                  |_        t        | j                        |_        | j                  |_	        t        | j                        |_
        |t        j                  j                  |      n	t               }|5  |j                  j!                  | j                  |       | j
                  r(|j"                  j!                  | j"                  |       n]|j$                  j!                  | j$                  |       | j                  dkD  r'|j&                  j!                  | j&                  |       | j(                  X|j(                  L| j(                  j+                         D ]/  }|j(                  |   j!                  | j(                  |   |       1 d d d        y # 1 sw Y   y xY w)Nr   r   )rJ   rK   rL   rO   rP   rQ   r   r-   r   r   r   r*   rC   r   r   rv   copy_r#   r   r   r   r   )r_   r   r   r   maybe_streamr   s         r4   _transfer_inputsz&ContinuousBatchingIOs._transfer_inputs   s    ".. ,,%)%>%>" $ 4 4Q 7!%!6!6q!9 $ 4 4#22#D$7$78!..!$"3"344:4Fuzz((0KM 	w$$**4+B+BQ]*^##!!''(8(8|'T ))//0H0HWc/d##a',,2243J3JYe2f"".53G3G3S"&"5"5":":"< wJ((4::4;N;Nz;Ziu:vw	w 	w 	ws   0DHHrB   c                    |r| j                   j                  d      n| j                  }|r| j                  j                  d      n| j                  }|r| j
                  dz   nt        | j                  | j
                        }| j                  d| j                  d|dz   f   j                          |r#| j                  | j                  | j                  d d| _        | j                  d| j                          | j                  ddd|f   j                          | j                  D ]  }d| j                  |<   d| j                   |<   | j"                  .| j"                  |   ddddd|d||z   f   j%                  t'        j(                  | j*                        j                          |r| j,                  ddd|f   j%                  d       | j                   ddd|f   j%                  | j.                         | j                  ddd||z   f   j%                  | j0                         y| j2                  r%| j,                  ddd|f   j%                  d       y| j                   ddd|f   j%                  | j.                         | j                  ddd||z   f   j%                  | j0                         y)a   Reset static tensors for the next batch. For efficiency, this only resets the portions of tensors that were
        actually used in the previous batch, using the attributes num_q_tokens and max_kv_read. If a (full_reset)
        is requested, the entire tensor storage is reset.
        r   Nr   )r   rn   rJ   r   rK   rE   minrv   r8   r   rw   r   r!   r~   r{   r   r   r   fill_r*   finfor<   r#   rX   rV   rQ   )r_   rB   q_lenkv_lenb_sizer   s         r4   rZ   z+ContinuousBatchingIOs._reset_static_tensors   s    6@((--b1TEVEV5?((--b1TEUEU4>,,q0CHYHY[_[v[vDw 	 4$"4"4 4k	k ABHHJ<@<[<[D##D$6$6$89 	GV$**,7F7
#))+ 33 	J,-Dj)./D
+"".##J/1fuf>N>N0NOUUKK 0 0155		 QZ(..r2$$QY/55d6M6MN##A'7'7$78>>t?U?UV!!QZ(..r2 $$QY/55d6M6MN##A'7'7$78>>t?U?UVr3   c                     | j                  d       g | _        i | _        | j                  | j                  j	                          yy)z4Reset all relevant states for a new generation loop.TrA   N)rZ   rR   rS   r]   synchronizer_   s    r4   resetzContinuousBatchingIOs.reset  sF    ""d"3!#,.)*++- +r3   c                 2    | j                   | j                  fS )z:Get the cumulative sequence lengths for the current batch.)ry   r{   r   s    r4   get_cumulative_seqlensz,ContinuousBatchingIOs.get_cumulative_seqlens(  s    (($*C*CCCr3   r   rz   prev_output_idsc                      y Nr2   )r_   r   rz   r   s       r4   carry_over_tokensz'ContinuousBatchingIOs.carry_over_tokens,  s     	r3   c                 R    | j                   | j                   j                          y y r   )r]   r   r   s    r4   retrieve_device_outputsz-ContinuousBatchingIOs.retrieve_device_outputs1  s%    *++- +r3   c                 &   | j                   dd | j                  f   j                         }| j                  rJ| j                   dd | j                  f   j	                  t
        j                        j                         }nd }| j                  ||fS )Nr   r   re   )r~   rL   tolistrI   viewr*   float32rR   )r_   
new_tokenslogprobss      r4   prepare_batch_updatez*ContinuousBatchingIOs.prepare_batch_update5  s    __Q(C$*C*C(C%CDKKM
q*ED,E,E*E'EFKKRWR_R_K`ggiH H%%z8;;r3   rR   logits_processorsuse_decode_fast_pathrJ   rK   use_paddingc           	         |st        d      |xr | j                  j                         dkD  | _        || _        | j                  rdn|| _        t        |      | _        | j                          t        | j                  j                        D cg c]  }d c}| _        t        | j                  j                        D cg c]  }d c}| _        g | _        i | _        g }g }	dg}
g }| j                   j#                         D ci c]  }|dg }}t        | j                  j                        D cg c]  }g  }}| j
                  dk(  rdn,t        | j                  j                        D cg c]  }g  c}}t%        |      D ]  \  }}|j&                  }|j(                  }|j*                  }| j                  j-                  ||      }|xj(                  |z  c_        |j/                  |j0                         |	j/                  t        |||z                |
j3                  |
d   |z          t5        | j6                  |      | _        |j9                         D ]H  \  }}||   j3                  ||   d   |z          t5        | j:                  |   |      | j:                  |<   J | j                  r:| j                  j=                  |j>                  ||| j                  dd|f          n)| j                  jA                  |j>                  ||||       |jB                  r?|j3                  |
d   dz
         tD        g|_        |d   | j                  |j>                  <   | j                  j3                  |        |jG                  || jH                  | jJ                  d        |
d   | _&        | jN                  E|j9                         D ]2  \  }}tQ        | jN                  |   |
||dk(  r| jR                  nd       4 |rG| jU                  |	      }|| j                  z
  }|
j/                  tW        | jL                  |             nd}tY        tZ        j\                  tZ        j^                  | j`                  
      } ||      | jb                  dt        |        ||	      | jd                  dt        |	        ||
      | jf                  dt        |
        ||      | jh                  dt        |       |j9                         D ]U  \  }}|d   }|| jj                  |<   |j/                  tW        ||              ||      | j                   |   dt        |       W | j                  stY        tZ        j\                  tZ        jl                  | j`                  
      }t%        |      D ]?  \  }} ||      | jn                  |dt        |      f<   t        |      | j                  |<   A |Nt%        |      D ]?  \  }} ||      | jp                  |dt        |      f<   t        |      | j                  |<   A yyyc c}w c c}w c c}w c c}w c c}w )a  Prepare tensors and metadata for the next model forward pass, using the given requests as data. This method:

        1. Resets the static tensors from the previous batch
        2. Iterates through requests to accumulate input_ids, position_ids, and sequence lengths
        3. Extends read/write indices for cache management
        4. Builds attention masks if needed (for eager/SDPA implementations)
        5. Converts accumulated lists to tensors and copies them to static storage

        This method also modifies the `position_offset` attribute of each request to track progress and adds a
        temporary token at the end of the requests for which there will a new token.
        zNo requests in batchr   Nr   r   )rR   arg_storagerm   )r   ry   r{   r@   r   rg   )9
ValueErrorr#   numelrQ   rJ   rK   rr   rL   rZ   rM   r"   rN   rO   rP   rR   rS   r{   r   	enumeratestateposition_offsetquery_lengthget_seqlens_kextendtokens_to_processappendmaxr   itemsr   fill_block_table
request_idextend_read_and_write_indiceshas_new_tokenr   prepare_tensor_argsrv   r8   r   r   r   r@   _get_num_sequencesr   r   r*   tensorru   r;   r   r   ry   r!   r   r   r   r   )r_   rR   r   r   rJ   rK   r   r`   r   r   ry   r!   r   r{   r   r    ifuture_stater   past_lengthr   	seqlens_klayer_type_seqlen_klayer_type_seqlens_knum_sequences_in_next_batchfake_sequences	to_tensorr   to_index_tensorgroup_write_indicesgroup_read_indicess                                  r4   prepare_batch_tensorsz+ContinuousBatchingIOs.prepare_batch_tensors?  s(   * !344  4T8H8H8N8N8PST8T( $ 4 41+$'(9$:!""$ ,11F1F+GHaH,1$**2G2G,H Iq I!#,.) 	 !sBFB[B[B`B`BbcJ
QCcc#()>)>#?@ar@@!--2TU4::K`K`Ea8b8b
  )):; #	8OA| &&E//K'44L

00lKI !!\1! U445k;3M NO ''(<R(@<(OP #D$5$5| DD 4=??3D h/
/$Z0778LZ8XY[8\_r8rs03D4E4Ej4QSf0g!!*-h
 ##

++E,<,<k<Y]YiYijkmnjnYop

88$$k<[
 ))%%&:2&>&BC+7.'FTUWFX11%2B2BC"")),7G#	8L 	--///0B0B0DE 	. 	
 326 *4H4N4N4P 0
0$#'#6#6z#B)=)=:DH[:[4#6#6ab	 *.*A*Ak*A*Z'84;T;TTN ''t/B/BN(ST N ELLDKKP	 ,5Y+?'Y(1:<1H-C-.AJK_A`!!"=C(<$=>5>~5N1c.12 1E0J0J0L 	q,J,1"5N.<D
+ ''~~(NOQZ[oQpD%%j12MC8L4MN		q ##%ell%++dkkZO*3K*@ D&&JYZmJn((,Fc2E.F,F)FG+./B+C%%a(D %-6z-B F)A)L[\nLoD++A/H5G1H/H,HI.12D.ED((+F & $G  I I  d@8bs   	Y	YY5	Y2	Yc                 ^    |r t        | j                  | j                        S | j                  S )zZGet the number of sequences for the current batch, accounting for padding if there is any.)r   rJ   rE   rL   )r_   r   s     r4   r   z(ContinuousBatchingIOs._get_num_sequences  s*    t(($*E*EFF(((r3   c                    | j                   }| j                  | j                   z   }| j                  |      }t        | j                  d| j                  d      | j                  d| j                  d      | j                  d|dz    | j                  | j                  d| | j                  | j                  dd|f   i i | j                  dni g g | j                  | j                  r| j                  ddd|f   ndd      }|ry|| _        | j                  sf| j                   rZ| j"                  j%                         D ci c]1  }|t'        | j"                  |   | j                  j(                  d      3 c}| _        | j                  rdn| j                  |d<   t+        | j                  j,                        D ]  }|r|n| j.                  |   }|d	   j1                  | j2                  |d|f          | j                  dk(  rd}	n|r|n| j4                  |   }	|d
   j1                  | j6                  |d|	f           | j8                  j;                         D ]u  \  }}
|
d|dz    |d   |<   | j                  rdn| j"                  |   |d   |<   | j                  D|r|n| j<                  |   }| j                  |   dd|d|f   |d   |<   w t?        | j8                  j%                               dk(  rW|d   jA                         d   |d<   |d   jA                         d   |d<   | j                  |d   jA                         d   |d<   |S c c}w )zGet model keyword arguments for the current batch, eventually padding the query dimension and KV dimensions
        if use_padding is True. The padding is only useful if we want static shapes, like when using cuda graphs.r   Nr   r   F)r   r   r   r   r!   r$   r   r   r   r    r   r"   r#   r%   i   r   r   r    r   r   .r   )!rJ   rK   r   r   r   	unsqueezer   ry   r   r!   rv   r8   r   r"   rQ   r#   rG   r   r   r   r   rM   rN   rP   r   r   rO   r   r{   r   r   rr   popitem)r_   r   q_sizekv_sizenum_sequenceskwargsr   r   write_index_sizeread_index_sizer   k_lens               r4   get_model_kwargsz&ContinuousBatchingIOs.get_model_kwargs  s    """"T%6%66//K/H $nnWf-77:**7F3==a@334Gma6GH**..~>"&"9"9$:L:L:NP^Q^P^:^"_#'#6#6#>4B**?C?S?S((N]N):;Y]
$  &D ''D,F,F '+&7&7&<&<&>%" D,=,=j,I4::K_K_ae ff%! '+&:&:@Q@Q~ tzz,,- 	VA)4v$:O:OPQ:R=!(()A)A!EVFVEVBV)WX1$"#-8'd>R>RST>U< ''(?(?CSOCS@S(TU	V &*%>%>%D%D%F 	m!J	2;<Oma>O2PF?#J/6:6J6JPTPaPablPmF>":."".#.D4G4G
4S7;7J7J:7VWZ\c]c\cekfkekWk7l'(4	m t((--/0A5&,_&=&E&E&G&JF?#%+N%;%C%C%Ea%HF>""".+12B+C+K+K+Ma+P'(G%s   6Mc                 H    | j                   | j                  | j                  fS )a.  Returns the tensors used inside the generation step that are not inputs to the model forward pass. In
        synchronous batching, there is no carry over, so the only tensor that will be used is output_ids, but we still
        return 3 tensors to have the same interface as when using async batching.)rz   r~   r   s    r4   get_cb_kwargsz#ContinuousBatchingIOs.get_cb_kwargs  s     ""DOOT__DDr3   .c                     | j                   r| j                  fS | j                  | j                  g| j                  j	                         S r   )rQ   rJ   rK   r   valuesr   s    r4   _get_graph_keyz$ContinuousBatchingIOs._get_graph_key  sE    %%''!!4#3#3Qd6G6G6N6N6PQQr3   prefixc                     | j                         }| j                  j                  |      }|t        j                  | d|       |S )NzCreating graph for key = )r   rT   	get_graphr   info)r_   r   keygraphs       r4   r   zContinuousBatchingIOs.get_graph%  sF    !!#%%c*=KK6("<cX>?r3   r   c                     | j                         }| j                  j                  ||       t        j                  d|       y )NzSetting graph for key = )r   rT   	set_graphr   r   )r_   r   r   s      r4   r   zContinuousBatchingIOs.set_graph-  s8    !!#c5)/12r3   Fr>   N) )+r&   r'   r(   r)   r8   r/   r,   r   r   r   r*   r;   re   r   ra   rY   rC   r\   r1   r   no_gradrZ   r   tupler+   r-   r.   r   r   r   r0   r   floatr   r   r   r   r   r   r   	CUDAGraphr   r   r2   r3   r4   r6   r6   F   s   
 M3*g"*g !*g %=	*g
 *g [[*g ?*g 
*gXW
5Z W
_c W
v _dw,w6;jj6G6GwW[w	w@ U]]_(W (W (W (WT.DellDellAR<S.S(T D7<||V[VbVb	
.<eD1C,Dd3iQUV[Q\_cQc,c&d <MF 23MF AMF #	MF
 MF MF MF 
MF^)d )s )BD B=O BHEuU\\5<<%MN ERc3h R UZZ-A-AD-H 3uzz33 3 3r3   r6   c                       e Zd Zdedededej                  dej                  de	ddfd	Z
dd
Zdej                  j                  ddfdZdej                  j                  dz  ddfdZy)HostDeviceIOPairr"   r9   r:   r;   r<   r=   r>   Nc                     t        |||t        j                  d      ||      | _        t        ||||||      | _        t        j
                  j                         rt        j
                  j                         nd | _        t        j
                  j                         rt        j
                  j                         nd | _	        t        j
                  j                         r$t        j
                  j                         | _
        y d | _
        y )Nrc   r"   r9   r:   r;   r<   r=   )r6   r*   r;   host_io	device_iorC   is_availableEventh2d_overcompute_overd2h_over)r_   r"   r9   r:   r;   r<   r=   s          r4   ra   zHostDeviceIOPair.__init__4  s     -'A<<&#+
 /'A#+
 /4jj.E.E.G

((*T27**2I2I2KEJJ,,.QU.3jj.E.E.G

((*Tr3   c                     | j                   j                          | j                  j                          | j                  | j                  | j
                  fD ]  }||j                           y r   )r   r   r   r  r  r  r   )r_   events     r4   r   zHostDeviceIOPair.resetS  sX    mmT%6%6F 	$E !!#	$r3   r   c                 T    | j                   j                  | j                  |d       y )NT)r   r   )r   r   r   )r_   r   s     r4   transfer_inputs_h2dz$HostDeviceIOPair.transfer_inputs_h2dZ  s     %%dnnVRV%Wr3   c                     |t         j                  j                  |      n	t               }|5  | j                  j
                  j                  | j                  j
                  d       d d d        y # 1 sw Y   y xY w)NTr   )r*   rC   r   r   r   r~   r   r   )r_   r   r   s      r4   transfer_outputs_d2hz%HostDeviceIOPair.transfer_outputs_d2h]  sc    4:4Fuzz((0KM 	XLL##))$..*C*CRV)W	X 	X 	Xs   <A33A<r   )r&   r'   r(   r   r   r   r*   r;   re   r   ra   r   rC   r\   r  r
  r2   r3   r4   r   r   3  s    R"R !R %=	R
 R [[R ?R 
R>$X%***;*; X XX5::+<+<t+C X Xr3   r   c                      e Zd ZdZdedededej                  dej                  de
dd	fd
Zdeej                  eeej                  f   f   fdZdee   de
dededededd	fdZdej                  fdZd#dedefdZdeej                  ej                  ej                  f   fdZdej                  dej                  dej                  dd	fdZedej                  fd       Zdej:                  j<                  d	z  fdZdej:                  j<                  dd	fdZ edefd       Z!d$dZ"d$d Z#deee   ee   ee$   d	z  f   fd!Z%d$d"Z&y	)%ContinuousBatchingAsyncIOsu  A class to handle the inputs and outputs for the asynchronous API. It uses two IO pairs to avoid race conditions
    between the two batches, which means twice as more VRAM is used for static input tensors and CUDA graph. If your GPU
    is large enough or you want to generate long sequences, this is a good trade-off to make.

    Asynchronous batching works by creating two pairs of host - device inputs and outputs:

                                    inputs
                      ┌──────────┐ ────────► ┌────────────┐
    IO pair object:   │ Host IOs │           │ Device IOs │       (for a CUDA system, Host = CPU and Device = GPU)
                      └──────────┘ ◄──────── └────────────┘
                                    outputs

    Each pair is separate from the other. This means that each pairs has its own CUDA graphs set, because CUDA graphs
    need to have static addresses for input tensors. To have a unique set of CUDA graph, we would need to copy the input
    tensors to a third device-side buffer. This could limit the memory cost of CUDA graphs but would slow down the
    forward pass.
    But the CUDA streams orchestrating the transfer from host to device (H2D) and device to host (D2H) are the same for
    both pairs. Same for the compute stream.
    The order of steps in async batching looks like this (for 3 batches of compute):

         │ ┌────┬────┐                  ┌────┬────┐     ┌────┬────┐       ┌────┐          ┌────┐
    CPU  │ │PR 0│PR 1│                  │UP 0│PR 2│     │UP 1│PR 3│       │UP 2│          │UP 3│
         │ └────┼───┬┴──┐               └────┴────┼───┐ └────┴────┼───┐   └────┘          └────┘
    H2D  │      │0->│1->│               ¦         │2->│ ¦         │3->│   ¦               ¦
         │      └───┼───┴───────────┬─────────────┴─┬─┼───────────┴───┼───────────────┐   ¦
    GPU  │          │   COMPUTE 0   │   COMPUTE 1   │█│   COMPUTE 2   │   COMPUTE 3   │   ¦
         │          └───────────────┼───┬───────────┼─┴─┬─────────────┼───┬───────────┼───┤
    D2H  │                          │0<-│           │1<-│             │2<-│           │3<-│
         │                          └───┘           └───┘             └───┘           └───┘

    with: - CPU: actions happening on the CPU (host-side)
          - GPU: actions happening on the GPU (device-side)
          - H2D: host to device transfer
          - D2H: device to host transfer
    and:
          - PR N: preparation of batch N
          - ->N: host to device transfer of batch N
          - COMPUTE N: compute step for batch N
          - <-N: device to host transfer of batch N
          - UP N: update of batch N

    You can see that the GPU is almost always busy, except where the █ is.
    Proper ordering of steps is ensured through the use of CUDA events and streams.
    r"   r9   r:   r;   r<   r=   r>   Nc                    t         j                  j                         s*t        dt         j                  j                               d| _        t        d      D cg c]  }t        ||||||       c}| _        t         j                  j                  |      | _	        t         j                  j                  |      | _
        t         j                  j                  |      | _        d | j                  d   j                  _        d | j                  d   j                  _        d | j                  d   j                  _        d | j                  d   j                  _        |j                  | _        y c c}w )Nz>Async batching requires CUDA, but torch.cuda.is_available() = r   rh   r   rD   r   )r*   rC   r   RuntimeErrorcurrent_pairrM   r   io_pairsr\   
h2d_stream
d2h_streamr]   r   r   ro   r^   s           r4   ra   z#ContinuousBatchingAsyncIOs.__init__  s3    zz&&(!`EJJD[D[D]Cabcc 1X

  +E' /

  **++6+:**++6+:#jj//v/>26a  /48a""126a  /48a""1 % 6 6+

s   E6c                 d    | j                   | j                     j                  j                         S r   )r  r  r   r   r   s    r4   r   z1ContinuousBatchingAsyncIOs.get_cumulative_seqlens  s&    }}T../77NNPPr3   rR   r   r   rJ   rK   r   c                     | j                   | j                     }|j                  j                  ||||||       |j                  j                  j                  | j                                y r   )r  r  r   r   rz   r   infer_carry_over_ids)r_   rR   r   r   rJ   rK   r   io_pairs           r4   r   z0ContinuousBatchingAsyncIOs.prepare_batch_tensors  s^     -- 1 12--02FVacn	
 	&&,,T-F-F-HIr3   c                    | j                   | j                     j                  j                  }| j                   d| j                  z
     j                  j                  }t	        | j
                        D cg c]  }d }}t        |j                               D ]  \  }}|j                  |      }||||<     t        j                  |t        j                        S c c}w )a  Infers the ids of the tokens to carry over from batch N to batch N+1. In asynchronous batching mode, we can
        schedule a request for batch N+1 without knowing the token predicted for that request in batch N. For that
        reason, we might need to carry over tokens just predicted in batch N before launching the forward pass of batch
        N+1. This method computes the ids of the tokens to carry over.r   r   r   )r  r  r   rS   rM   ro   r   r   getr*   r   ru   )r_   !next_req_id_to_new_token_position!prev_req_id_to_new_token_positionr`   rz   r   req_idnew_token_positions           r4   r  z/ContinuousBatchingAsyncIOs.infer_carry_over_ids  s    
 -1MM$:K:K,L,T,T,q,q),0MM!d>O>O:O,P,X,X,u,u)&+D,A,A&BC"CC ##D#I#I#KL 	7IAv!B!F!Fv!N!-5612	7 ||N%++>> Ds   5	Cc                 6   | j                   | j                     }|j                  | j                         | j                  j	                  |j
                         | j                  j                  |j
                         |j                  j                  |      S )Nr   )
r  r  r  r  record_eventr  r]   
wait_eventr   r   )r_   r   r  s      r4   r   z+ContinuousBatchingAsyncIOs.get_model_kwargs  st    -- 1 12##DOO4$$W%5%56&&w'7'78  11k1JJr3   c                     | j                   | j                     }| j                   d| j                  z
     }|j                  j                  |j                  j                  |j                  j                  fS )a  Returns the tensors used inside the generation step that are not inputs to the model forward pass. Those
        tensors could be retrieved using this object, but it would trigger a recompile if using torch.compile. They are:
        - output_ids: the output ids of the current batch
        - prev_output_ids: the output ids of the previous batch, required to carry over outputs tokens of the previous
            batch to the input tokens of the next batch.
        - carry_over_ids: a mask representing how to carry over tokens.
        r   )r  r  r   rz   r~   )r_   r  previous_pairs      r4   r   z(ContinuousBatchingAsyncIOs.get_cb_kwargs  sh     }}T%6%67a$*;*;&;<""11##..""--
 	
r3   r   rz   r   c                     |d|f   }|dk7  j                         }|d|j                  d       }|d|j                  d       }||z  |d   d|z
  z  z   |d<   y)a  As explained in the infer_carry_over_ids method, we might need to carry over tokens just predicted in batch N
        before launching the forward pass of batch N+1. This method performs the carry over, and is recorded in CUDA
        graphs if they are enabled.r   r   Nr   )r/   rn   )r_   r   rz   r   carried_over_idscarried_over_masks         r4   r   z,ContinuousBatchingAsyncIOs.carry_over_tokens  sy     +1n+<=+r1668+,?innQ.?@-.A	q0AB'*;;ilaRcNc>dd	!r3   c                 \    | j                   | j                     j                  j                  S r   )r  r  r   r~   r   s    r4   r~   z%ContinuousBatchingAsyncIOs.output_ids	  s%     }}T../99DDDr3   c                     d| j                    d}| j                  | j                      j                  j                  |      S )Nz(IO ))r   )r  r  r   r   )r_   r   s     r4   r   z$ContinuousBatchingAsyncIOs.get_graph  s@    ))*!,}}T../99CC6CRRr3   r   c                 h    | j                   | j                     j                  j                  |       y r   )r  r  r   r   )r_   r   s     r4   r   z$ContinuousBatchingAsyncIOs.set_graph  s%    d''(22<<UCr3   c                 \    | j                   | j                     j                  j                  S r   )r  r  r   rQ   r   s    r4   rQ   z*ContinuousBatchingAsyncIOs.use_block_table  s#    }}T../77GGGr3   c                 j   | j                   | j                     }| j                  j                  |j                         | j
                  j                  |j                         |j                  | j
                         | j
                  j                  |j                         | j                          y r   )
r  r  r]   r  r  r  r  r
  r  swap_io_pairsr_   r  s     r4   r   z2ContinuousBatchingAsyncIOs.retrieve_device_outputs  s~    -- 1 12(()=)=>""7#7#78$$T__5$$W%5%56r3   c                 ,    d| j                   z
  | _         y)zeSwitch to the other IO pair so the next batch reads from / writes into a fresh set of static buffers.r   N)r  r   s    r4   r+  z(ContinuousBatchingAsyncIOs.swap_io_pairs%  s     1 11r3   c                     | j                   | j                     }|j                  j                          |j                  j                         S r   )r  r  r  r   r   r   r,  s     r4   r   z/ContinuousBatchingAsyncIOs.prepare_batch_update*  s;    -- 1 12$$&3355r3   c                     d| _         | j                  D ]  }|j                           | j                  j	                          | j
                  j	                          | j                  j	                          y)zWReset all state for a new generation session. Used in persistent mode between sessions.r   N)r  r  r   r  r   r  r]   r,  s     r4   r   z ContinuousBatchingAsyncIOs.reset/  sX    }} 	GMMO	##%##%'')r3   r   r   )'r&   r'   r(   r)   r   r   r   r*   r;   re   r   ra   r   r+   r-   r.   r   r0   r   r1   r/   r   r  r   r   r   r   propertyr~   rC   r   r   r   rQ   r   r+  r   r   r   r2   r3   r4   r  r  c  s   +Z#7"#7 !#7 %=	#7
 #7 [[#7 ?#7 
#7LQellDellAR<S.S(T QJ 23J AJ #	J
 J J J 
J?ell ?(KD K=O K
uU\\5<<%MN 
"e<<e e 	e
 
e& EELL E ES5:://$6 SDuzz33 D D H H H	2
6eD1C,Dd3iQUV[Q\_cQc,c&d 6
*r3   r  ) 
contextlibr   	functoolsr   	itertoolsr   typingr   r*    transformers.configuration_utilsr   +transformers.generation.configuration_utilsr   utilsr
   r"   r   cb_logits_processorsr   requestsr   r   r   r   r   r   r   r   r   r6   r   r  r2   r3   r4   <module>r:     sd    #     = P * & G > > j j$ $Nj3 j3Z-X -X`S* S*r3   