
    ^j                        d dl Z d dlZd dlZd dlZd dlmZ d dlmZmZ d dl	m
Z
mZ d dlmZ d dlmZ 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mZ d
dlmZ ddlmZ ddlmZ ddl m!Z! ddl"m#Z# ddl$m%Z%m&Z& ddl'm(Z(m)Z) ddl*m+Z+ ddl,m-Z- ddl.m/Z/m0Z0m1Z1m2Z2 ddl3m4Z4m5Z5m6Z6 ddl7m8Z8m9Z9 	  G d dejt                        Z; G d d      Z< G d d       Z= G d! d"      Z> G d# d$      Z? G d% d&      Z@y)'    N)abstractmethod)Callable	Generator)contextmanagernullcontext)perf_counter)Any)nn)tqdm)logging_redirect_tqdm   )PretrainedConfig)ContinuousBatchingConfigGenerationConfig)logging   )LogitsProcessorList   )PagedAttentionCache)%ContinuousBatchingLogitsProcessorList)DistributedHelper)"resolve_continuous_batching_config%update_cb_config_after_cache_creation)ContinuousBatchingAsyncIOsContinuousBatchingIOs)ModelRunner)OffloadingManager)GenerationOutputRequestStateRequestStatuslogger)SCHEDULER_MAPPINGFIFOScheduler	Scheduler)WorkloadHintsdrain_queuec                       e Zd ZU eed<   ej                  ed<   ej                  ed<   ede	ddfd       Z
ededefd	       Zy)
ProtoPretrainedModelconfigdtypedeviceattn_implementationreturnNc                      y N )selfr,   s     /var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/generation/continuous_batching/continuous_api.pyset_attn_implementationz,ProtoPretrainedModel.set_attn_implementationI           generation_configc                      y r/   r0   )r1   r6   s     r2   _get_logits_processorz*ProtoPretrainedModel._get_logits_processorM   r4   r5   )__name__
__module____qualname__r   __annotations__torchr*   r+   r   strr3   r   r   r8   r0   r5   r2   r(   r(   D   s`    ;;LL3 4   7G L_  r5   r(   c                   >    e Zd ZdZd	dZdeddfdZdee   ddfdZy)
OutputRoutera  Dedicated object for routing generation outputs to the right destination.

    When an async handler is registered for a request, the output is forwarded
    to that handler via ``call_soon_threadsafe``. Otherwise the output is placed
    on the shared ``output_queue``.
    r-   Nc                 v    t        j                         | _        i | _        t	        j
                         | _        y r/   )queueQueueoutput_queueresult_handlers	threadingLock_lockr1   s    r2   __init__zOutputRouter.__init__Z   s&    !KKMVX^^%
r5   outputc                     | j                   5  | j                  j                  |j                        }ddd       |\  }}|j	                  ||       y| j
                  j                  |       y# 1 sw Y   ?xY w)zDRoute a single output to its registered handler or the output_queue.N)rH   rE   get
request_idcall_soon_threadsaferD   put)r1   rK   entrycallbackloops        r2   deliverzOutputRouter.deliver_   sq    ZZ 	@((,,V->->?E	@"NHd%%h7!!&)	@ 	@s   &A11A:outputsc                 L   g }d}| j                   5  |D ]]  }| j                  j                  |j                        }||\  }}|j	                  ||f       C| j
                  j                  |       _ 	 ddd       |r||fd}|j                  |       yyy# 1 sw Y   &xY w)zRoute a batch of outputs, using a single ``call_soon_threadsafe`` to minimize cross-thread overhead.

        Outputs without a registered handler fall back to the shared ``output_queue``.
        Nc                 (    | D ]  \  }} ||        y r/   r0   )batchcbouts      r2   
_run_batchz.OutputRouter.deliver_batch.<locals>._run_batchz   s    $ GBsGr5   )rH   rE   rM   rN   appendrD   rP   rO   )r1   rU   	callbacksrS   rK   rQ   rR   r[   s           r2   deliver_batchzOutputRouter.deliver_batchi   s    
 >@	ZZ 	2! 2,,001B1BC$%*NHd$$h%78%%))&12	2 )!*  %%j1 *9	2 	2s   A#BB#r-   N)	r9   r:   r;   __doc__rJ   r   rT   listr^   r0   r5   r2   r@   r@   R   s9    &
*. *4 *2T*:%; 2 2r5   r@   c                       e Zd ZdZdZdZdZdZddZdd	Z	d
e
de
ddfdZddZde
ddfdZede
fd       Zede
fd       Zy)BackgroundThreadStatuszTracks the status of the background thread locally and in its TP group. The status is an int that can only
    increase, representing how soon the thread should stop.r   r   r   r   r-   Nc                 z    t        j                         | _        | j                  | _        | j                  | _        y r/   )rF   rG   _local_status_lock	DONT_STOP_local_status
_tp_statusrI   s    r2   rJ   zBackgroundThreadStatus.__init__   s(    "+.."2!^^..r5   c                     | j                   | _        | j                  5  | j                   | _        ddd       y# 1 sw Y   yxY w)zClear the local and TP statuses. This method should ONLY be called by the main thread itself BEFORE starting
        the background thread.N)rf   rh   re   rg   rI   s    r2   clearzBackgroundThreadStatus.clear   s9     ..$$ 	0!%D	0 	0 	0s	   9Astatusglobal_rankc                 8   || j                   | j                  fvrt        d| d|       | j                  5  t	        || j
                  | j                        | _        ddd       t        j                  d| d|d| j
                         y# 1 sw Y   2xY w)zRequest the background thread to stop. This does not take effect immediately, only after the TP group has
        communicated.zInvalid stop status z from rank NzRank z3 requested background thread to stop with status = z. Now self._local_status = )	FLUSH_AND_STOP	HARD_STOP
ValueErrorre   maxrg   rh   r!   info)r1   rk   rl   s      r2   request_stopz#BackgroundThreadStatus.request_stop   s     $--t~~>>3F8;{mTUU$$ 	R!$VT-?-?!QD	RK= T6+Uq\`\n\n[rs	
	R 	Rs   'BBc                 h    | j                   5  | j                  | _        ddd       y# 1 sw Y   yxY w)zzMark the background thread as stopped. This should be called by the main thread when the generation loop
        finishes.N)re   STOPPEDrg   rI   s    r2   mark_as_stoppedz&BackgroundThreadStatus.mark_as_stopped   s.     $$ 	.!%D	. 	. 	.s   (1	tp_statusc                     || j                   k  rt        d|d| j                         || _         | j                  5  t        | j                  |      | _        ddd       y# 1 sw Y   yxY w)z8Update the local and TP statuses with the new TP status.z1TP communicated a lower stop status: tp_status = z, self._tp_status = N)rh   rp   re   rq   rg   )r1   rw   s     r2   update_with_tp_statusz,BackgroundThreadStatus.update_with_tp_status   sn    t&QYNRgUYUdUdThijj#$$ 	D!$T%7%7!CD	D 	D 	Ds   A##A,c                     | j                   S )zVThe locally requested status, possibly ahead of the value agreed upon by the TP group.)rg   rI   s    r2   local_statusz#BackgroundThreadStatus.local_status   s     !!!r5   c                     | j                   S )zKThe status last agreed upon by the TP group through a MAX-reduce operation.)rh   rI   s    r2   rw   z BackgroundThreadStatus.tp_status   s     r5   r_   )r9   r:   r;   r`   rf   rn   ro   ru   rJ   rj   intrs   rv   ry   propertyr{   rw   r0   r5   r2   rc   rc      s    ? INIG)
0	
3 	
S 	
T 	
.Ds Dt D "c " " 3  r5   rc   c                      e Zd ZU eez  ed<   eed<   dedede	de
dedej                  d	z  d
ej                  d	z  dededej"                  dej$                  dededd	fdZdefdZd!dZd!dZdefdZdededd	fdZdefdZd!dZdefdZ d Z!dedd	fdZ" ejF                         de$jJ                  dd	fd       Z& ejF                         de$jJ                  dd	fd        Z'y	)"ContinuousBatchProcessorinputs_and_outputs	schedulercacher)   r6   continuous_batching_configlogit_processorinput_queueNcancel_queueoutput_routerbackground_thread_statusmodel_devicemodel_dtypedistributed_helperr-   c                    || _         || _        || _        || _        || _        || _        || _        |	| _        |
| _        || _	        || _
        || _        t        |dd      | _        |j                  | _        | j                  j                  |j                   |
       t        |dd      dn|j"                  | _        |j$                  | _        ||||
|| j                  d}| j                  j&                  | _        | j&                  rt)        d	i || _        nt-        d	i || _        t/        |||j0                  |j2                  | j*                  j4                  | j                        | _        t9        | j                  | j                  | j                   | j*                  | j                  | j                        | _        y)
a)  Initialize the continuous batch processor.

        Args:
            cache: A [`PagedAttentionCache`] object
            config: The model configuration
            generation_config: The generation configuration
            continuous_batching_config: The continuous batching configuration
            logit_processor: The [`ContinuousBatchingLogitsProcessorList`] object used to process the logits.
            input_queue: Queue for incoming requests. Is None if this process is not a TP driver.
            cancel_queue: Queue for cancellation request_ids. Is None if this process is not a TP driver.
            output_router: An [`OutputRouter`] object that routes outputs to handlers or the output queue.
            background_thread_status: A [`BackgroundThreadStatus`] object to track the background thread status.
            model_device: Device for model inputs/outputs
            model_dtype: Data type for model inputs/outputs
            scheduler: The [`Scheduler`] to use
            distributed_helper: The [`DistributedHelper`] to use
        	do_sampleTsliding_windowNr   )r   r)   r   r+   r   r   )r   r   cpu_offload_space_gibsafety_thresholdcompute_streamr   )r   	cb_configr   r   r   return_logprobsr0   )r   r)   r   r   r   r   r   r   r   r   r   r   getattrr   r   set_tp_seedseedr   max_batch_tokensuse_async_batchingr   r   r   r   cpu_offload_space"cpu_offload_space_safety_thresholdr   offloading_managerr   model_runner)r1   r   r)   r6   r   r   r   r   r   r   r   r   r   r   	io_kwargss                  r2   rJ   z!ContinuousBatchProcessor.__init__   s   B 
3.&(*(@%(&""4 !!2KF9II 	++,F,K,K\Z $+63CT#J#RaX^XmXm % 6 6 *D"&#33
	 #'.."C"C""&@&M9&MD#&;&Hi&HD# #4"<"N"N7ZZ22AA#66#
 ( 00nn**#66nn 00
r5   c                     d| j                    d| j                  j                   d| j                  j                   d| j                  j                         j                         z   S )Nz%ContinuousBatchProcessor(input_queue=z, active_requests=z, waiting_requests=))r   r   active_requestswaiting_requestsr   get_model_kwargs__repr__rI   s    r2   r   z!ContinuousBatchProcessor.__repr__  sj    3D4D4D3E F#~~==>>QRVR`R`RqRqQrrsu%%668AACD	
r5   c                     d | _         t        j                          t        j                  j                         rt        j                  j                          y y r/   )r   gccollectr=   cudais_availableempty_cacherI   s    r2   __del__z ContinuousBatchProcessor.__del__%  s8    "&


::""$JJ""$ %r5   c                     | j                   j                          | j                  j                          | j                  j                          | j                  j                          y)z4Reset the batch processor for a new generation loop.N)r   resetr   r   r   free_all_requestsrI   s    r2   r   zContinuousBatchProcessor.reset+  sF    %%'%%'

$$&r5   c                 \   | j                   7| j                  +t        | j                         t        | j                        f}ng g f}t        |d         t        |d         z   }| j                  j
                  }| j                  j                  ||      \  }}| j                  j                  |       | j                  j                  t        j                  k(  ry|dk(  ry| j                  j                  |      \  }}|D ]C  }	 | j                  j                  |j                         | j                   j#                  |       E |D ]  }	| j                   j-                  |	        y# t$        $ r6}t'        j(                  d| d       | j+                  ||       Y d}~d}~ww xY w)zCommunicates with the TP group to get A. the new requests and cancellations from the TP driver, and B. an
        eventual stop signal from any process in the TP group. Returns True if the TP group is hard-stopping, False
        otherwiseNr   r   TFzError processing new request: exc_info)r   r   r&   lenr   r{   r   tp_all_reduce_statery   rw   rc   ro   tp_broadcast_object_from_rank_0r   check_kwargslogit_processor_kwargsr   add_waiting_request	Exceptionr!   error_handle_request_errorset_request_cancellation)
r1   payloadpayload_sizelocal_requested_statusrw   
new_statescancellationsstateerN   s
             r2   _update_tp_group_statez/ContinuousBatchProcessor._update_tp_group_state2  s   
 'D,=,=,I"4#3#34k$BSBS6TUG2hG71:WQZ8 "&!>!>!K!K"&"9"9"M"Ml\r"si%%;;IF ((226L6V6VV1$($;$;$[$[\c$d!
M   	5E5$$11%2N2NO2259	5 ( 	@JNN33J?	@  5=aSADQ**1e445s   A E,,	F+5,F&&F+r   r   c                 8   t         j                  |_        t        |      |_        t        |j                  t              r+| j                  j                  |j                        |_	        ng |_	        | j                  j                  |j                                y)z(Handle general request processing error.N)r    FAILEDrk   r>   r   
isinstancerN   r   !get_active_request_static_outputsgenerated_tokensr   rT   to_generation_output)r1   r   r   s      r2   r   z.ContinuousBatchProcessor._handle_request_errorY  so    $++%j e&&,%)^^%U%UV[VfVf%gE"%'E"""5#=#=#?@r5   c                    | j                         }|ry| j                  j                         }|D ]  }| j                  j	                  |        | j                  j                         sy| j                  j                  | j                  | j                  j                        \  }}}}|j| j                  j                         dk(  rt        d      | j                  j                  | j                  | j                  j                        \  }}}}|j|sy| j                  j                  r| j                  j                          | j                  j                  |       t        j                  t         j"                        rt        j$                  dt'        |       dt'        | j                  j(                         dt'        | j                  j*                         d| d| d	| j                  j-                                 | j.                  j1                  |||      \  }}| j2                  j5                  || j6                  |||| j.                  j8                  
       y)zPrepare tensors and metadata for the next model forward pass. Returns True if there are requests to process,
        False otherwise.Fr   z>No requests can be scheduled and no requests can be offloaded.zScheduled: z, Waiting: z
, Active: z	. cum Q: z
. cum KV: z, free blocks: )requests_in_batchlogits_processorsuse_decode_fast_pathnum_q_tokensmax_kv_readuse_paddingT)r   r   clear_cancelled_requestsr   free_request_cpu_cachehas_pending_requestsschedule_batchr   r   	num_pagesoffload_requestsRuntimeErrorstarved_requestsrestore_scheduled_requestsr!   isEnabledForr   DEBUGdebugr   r   r   get_num_free_blocksr   maybe_pad_inputsr   prepare_batch_tensorsr   
pad_inputs)r1   hard_stoppingcancelled_statesr   r   r   r   r   s           r2   prepare_next_batchz+ContinuousBatchProcessor.prepare_next_batchf  s3   
 335>>BBD% 	BE##::5A	B~~224 NR^^MjMj!!4::#7#7N
J/{  '&&779Q>"#cddQUQ_Q_QnQn%%tzz';';RN3\;  ' !>>**##446 	::;LM w}}-LLc"345[T^^EdEdAe@f gt~~==>?y W&-tzz7U7U7W6XZ %)$5$5$F$F|U`bv$w!k55/"22!5%#))44 	6 	
 r5   c                 X   | j                   j                         \  }}}d}g }|D ]  }|j                  }|j                  t        j
                  t        j                  fv rN| j                  r|j                  r|dz  }Zt        d|j                  j                   d|j                   d      |j                  r|j                         dk(  rt        j                  |_        ||   }|||   nd}	|dz  }|j                  ||	      }
| j                  j!                  ||j"                         |
r6| j$                  j'                  |j                         d| j$                  _        |j*                  s|j                  t        j
                  k(  sl|j-                  |j/                                |j                  t        j0                  k(  s| j                  j!                  ||j"                          |r| j2                  j5                  |       g g }}| j$                  j6                  r}| j$                  j6                  j9                         }|j:                  }d|_        t=        |      D cg c]  }|j                   d|  }}t?        || j                  jA                  |j                              }||z
  }t=        |      D ]D  }|j9                         }|jC                         }||_        | j$                  jE                  |       F |dk(  r|D ]*  }|jG                  |      | j$                  jH                  |<   , | j                  jK                  |j                  |      \  }}|jM                  |       |jM                  |       | j$                  j6                  r}|ri| j                   jN                  }|tP        jR                  jU                  |      n	tW               }|5  | j                  jY                  ||       ddd       yyc c}w # 1 sw Y   yxY w)	z0Update request states based on generated tokens.r   r   zTried to update z	 request z in sync mode.NFz__child#)-r   prepare_batch_updater   rk   r    FINISHEDPENDINGr   has_new_tokenr   namerN   generated_lenDECODINGupdate_and_check_completionr   !mark_shareable_blocks_as_completecomplete_blocksr   finish_requestblock_new_requests	streamingr\   r   
PREFILLINGr   r^   _requests_to_forkpopnum_childrenrangemincompute_max_num_forks!create_equivalent_initial_requestr   forkr   fork_requestextendr   r=   r   streamr   
copy_cache)r1   r   
new_tokenslogprobscurrent_logits_indexpending_outputsfuture_stater   tokenlogprobis_finishedcopy_sourcecopy_destinationstate_to_forkr   inew_request_idsnum_to_forknum_to_schedule_new_request_idchild_statecopy_srccopy_dstr   maybe_streams                             r2   update_batchz%ContinuousBatchProcessor.update_batch  s   262I2I2^2^2`/:x - 	bL &&E|| 6 68M8MNN**#11,1,"%5ell6G6G5H	RWRbRbQccq#rss))&&(A-#0#9#9EL"#78<D<P(#78VZ$)$ $??wO

<<ULD`D`aNN11%2B2BC8=DNN5??ellm6L6L&L#**5+E+E+GH!9!99

<<ULD`D`a?	bB ,,_= )+B%nn.. NN<<@@BM(55L)*M&QVWcQdeA-":":!;8A3GeOelDJJ,L,L]MeMe,fgK*[8O?+ @!0!4!4!6+MMO)7&22;?	@ a"1 dANASASTbAc..~>d "&!8!89Q9QSb!cHhx(##H-/ nn..4  "44CCN@N@Z5::,,^<`k`mL E

%%k3CDE E + f4E Es   6P4P  P)c                 6    | j                   j                         S )z2Check if there are any active or waiting requests.)r   r   rI   s    r2   r   z-ContinuousBatchProcessor.has_pending_requests  s    ~~2244r5   c                     | j                   j                         d   }|D ]M  }| j                  ||j                         | j                  j                  |j                  j                         O y)z&Handle errors during batch processing.r   N)r   r   r   r   r   r   rN   )r1   r   failed_future_statesr  s       r2   handle_batch_errorz+ContinuousBatchProcessor.handle_batch_error  sa    #66KKMaP0 	IL&&ul.@.@ANN)),*<*<*G*GH	Ir5   c                 (   t        | j                  j                  j                               }|D ]9  }| j	                  ||       | j                  j                  |j                         ; | j                  j                          t        | j                  j                  j                               D ]9  }| j                  j                  j                  |      }| j	                  ||       ; | j                  j                  j                          y)z.Fail all active requests with the given error.N)ra   r   r   valuesr   r   rN   r   free_all_waiting_cpu_cachesr   keysr   waiting_requests_orderrj   )r1   r   requestsr   req_ids        r2   fail_all_requestsz*ContinuousBatchProcessor.fail_all_requests  s     66==?@ 	<E&&ue4NN))%*:*:;	<
 	;;=4>>::??AB 	5FNN3377?E&&ue4	5
 	--335r5   modelc                     | j                   j                  | j                  j                        }| j                  j	                  ||       | j                   j                          y)z!Perform a single generation step.)r   N)r   r   r   r   compute_batchretrieve_device_outputs)r1   r!  
batch_datas      r2   _generation_stepz)ContinuousBatchProcessor._generation_step  sU    
 ,,==$J[J[JfJf=g
 	''z: 	779r5   c                 :    | j                   j                  |       y)aG  Pre-capture CUDA graphs (or trigger compile warmup) for varlen and decode paths. In async mode, both IO
        pairs are warmed up since each has its own graph buffer and static tensors. The varlen path is warmed up at
        the largest possible `(q, kv)` sizes so subsequent captures fit inside it without growing the pool.N)r   warmupr1   r!  s     r2   r(  zContinuousBatchProcessor.warmup  s    
 	  'r5   r_   )(r9   r:   r;   r   r   r<   r$   r   r   r   r   r   rB   rC   r@   rc   r=   r+   r*   r   rJ   r>   r   r   r   boolr   r   r   r   r   r  r   r  r   no_gradr
   Moduler&  r(  r0   r5   r2   r   r      s   -0JJJ\
"\
 !\
 ,	\

 %=\
 ?\
 [[4'\
 kkD(\
 $\
 #9\
 ll\
 [[\
 \
 .\
 
\
|
# 
%'% %NA9 A\ Ad A>D >@KEZ5d 5I6y 6T 6" U]]_:bii :D : : U]]_(BII ($ ( (r5   r   c                   0   e Zd ZdZ	 d,dededededz  ddf
dZdeddfd	Z	d-d
Z
defdZd-dZ	 	 	 	 d.dededz  dededdf
dZd,dededz  ddfdZd-dZ	 	 	 	 	 d/dee   dedz  dedz  dededeee   z  dz  dededz  fdZ	 	 	 d0deee      dedz  dedededee   fdZdeddfdZd1dedz  dedz  dedz  fd Zd! Zdedee   fd"Zded#eddfd$Z e jB                         d-d%       Z"d-d&Z#de$fd'Z%d(e&d)e$dz  ddfd*Z'd(e&d)e$dz  ddfd+Z(y)2ContinuousBatchingManagera  Manager for handling continuous batching of generation requests. It provides a user interface for submitting
    generation requests, retrieving results, and managing the background generation thread. This class should not be
    created directly, but through one of the following entry points (all methods of the `ContinuousMixin` mixin):
    - `init_continuous_batching`
    - `continuous_batching_context_manager`
    - `generate_batch`
    Nr!  r6   r   workload_hintsr-   c                    t        j                  |j                        | _        t        j                         | _        d| _        t        j                         | _        t        j                         | _
        t               | _        t               | _        d| _        d| _        d| _        d| _        d| _        | j)                  |       |j+                         | _        || _        t1        |dd      }||nd| _        t5        t1        | j,                  dd      |j6                        | _        | j8                  j:                  | _        |j<                  r| j8                  j?                          tA        | j,                  jC                  |      |jD                  |jF                  	      | _$        tK        | j,                  jL                  ||| jH                  jN                  
      | _(        | jP                  jR                  | _*        y)ay  Initialize the continuous batching manager.

        Args:
            model: The language model for generation
            generation_config: Configuration for generation parameters
            continuous_batching_config: Configuration for continuous batching parameters
            workload_hints: Workload hints for the continuous batching initialization (optional)
        )maxsizer   NFnum_return_sequencesr   _device_mesh)device_meshcpu_group_timeout)logits_processorper_request_processorsdrop_unsupported_processors)r)   r   r/  has_logit_processors)+rB   rC   max_queue_sizer   r   _request_counterrF   rG   _request_lockEvent_has_new_requestsrc   r   r@   r   batch_processor_generation_threadfatal_error	warmed_up_original_attn_implswitch_to_paged_attnevalr!  r6   r   r2  r   r5  r   is_tp_driverdisable_nccl_graph_mixingmaybe_warn_nccl_graph_mixingr   r8   r7  r8  r   r   r)   do_processingr   allow_block_sharing_use_prefix_sharing)r1   r!  r6   r   r/  r2  s         r2   rJ   z"ContinuousBatchingManager.__init__0  s     !;;/I/X/XY.3kkm !&^^-!*!2 )?(@%)^@D"& .2 $( !!%(ZZ\
 "3&'8:PRVW<P<\$8bc! #4

NDA8JJ#
 !33@@%??##@@B  E!ZZ==>OP#=#T#T(B(^(^ 
 +M::$$0)!%!5!5!C!C	+
' $(#B#B#V#V r5   c                     d|j                   j                  vrD|j                   j                  | _        |j                  d|j                   j                          yy)zhSwitch to the paged version of the attention implementation. If the attn is already paged, does nothing.zpaged|N)r)   _attn_implementationrC  r3   r)  s     r2   rD  z.ContinuousBatchingManager.switch_to_paged_attnu  sK    5<<<<<',||'H'HD$))F5<<3T3T2U*VW =r5   c                     | j                   | j                         | _         | j                   j                  | j                         d| _        y)zPre-capture CUDA graphs for varlen and decode paths by running dummy batches. Initializes the batch
        processor if not already done.NT)r?  _create_batch_processorr(  r!  rB  rI   s    r2   r(  z ContinuousBatchingManager.warmup{  s@     '#'#?#?#AD ##DJJ/r5   c                 V    | j                   duxr | j                   j                         S )zUReturns True if the background generation thread has been started and is still alive.N)r@  is_aliverI   s    r2   
is_runningz$ContinuousBatchingManager.is_running  s'    &&d2Yt7N7N7W7W7YYr5   c                    | j                         rt        j                  d       y| j                  j	                          d| _        t        j                  | j                        | _	        | j                  j                          y)z'Start the background generation thread.z"Manager thread is already running.N)target)rR  r!   warningr   rj   rA  rF   Thread_run_generation_loopr@  startrI   s    r2   rX  zContinuousBatchingManager.start  sa    ??NN?@%%++-"+"2"2$:S:S"T%%'r5   blocktimeoutkeep_for_next_session	hard_stopc                    | j                   t        j                  d       | j                  d}|r|dz  }t        j                  |       yt	               }|rt
        j                  nt
        j                  }| j                  j                  || j                  j                         |r| j                  ||       |sd| _         n&t        j                  d       | | j                  _        | j                   ,| j                  j#                  | j                          d| _        t%        j&                          t(        j*                  j-                         rt(        j*                  j/                          yy)a  Stop the background generation thread. If the `block` flag is set to True, then this method waits for the
        thread to stop for a maximum time of `timeout` seconds (None means no timeout). If the `keep_for_next_session`
        flag is set to True, then the manager is cached on the model for future use. If the `hard_stop` flag is set,
        the background generation thread will be stopped immediately and pending requests will be failed.Nz%
Batch processor was not initialized.zManager not started.z? Hence the unstarted manager will not be kept for next session.z:Continuous batching manager will be kept for next session.)r?  r!   rU  r@  r   rc   ro   rn   r   rs   r   rl   joinrr   r!  #_cached_continuous_batching_managerrC  r3   r   r   r=   r   r   r   )r1   rY  rZ  r[  r\  msgstop_trigger_timestop_statuss           r2   stopzContinuousBatchingManager.stop  s(    'NNCD ""*(C$XXNN3 )N:C,66I_InIn%%22;@W@W@c@cdII'1 %#'D  KKTU=ADJJ: ##/JJ..t/G/GH'+D$ 	

::""$JJ""$ %r5   ra  c                    | j                   y| j                   j                  |       | j                   j                         rt        j                  d| d       yt               }t        j                  d||z
  dd       d| _         y)zeWait for the background thread to finish. Wait can be capped using the timeout argument (in seconds).NrZ  z3Generation thread did not exit after join timeout (z).z+Background generation thread stopped after .2fs.)r@  r^  rQ  r!   rU  r   rr   )r1   ra  rZ  ends       r2   r^  zContinuousBatchingManager.join  s     ""* 	$$W$5""++-NNPQXPYY[\].CKKEcL]F]^aEbbdef&*D#r5   c                 ~    | j                         r| j                  dd       | j                  j                          y)zTerminate the manager and release distributed resources. Safe to call multiple times. After calling this,
        the manager cannot be restarted.TF)rY  r[  N)rR  rc  r   destroy_cpu_comm_grouprI   s    r2   destroyz!ContinuousBatchingManager.destroy  s0     ??IIDI>668r5   	input_idsrN   max_new_tokensr   record_timestampseos_token_idr   c           
         | j                   sy| j                  j                  t        j                  k\  r0|dd  dd dz   |dd  dd z   }t        j                  d| d       y|9| j                  5  d	| j                   }| xj                  dz  c_        ddd       || j                  j                  n|}|| j                  j                  n|}t        |t        |      | j                  dz
  |||||
      }	| j                  j!                  |	dd       | j"                  j%                          |S # 1 sw Y   xY w)a  Add a new generation request to the queue. If the process is not a TP driver, this is a no-op.

        Args:
            input_ids: Input token IDs to use as prompt
            request_id: Optional custom request ID (auto-generated if None)
            max_new_tokens: Maximum number of new tokens to generate
            streaming: Whether to stream tokens as they're generated
            record_timestamps: Whether to record timestamps for each generated token
            eos_token_id: End-of-sequence token ID(s)
            logit_processor_kwargs: Keyword arguments for the logits processor.

        Returns:
            str | None: The request ID if the process is a TP driver, None otherwise.
        Nr   z, ..., r   z0Background thread is stopping. Request with ids z will be dropped.req_)rN   initial_tokensr   rn  rm  ro  r   r   T
   rY  rZ  )rF  r   r{   rc   rn   r!   rU  r<  r;  r6   rm  ro  r   ra   r2  r   rP   r>  set)
r1   rl  rN   rm  r   rn  ro  r   previewr   s
             r2   add_requestz%ContinuousBatchingManager.add_request  s[   2   ((559O9^9^^"2A"-	9y~>NPQPR<SSGNNMgYVghi## +#D$9$9#:;
%%*%+ CQBX//>>^l>J>Rt--::Xd !	?22Q6/)%#9	
 	U$;""$++ +s   3%D77E inputsc                    t        |      }| j                  5  t        | j                  | j                  |z         D cg c]  }d| 	 }}| xj                  |z  c_        ddd       t	        t        |            }	| j                  rt        |	d d      }	| j                  j                  }
|
 | j                  j                  j                  n|
}
|
dn|
}
|	D ]  \  }} | j                  d||||||
d|   |S c c}w # 1 sw Y   xY w)	zgUtility function to batch `add_request` and return their IDs. Check its documentation for more details.rs  Nc                     | d   S )Nr   r0   )xs    r2   <lambda>z8ContinuousBatchingManager.add_requests.<locals>.<lambda>'  s
    !A$ r5   T)keyreverserq  )rl  rN   rm  r   rn  ro  r0   )r   r<  r   r;  ra   ziprK  sortedr6   ro  r!  r)   ry  )r1   rz  rm  r   rn  r   num_requestsr
  request_idsids_and_inputsro  rN   rl  s                r2   add_requestsz&ContinuousBatchingManager.add_requests  s&    6{ 	2/4T5J5JDLaLadpLp/qr!T!:rKr!!\1!	2 c+v67###NPTUN--::9E9Mtzz((55S_)1r|%3 		!J	D #%-#"3) )		 + s	2 	2s   &DC>
D>DDc                     | j                   r6| j                  j                  |       | j                  j	                          yy)zCancel a request by its ID. If this called from a process that is not a TP driver, it's a no-op: only TP
        driver processes interact with the manager.N)rF  r   rP   r>  rw  )r1   rN   s     r2   cancel_requestz(ContinuousBatchingManager.cancel_request9  s8     !!*-""&&( r5   c                 X   | j                   %| j                  j                  j                         ry	 | j                  j                  j	                  d|      }|5|j
                  |k7  r&| j                  j                  j                  |       y|S # t        j                  $ r Y yw xY w)zRetrieve one result from the output queue. If an ID is provided, returns the first matching request. If a
        timeout is provided, returns None after the timeout (in seconds).NTrv  )	r@  r   rD   emptyrM   rN   rP   rB   Empty)r1   rN   rZ  results       r2   
get_resultz$ContinuousBatchingManager.get_resultB  s     ""*t/A/A/N/N/T/T/V	''4488tW8UF%&*;*;z*I""//33F;M{{ 		s   AB B B)(B)c              #      K   | j                   \| j                   j                         rA| j                  d      }|| | j                   | j                   j                         r?yyyyw)z.Iterate over results as they become available.N皙?re  )r@  rQ  r  )r1   r  s     r2   __iter__z"ContinuousBatchingManager.__iter__P  sf     %%1d6M6M6V6V6X__S_1F! %%1d6M6M6V6V6X16X1s   A%A,(A,c              #      K   | j                   n| j                   j                         rS| j                  |d      }|| |j                         ry| j                   | j                   j                         rQyyyyw)zIterate over results matching a specific request id (blocking).

        Uses the shared output queue with requeue. For high-concurrency serving,
        use :meth:`register_result_handler` instead.
        Nr  )rN   rZ  )r@  rQ  r  r  )r1   rN   r  s      r2   request_id_iterz)ContinuousBatchingManager.request_id_iterW  sy      %%1d6M6M6V6V6X__
C_HF!%%' %%1d6M6M6V6V6X16X1s   A7A>:A>rR   c                      t        j                         } fd} j                  j                  5  ||f j                  j                  <   ddd       y# 1 sw Y   yxY w)a+  Register a callback for result delivery (streaming or non-streaming).

        The callback is invoked on the event loop via ``call_soon_threadsafe`` each time a result is produced for this
        request. For streaming requests, this happens on every token; for non-streaming, only on completion. The handler
        is automatically cleaned up when the request finishes.

        Args:
            request_id (`str`): The request ID to receive outputs for.
            callback (`callable`): Called with a ``GenerationOutput`` for each result.
        c                      |        | j                         rFj                  j                  5  j                  j                  j	                  d        d d d        y y # 1 sw Y   y xY wr/   )r  r   rH   rE   r   )r  rR   rN   r1   s    r2   _auto_cleanupzHContinuousBatchingManager.register_result_handler.<locals>._auto_cleanupq  sf    V!!#''-- M&&66:::tLM M $M Ms   'A!!A*N)asyncioget_running_loopr   rH   rE   )r1   rN   rR   rS   r  s   ```  r2   register_result_handlerz1ContinuousBatchingManager.register_result_handlerd  s^     '')	M %% 	S>KT=RD..z:	S 	S 	Ss   AA#c                    d}	 | j                         }|| _        d| _        |j                  r@|j	                         st        d      | j                          | xj                  dz  c_        	 |j	                         }|r6| j                          |j                          | xj                  dz  c_        n| j                  j                  t        j                  k(  rno| j                  j                  t        j                  k(  r|j                         sn7| j                  j                  d       | j                  j!                          t#        |j$                  t&              r8d|j$                  j(                  z
  |j$                  _        |j                          t        d| j                  j                        }| j+                  ||       | j                  j5                          t/        j6                  d       y# t,        $ r6}t/        j0                  d	| d
       | j3                  ||       Y d}~jd}~ww xY w# | j                  j5                          t/        j6                  d       w xY w)z6Main processing loop running in the background thread.Nr   z$Failed to bootstrap the first batch.r   Tr  re  zdGeneration loop finished before this request completed w/ self.background_thread_status.tp_status = zError in generation loop: r   zCGeneration loop finished and background thread exited successfully.)rO  r?  current_batchr   r   r   r&  r  r   rw   rc   ro   rn   r   r>  waitrj   r   r   r   current_pair_fail_all_remaining_requestsr   r!   r   _handle_critical_errorrv   rr   )r1   r?  requests_availabler   r   s        r2   rW  z.ContinuousBatchingManager._run_generation_loop|  s    8	_"::<O#2D !"D 11&99;&'MNN%%'""a'" %4%G%G%I" &))+#002&&!+& 22<<@V@`@`` 11;;?U?d?dd+@@B **///<**002- 4 /<<>XYBCoFhFhFuFuBu22?,,. !wTMjMjMtMtLxyE --e_E ))99;KK]^  	<LL5aS9DI''?;;	< ))99;KK]^s*   GH 	I,H>9I >II 1I7c                 |    | j                   t        d      | j                   j                  | j                         y)z=Perform a single generation step. This is mostly cuda graphedNzNTried to perform a generation step before the batch processor was initialized.)r?  r   r&  r!  rI   s    r2   r&  z*ContinuousBatchingManager._generation_step  s2    'opp--djj9r5   c                    t        | dd      }t        |t              r|j                          |S t	        | j
                  j                  | j                  | j
                  j                  | j                  t        | j
                  di       | j
                  j                        }|j                  | _        t        | j                  |j                  |j                  | j                         |j                   dkD  rd| j                  _        | j                  j$                  }t'        j(                  |d      }|t+        j,                  d| d       t.        } ||| j                  j0                  | j                  j2                  	      }t        || j
                  j                  | j4                  | j                  | j6                  | j8                  r| j:                  nd| j8                  r| j<                  nd| j>                  | j@                  | j
                  j                  | j
                  j                  || j                  
      }|S )ziCreate a new batch processor. If an already initialized batch processor exists, it is reset and returned.r?  Ntp_plan)r)   r   r+   r   r  r*   )r   
num_blocksr   use_prefix_sharingr   zScheduler 'z ' not found. Defaulting to FIFO.)r   safety_marginmax_requests_per_batch)r   r)   r6   r   r   r   r   r   r   r   r   r   r   )!r   r   r   r   r   r!  r)   r   r+   r   r*   r  rK  r   r  r   num_sliding_attention_groupsmax_blocks_per_requestscheduler_typer"   rM   r!   rU  r#   r  r  r6   r   rF  r   r   r   r   )r1   r?  paged_attention_cacher  scheduler_clsr   s         r2   rO  z1ContinuousBatchingManager._create_batch_processor  s    "$(94@o'?@!!#"" !4::$$'+'F'F::$$#66DJJ	26**""!
 $9#K#K -55,772CC#77		
 !==AEFD++B 88GG)--ndC NN[(88XYZ)M!'99GG#'#B#B#Y#Y
	 3'::$$"44'+'F'F 00,0,=,=((4.2.?.?**T,,%)%B%B**

((#66
 r5   r   r?  c                    || _         | j                  j                  t        j                  | j
                  j                         | j
                  j                  dt        j                         | j                  ||       y)z:Handle critical errors that terminate the generation loop.)rk   rl   r   N)	rA  r   rs   rc   ro   r   rl   r   r  )r1   r   r?  s      r2   r  z0ContinuousBatchingManager._handle_critical_error   sk     !%%22)33AXAXAdAd 	3 	

 	33A7M7W7WX))%Ar5   c                     	 	 | j                   j                         }||j                  ||       /# t        j                  $ r Y nw xY w||j                  |       yy)zCFail all remaining requests in the input queue and active requests.N)r   
get_nowaitr   rB   r  r   )r1   r   r?  req_datas       r2   r  z6ContinuousBatchingManager._fail_all_remaining_requests  sl    	++668".#99%J  {{ 		 &--e4 's   02 AAr/   r_   )TNFF)NNFFN)NFF)NN))r9   r:   r;   r`   r(   r   r   r%   rJ   rD  r(  r*  rR  rX  floatrc  r^  rk  ra   r}   r>   r	   ry  r  r  r   r  r  r   r  r   r  r=   r+  rW  r&  r   rO  r   r  r  r0   r5   r2   r.  r.  '  s    04CW#CW ,CW %=	CW
 &,CW 
CWJX*> X4 XZD Z(  $&+0%0% 0%  $	0%
 0% 
0%d+e +edl +d +9 "&%)"'/3797 $J7 d
	7
 7  7 DIo,7 #&7 
t7x &*"'!T#Y! d
! 	!
  ! #&! 
c!F) ) )S4Z  YilpYp # )<L2M S# S Sd S0 U]]_=_ =_~:<)A <|BI BH`cgHg Blp B5) 5NfimNm 5rv 5r5   r.  c                      e Zd ZU dZeed<    ej                         	 	 	 ddedz  dedz  de	dz  de
fd       ZddZe ej                         	 	 	 	 	 	 	 ddedz  d	ed
edz  dedz  dedede	dz  dee
   fd              Z ej                         	 	 	 	 	 	 ddeee      dedz  dedz  dededededeeef   fd       Zy)ContinuousMixina  Mixin class for models to add continuous batching capabilities. Continuous batching has three entry points:
    - `init_continuous_batching`, which is the actual entry point for continuous batching
    - `continuous_batching_context_manager`, which itself is a wrapper around `init_continuous_batching`
    - `generate_batch`, which is really a wrapper around `continuous_batching_context_manager`

    They are defined in this order. Any change made to any of those three entry points should be reflected in the other
    two.
    r6   Nr   r/  r-   c                    t        | d      rt        | d      rt        | d      st        d      t        | dd      }t        |t              r(t        j                  d       |j                  |        |S ||n| j                  }|t        d      |j                  t        j                  d	       d
|_
        |2t        t        |dd      t              r|j                  }n
t               }t	        | |||      S )a  Initialize a manager for continuous batching inference.

        Args:
            generation_config: An optional generation configuration, which may contain a CompileConfig object
            continuous_batching_config: An optional continuous batching configuration
            workload_hints: Optional WorkloadHints to help the continuous batching manager make better decisions for
                default values
        Returns:
            `ContinuousBatchingManager`: The manager instance to add requests and retrieve results.
        r)   r+   r*   z;Model must have 'config', 'device', and 'dtype' attributes.r_  NzCached continuous batching manager found: it will be re-used instead of creating a new one. If you want to create a new manager, you should call `destroy_cached_continuous_batching_manager` first.z8A GenerationConfig must be provided or set in the model.zE`eos_token_id` not set in GenerationConfig. Setting to -1 (disabled).rq  r   )r!  r6   r   r/  )hasattrAttributeErrorr   r   r.  r!   rr   rD  r6   rp   ro  rU  r   r   )r1   r6   r   r/  cached_manager
gen_configs         r2   init_continuous_batchingz(ContinuousMixin.init_continuous_batching)  s   $ tX&gdH.EWUY[bMc !^__ !'LdSn&?@KKu //5!! +<*G&TMcMc
WXX""*NNbc&(J# &-'*.JDQSkl-7-R-R*-E-G* )('A)	
 	
r5   c                 x    t        | dd      }t        |t              r|j                          t	        | d       yy)zFDestroy the cached continuous batching manager and free GPU resources.r_  N)r   r   r.  rk  delattr)r1   r  s     r2   *destroy_cached_continuous_batching_managerz:ContinuousMixin.destroy_cached_continuous_batching_manager`  s9     'LdSn&?@""$D?@ Ar5   rY  rZ  persistent_managerr(  c              #     K   | j                  |||      }|r`|j                  sTt        j                  d       t	               }	|j                          t        j                  dt	               |	z
  dd       |j                          	 | t        j                  d       |j                  |||       |s|j                          yy# t        j                  d       |j                  |||       |s|j                          w w xY ww)	a  A context manager to safely use the continuous batching manager. Arguments are similar to the ones of
        `init_continuous_batching`, except for:
            - block: whether to block the thread when stopping the manager. Default is True.
            - timeout: maximum time to wait for the thread to stop. Default is None (no timeout).
            - warmup: whether to pre-capture CUDA graphs at the largest sizes before running. Default is True.
        )r6   r   r/  z%Warming up for continuous batching...zWarming up completed in rf  rg  z!Continuous batching loop finished)rY  rZ  r[  N)
r  rB  r!   rU  r   r(  rX  r   rc  rk  )
r1   r6   rY  rZ  r   r  r(  r/  managerrX  s
             r2   #continuous_batching_context_managerz3ContinuousMixin.continuous_batching_context_managerg  s     $ ///'A) 0 

 '++NNBC NENNNN5lnu6LS5QQSTU	"M LL<=LLugM_L`%! & LL<=LLugM_L`%! &s   BD
C =D>D		Drz  rn  progress_barc           	         |si S t        j                         t        j                  k  rt        j                  d       d}|| j
                  n|}	|	j                  |	j                  nd}
t        |      |
z  }|j                  dd      }||	j                  n|}t        t        d |D              ||nd|      }|rt        j                  d	       | j                  ||d
d|||      }t        t         g      }t        || d| dd      }i }d}|5 }|5  |5 }	 |j                  |||      }||k  r|j!                  d      }|r8|j"                  }|j%                         rM|||<   |dz  }|j'                  d       n1|j)                         s!t        j*                  d       t-        d       n||k  rddd       ddd       ddd       i }g }D ],  }|j1                  |      }||||<   |j3                  |       . |rt        j*                  d| d       |S # t.        $ r$}t        j*                  d| d
       Y d}~d}~ww xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w)a-  Generate sequences for a batch of prompts using continuous batching.

        Args:
            inputs: List of input token sequences (prompts)
            generation_config: Optional generation configuration
            continuous_batching_config: Optional continuous batching configuration
            record_timestamps: If set to true, the requests will have a timestamp for each token generated
            progress_bar: If set to true, a progress bar will be displayed
            persistent_manager: whether to persist the manager after the generation is finished. Default is False.
            warmup: whether to pre-capture CUDA graphs before processing requests. Default is True.
        Returns:
            `dict[str, GenerationOutput]`: a dictionary of request ids to GenerationOutput objects
        z=Progress bar is disabled when logger level is less than DEBUGFNr   rm  c              3   2   K   | ]  }t        |        y wr/   )r   ).0rl  s     r2   	<genexpr>z1ContinuousMixin.generate_batch.<locals>.<genexpr>  s     !IY#i.!Is   r   )max_prompt_lengthmax_generated_lengthr  a,  Since you passed `persistent_manager=True`, the manager will be kept alive after the generation is finished. However, it was sized specifically for the requests passed in `generate_batch`. If you plan to reuse the manager for a very different workload, you might want to create a new manager instead.T   )r6   r   rY  rZ  r  r(  r/  zSolving z	 requestsrequest)totaldisabledescunit)rz  rm  rn  re  z*Generation thread terminated unexpectedly.zCReturning results of generate_batch despite unexpected termination.zError during batch generation: r   z	Requests z not found in results.)r!   getEffectiveLevelr   r   rU  r6   r2  r   r   rm  r%   rq   r  r   r   r  r  rN   r  updaterR  r   printr   rM   r\   )r1   rz  r6   r   rn  r  r  r(  kwargsgen_cfgr2  r  rm  r/  
manager_cm
logging_cmpbar_cmresultsfinished_countr  pbarr  r  r  r   reordered_resultsmissing_keyss                              r2   generate_batchzContinuousMixin.generate_batch  s   4 I ##%6NNZ[ L ->,E$((K\?F?[?[?gw;;mn6{%99  $4d;3A3I//~ '!!I&!II3A3MST%

 NNv ==/'A1) > 

 +F84
%%L>3	
  	S7J 	S 	S4S%22!.Te 3  %|3$///:F!'!2!2!--/.4GFO*a/N KKN$//1%QRcd %|3	S 	S 	S. ! 	,F[[(F!,2!&)##F+	, LL9\N2HIJ    S>qcBTRRS'	S 	S 	S 	S 	S 	Ssa   I,I IBH$:I I,$	I	-I	II	III  I)	%I,,I5)NNNr_   )NTNNFTN)NNFTFT)r9   r:   r;   r`   r   r<   r=   r+  r   r%   r.  r  r  r   r*  r  r   r  ra   r}   dictr>   r   r  r0   r5   r2   r  r    s    ('U]]_ 6:FJ/3	4
+d24
 %=t$C4
 &,	4

 
#4
 4
lA U]]_ 6: $FJ#(/3#"+d2#" #" 	#"
 %=t$C#" !#" #" &,#" 
,	-#"  #"L U]]_ 6:FJ"'!#(m!T#Ym! ,d2m! %=t$C	m!
  m! m! !m! m! 
c##	$m! m!r5   r  )Ar  r   rB   rF   abcr   collections.abcr   r   
contextlibr   r   timer   typingr	   r=   r
   r   tqdm.contrib.loggingr   configuration_utilsr   generation.configuration_utilsr   r   utils.loggingr   logits_processr   r   r   cb_logits_processorsr   distributedr   initializationr   r   input_outputsr   r   r   r   r   r   r  r   r   r    r!   r   r"   r#   r$   utilsr%   r&   r,  r(   r@   rc   r   r.  r  r0   r5   r2   <module>r     s     	    / 2      6 3 X $ 0 & G * e L % 1 K K B B -,299 ,2 ,2^7 7vg( g(Vs5 s5l`! `!r5   