
    qiL                         d dl Z d dlmZmZ d dlmZ ddlmZmZ ddl	m
Z
 ddlmZmZmZmZ  G d	 d
e      Z e        G d de             Z e        G d de             ZeedZy)    N)ABCabstractmethod)deque   )attach_tracertraced   )PagedAttentionCache)FutureRequestStateRequestStateRequestStatusloggerc                      e Zd ZdZddedefdZedefd       Z	e
deded	ee   d
z  fd       Zed	efd       Zeddeded	d
fd       Zeded	ee   fd       Zedefd       Zed        Zeded	efd       Zededed	efd       Zdedee   d	ee   fdZdedee   dedee   d	d
f
dZ	 d dee   dededee   ded	eee   ef   fdZdee   d	d
fdZy
)!	ScheduleraA  
    Abstract base class for scheduling requests in the continuous batch processor. Schedulers manage the lifecycle of
    requests from when they are added to the waiting queue to when they are scheduled for processing. Different
    schedulers implement different strategies for prioritizing and batching requests.
    cacheretain_cache_on_finishc                 $   i | _         i | _        t               | _        || _        || _        t        j                         | _        t               | _
        g | _        d| _        |j                  rd | _        y |j                  j                  | _        y )NF)active_requestswaiting_requestsr   waiting_requests_orderr   r   	threadingLock_cancellation_lockset_requests_to_cancel_requests_to_forkblock_new_requestsnum_full_attention_groupsconfigsliding_windowcache_budget_module)selfr   r   s      g/opt/pipecat/venv/lib/python3.12/site-packages/transformers/generation/continuous_batching/scheduler.py__init__zScheduler.__init__   sx    8:9;27'#
&<#"+.."2-0U 57"'+0+J+J4 PUP\P\PkPk     statec                    | j                   r|j                  | j                  v rn| j                  j                  |j                        }|j                  t        |j                        d |_        |j                  |_        |j                  |_        || j                  |j                  <   | j                  j                  |j                         y)z#Adds a request to the waiting list.N)r   
request_idr   poptokens_to_processleninitial_tokensallocated_blocksposition_offsetr   r   append)r"   r&   	old_states      r#   add_waiting_requestzScheduler.add_waiting_request,   s     &&5+;+;t?S?S+S,,001A1ABI&+&=&=I,,-/'E# &/%?%?E"$-$=$=E!27e../##**5+;+;<r%   token_budgetcache_budgetreturnNc                      y)a  Schedules requests for the next batch based on available token and cache budgets. This method selects which
        requests should be processed in the current batch, considering the budgets and the scheduler's prioritization
        rules. The token_budget is the maximum number of tokens that can be processed in a batch, and the cache_budget
        is the maximum number of KV cache entries that can be read in a batch.N )r"   r2   r3   s      r#   schedule_batchzScheduler.schedule_batch9   s    r%   c                 l    t        t        | j                        xs t        | j                              S )z3Checks if there are requests ready to be processed.)boolr+   r   r   )r"   s    r#   has_pending_requestszScheduler.has_pending_requests@   s*     C,,-KT5J5J1KLLr%   r(   evict_from_cachec                 x    |r8| j                   j                  |       | j                  j                  |d       yy)zCompletes processing of a request and optionally frees its allocated cache blocks. This method is called
        when a request has finished generation or encountered an error.
        N)r   free_blocksr   r)   )r"   r(   r;   s      r#   finish_requestzScheduler.finish_requestE   s4    
 JJ"":.  $$Z6 r%   c                 T    || j                   v r| j                   |   j                  S g S )z,Gets generated tokens for an active request.)r   generated_tokensr"   r(   s     r#   !get_active_request_static_outputsz+Scheduler.get_active_request_static_outputsN   s.     ---''
3DDD	r%   c                 |    | j                   5  | j                  j                  |       ddd       y# 1 sw Y   yxY w)z!Marks a request for cancellation.N)r   r   addrA   s     r#   set_request_cancellationz"Scheduler.set_request_cancellationU   s6     $$ 	5$$((4	5 	5 	5s   2;c                 ~   | j                   5  | j                  D ]~  }| j                  j                  |d       | j                  j                  |d       || j
                  v r| j
                  j                  |       | j                  j                  |        t               | _        ddd       y# 1 sw Y   yxY w)z=Remove all cancelled requests from active and waiting queues.N)
r   r   r   r)   r   r   remover   r=   r   rA   s     r#   clear_cancelled_requestsz"Scheduler.clear_cancelled_requests[   s     $$ 	-"66 3
$$((T:%%))*d;!<!<<//66zB

&&z23 (+uD$	- 	- 	-s   BB33B<c                 ^    || j                   v xs || j                  vxr || j                  vS )z2Checks if a request has been cancelled or removed.)r   r   r   rA   s     r#   request_is_cancelledzScheduler.request_is_cancelledg   s:     T555 
d222^zI^I^7^	
r%   len_next_tokensc                 n   |j                         }|j                  | j                  j                  z  |z
  }||k  s|j                  dk(  rk||z
  dz   | j                  j                  z  dz   }| j                  j	                  ||j
                  |j                        }|y|xj                  |z  c_        y)a  Allocate additional cache blocks for a request if the currently allocated blocks are insufficient to
        accommodate the next tokens. It calculates how many blocks are needed based on the request's current
        cache occupancy and the number of tokens to be processed. The allocation itself is done by the CacheAllocator
        objects. Returns a boolean indicating if the allocation was successful or not.
        r   r	   FT)current_lenr-   r   
block_sizeallocate_blocksr(   )r"   r&   rK   rM   	occupancyblocks_needed	allocateds          r#   _allocate_blocks_if_neededz$Scheduler._allocate_blocks_if_neededn   s     '')**TZZ-B-BB[P	&%*@*@A*E-	9A=$**BWBWW[\\M

22=%BRBRTYTjTjkI ""i/"r%   "request_ids_to_remove_from_waitingc                    | j                   j                  r|j                  t        j                  k(  r| j                   j                  |j                  |j                        }|dkD  r|| j                  |j                  <   |j                  |j                         t        j                  |_        |xj                  || j                   j                  z  z  c_        t        |t        |j                        dz
        }|j                  |d |_        |xj                  |z  c_        |j                  t        j                   k(  r|j"                  }|S |j                  }|S )zPrepares a request for processing in the current batch. If prefix sharing is enabled, and the request was
        pending, this is where we look for a prefix match and split the request if found.r   r	   N)r   use_prefix_sharingstatusr   PENDINGsearch_prefix_matchr(   remaining_prefill_tokensr   rD   
PREFILLINGr-   rN   minr+   r.   DECODINGr*   )r"   r&   rT   prefill_lengthrequest_tokenss        r#   _infer_request_tokenszScheduler._infer_request_tokens   s"    ::((U\\]=R=R-R!ZZ;;E<L<LeNlNlmN!9>$$U%5%56266u7G7GH,77&&.DJJ<Q<Q*QQ&!$^S9W9W5X[\5\!]161O1OP^P_1`.%%7% <<=111"44N  #;;Nr%   r_   c                    |j                   dkD  r:|t        |      dz
  k\  r)t        |      dz
  }| j                  j                  |       t        |      |k  r|j                  t
        j                  k(  r4|| j                  |j                  <   |j                  |j                         |j                  t
        j                  k  r.|j                  |_        g |_        t
        j                  |_        yy|j                  t
        j                  k(  rI|| j                  |j                  <   t
        j                  |_        |j                  |j                         ||d |_        |d| |_        y)aR  Schedules a request for the current batch, updating the request's status according to the token budget left.
        After a request is scheduled, it is part of the next batch unless there is an error.
        If the request has children (for parallel decoding), it ensures at least one token remains before the request is
        forked.r   r	   N)num_childrenr+   r   r/   rW   r   rX   r   r(   rD   r[   rZ   r*   r]   )r"   r&   r_   r2   rT   s        r#   _schedule_requestzScheduler._schedule_request   s6    !lc.6IA6M&M~.2L""))%0 ~-||}4449>$$U%5%56266u7G7GH||}777*/*H*H'13.  -55 8 ||}4449>$$U%5%56,77266u7G7GH-;LM-JE*&4]l&CE#r%   
candidatessafety_marginc                    g }d}|| j                   j                  z  }|D ]   }	| j                   j                         }
|
|k  }|r?|r=|	j                  t        j
                  k7  r t        j                  d|
d|        ||fS |	j                         }| j                  |n|| j                  z  }||k  r| j                  |	|      }t        t        |      |      }| j                  |	|      }|sId}|
dk(  r@|	j                  | j                  v r(t        j                  d|	j                   d        ||fS | j!                  |	|||       t        |	j"                        }||z  }||z  }| j                   j$                  rF|	j                         | j                   j&                  z  }||z   }|| j                   j&                  z  }nd}|	j(                   }|j+                  t-        |	||             |	j                  }| j                  j/                  |d      du}|r|j1                  |       |dk(  s|dk(  s ||fS  ||fS )	a>  Schedules candidate requests for the current batch.

        This method contains the common logic shared by all schedulers: it checks token and cache budgets, allocates
        cache blocks if needed, updates request states, and tracks which waiting requests should be removed from the
        waiting queue.
        FzJOutside safety margin, breaking out of scheduling loop. num_free_blocks = z safety_margins = NTr   zBreaking mid-loop for request z because the cache is full)r   
num_blocksget_num_free_blocksrW   r   r]   r   inforM   r!   r`   r\   r+   rS   r(   r   rc   r*   allow_block_sharingrN   rZ   r/   r   r)   rD   )r"   rd   r2   r3   rT   re   scheduled_requestsone_allocation_failedsafety_marginsr&   num_free_blocksoutside_safety_margincache_neededr_   request_lenallocation_successfultokens_in_current_blocktokens_after_forwardcomplete_blockshas_new_tokenreq_idwas_waitings                         r#   _process_candidateszScheduler._process_candidates   s      %&)>)>> ?	E"jj<<>O$3n$D!$);P]PfPf@faNbbudrcvw r "#888m !,,.L $ 8 8 @lUYUmUmFm  l* "77?abNc.1<@K$($C$CE;$W! )(,% #a'E,<,<@U@U,UKK"@AQAQ@RRl mnB "#888A  ""5.,Hjke556K K'LL(L zz--*/*;*;*=

@U@U*U''>'L$"6$**:O:O"O"# !& > >>M%%&8&_` %%F//33FDAMK266v> q LA$5!#888C?	B "#888r%   c                 h    t        | j                  D cg c]	  }||vs| c}      | _        yc c}w )z8Removes processed requests from the waiting queue order.N)r   r   )r"   rT   rw   s      r#   _cleanup_waiting_queuez Scheduler._cleanup_waiting_queue  s.    &+"&"="=rOqAqVr'
#rs   	//)F)T)        )__name__
__module____qualname____doc__r
   r9   r$   r   r   r1   r   intlistr   r7   r:   strr>   rB   rE   rH   rJ   rS   r   r`   rc   floattuplery   r{   r6   r%   r#   r   r      sE   l1 l4 l 
= 
= 
= R3 Rc RdK]F^aeFe R R Md M M 7 7 7PT 7 7 C DI   53 5 5
 	- 	- 
s 
t 
 
  s W[  $< ]`ad]e jnorjs 2$D$D S	$D 	$D
 -0H$D 
$DX  #S9&S9 S9 	S9
 -0HS9 S9 
t&'-	.S9j
S 
VZ 
r%   r   c                   \     e Zd ZdZddededef fdZede	de	de
e   d	z  fd
       Z xZS )FIFOScheduleraK  This scheduler processes requests in the order they arrive, meaning decoding requests has priority over
    prefilling requests. Additionally, it includes a safety margin mechanism to prevent cache exhaustion. By default,
    when 80% of the cache is full, new requests will not be scheduled to prioritize decoding active requests.r   r   re   c                 4    t         |   ||       || _        y)a[  Initializes the FIFO scheduler. The safety margin is the percentage of free blocks under which we stop
        scheduling new prefill requests, so safety_margin = 0.1 means that when there is less than 10% of free blocks,
        or equivalently when more than 90% of blocks are already allocated, we stop scheduling new prefill requests.
        N)superr$   re   )r"   r   r   re   	__class__s       r#   r$   zFIFOScheduler.__init__#  s    
 	 67*r%   r2   r3   r4   Nc                    g }g }| j                   j                         D ]`  }|j                  t        j                  k(  r|j                  |       2|j                  t        j                  k(  sP|j                  |       b | j                  s/| j                  D ]   }|j                  | j                  |          " ||z   }t               }| j                  ||||| j                        \  }	}
| j                  |       |	s|
ry |	S )Nre   )r   valuesrW   r   r]   r/   r[   r   r   r   r   ry   re   r{   r"   r2   r3   priority_statessecond_priority_statesr&   rw   rd   rT   rk   rl   s              r#   r7   zFIFOScheduler.schedule_batch+  s   .057))002 	5E||}555&&u-!9!99&--e4		5 &&55 M&--d.C.CF.KLM %'==
-0U*484L4L.,, 5M 5
11 	##$FG "&;!!r%   )Fg?)r}   r~   r   r   r
   r9   r   r$   r   r   r   r   r7   __classcell__)r   s   @r#   r   r     sZ    q+1 +4 +hm +  "3  "c  "dK]F^aeFe  "  "r%   r   c                   :    e Zd ZdZedededee   dz  fd       Zy)PrefillFirstSchedulerzScheduler that prioritizes split prefill requests over decoding requests. This scheduler ensures that split
    prefill requests (which are continuations of partially processed prompts) are completed before processing new
    decoding requests.r2   r3   r4   Nc                    g }g }| j                   j                         D ]`  }|j                  t        j                  k(  r|j                  |       2|j                  t        j                  k(  sP|j                  |       b | j                  s/| j                  D ]   }|j                  | j                  |          " ||z   }t               }| j                  ||||d      \  }	}
| j                  |       |	s|
ry |	S )Nr|   r   )r   r   rW   r   r[   r/   r]   r   r   r   r   ry   r{   r   s              r#   r7   z$PrefillFirstScheduler.schedule_batchW  s	   .057))002 	5E||}777&&u-!7!77&--e4	5 &&55 M&--d.C.CF.KLM %'==
-0U*484L4L. 5M 5
11 	##$FG "&;!!r%   )	r}   r~   r   r   r   r   r   r   r7   r6   r%   r#   r   r   Q  s<     !"3 !"c !"dK]F^aeFe !" !"r%   r   )fifoprefill_first)r   abcr   r   collectionsr   utils.metricsr   r   r   r
   requestsr   r   r   r   r   r   r   SCHEDULER_MAPPINGr6   r%   r#   <module>r      sw     #  2 & M MB
 B
L ."I ." ."f '"I '" '"V * r%   