
    |-jW                         d dl Z d dlmZmZ d dlmZ ddlmZ ddlm	Z	m
Z
mZmZ  G d de          Z G d	 d
e          Z G d de          ZeedZdS )    N)ABCabstractmethod)deque   )PagedAttentionCache)FutureRequestStateRequestStateRequestStatusloggerc                   
   e Zd ZdZdefdZd dZdefdZe	d	e
d
e
deee         dz  ee
e
f         fd            ZdefdZdeddfdZdeeef         fdZdedee
         fdZdefdZdee         fdZdedefdZ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ee
e
f         fdZdee         fdZdee         ddfdZdS )"	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.
    cachec                     || _         t          j                    | _        | j         j        rd n| j         j        j        | _        | j         j        | j         j	        z  | _
        |                                  d S )N)r   	threadingLock_cancellation_locknum_full_attention_groupsconfigsliding_windowread_cache_limitmax_blocks_per_request
block_sizemax_decode_fast_path_lengthreset)selfr   s     u/var/www/html/banglarbhumi/venv/lib/python3.11/site-packages/transformers/generation/continuous_batching/scheduler.py__init__zScheduler.__init__   sa    
"+."2"2(,
(L rRVR\RcRr+/:+LtzOd+d(

    returnNc                     i | _         i | _        t                      | _        t	                      | _        g | _        d| _        dS )z0Reset scheduler state for a new generation loop.FN)active_requestswaiting_requestsr   waiting_requests_orderset_requests_to_cancel_requests_to_forkblock_new_requestsr   s    r   r   zScheduler.reset&   s@    8:9;27''#-0UU 57"'r   statec                 b    || j         |j        <   | j                            |j                   dS )z#Adds a request to the waiting list.N)r"   
request_idr#   append)r   r)   s     r   add_waiting_requestzScheduler.add_waiting_request/   s2    27e./#**5+;<<<<<r   token_budgetcache_budgetc                     dS )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.
        Returns the list of scheduled requests in their "FutureRequestState" form, a boolean indicating if the decode
        fast path can be used, the total number of query tokens and the maximum number of kv tokens read.N )r   r.   r/   s      r   schedule_batchzScheduler.schedule_batch4   s      r   c                 l    t          t          | j                  pt          | j                            S )z3Checks if there are requests ready to be processed.)boollenr!   r"   r(   s    r   has_pending_requestszScheduler.has_pending_requests?   s+    C,--KT5J1K1KLLLr   r+   c                 p    | j                             |           | j                            |d           dS )zCompletes processing of a request and frees its allocated cache blocks. This method is called
        when a request has finished generation or encountered an error.
        N)r   free_blocksr!   popr   r+   s     r   finish_requestzScheduler.finish_requestC   s9     	
z***  T22222r   c                     | j         r| j                                        S t          t	          | j                            }|| j                            |          fS )zRemove and return an active request chosen as the eviction victim for cache-pressure offload or soft reset.
        Picks the newest active request when `block_new_requests` is set, else the oldest.)r'   r!   popitemnextiterr9   r:   s     r   pop_request_to_evictzScheduler.pop_request_to_evictJ   sX     " 	2'//111$t34455
4/33J????r   c                 <    || j         v r| j         |         j        S g S )z,Gets generated tokens for an active request.)r!   generated_tokensr:   s     r   !get_active_request_static_outputsz+Scheduler.get_active_request_static_outputsR   s&    ---'
3DD	r   c                 z    | j         5  | j                            |           ddd           dS # 1 swxY w Y   dS )z!Marks a request for cancellation.N)r   r%   addr:   s     r   set_request_cancellationz"Scheduler.set_request_cancellationX   s    $ 	5 	5$((444	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5s   044c                    g }| j         5  | j        D ]}| j                            |d          }| j                            |d          }|p|}||                    |           || j        v r| j                            |           | j        	                    |           t                      | _        ddd           n# 1 swxY w Y   |S )z=Remove all cancelled requests from active and waiting queues.N)r   r%   r!   r9   r"   r,   r#   remover   r8   r$   )r   cancelled_statesr+   state_astate_wr)   s         r   clear_cancelled_requestsz"Scheduler.clear_cancelled_requests]   s   $ 	- 	-"6 	3 	3
.22:tDD/33JEE*7$$++E222!<<</66zBBB
&&z2222'*uuD$	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	-  s   B,CC	Cc                 8    || j         v p|| j        vo|| j        vS )z2Checks if a request has been cancelled or removed.)r%   r!   r"   r:   s     r   request_is_cancelledzScheduler.request_is_cancelledn   s/    T55 
d22^zI^7^	
r   len_next_tokensc                 "   |                                 }|j        | j        j        z  |z
  }||k     s|j        dk    rR||z
  dz   | j        j        z  dz   }| j                            ||j        |j                  }|dS |xj        |z  c_        dS )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   NFT)current_lenallocated_blocksr   r   allocate_blocksr+   )r   r)   rO   rQ   	occupancyblocks_needed	allocateds          r   _allocate_blocks_if_neededz$Scheduler._allocate_blocks_if_neededt   s     ''))*TZ-BB[P	&&%*@A*E*E-	9A=$*BWW[\\M
22=%BRTYTjkkI u""i/""tr   "request_ids_to_remove_from_waitingc                 4   | j         j        r|j        t          j        k    r|j        s| j                             |j        |j                  }|dk    r|| 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        }n|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is_cpu_offloadedsearch_prefix_matchr+   remaining_prefill_tokensr!   rE   
PREFILLINGrR   r   minr5   position_offsetDECODINGtokens_to_process)r   r)   rX   prefill_lengthrequest_tokenss        r   _infer_request_tokenszScheduler._infer_request_tokens   s    :( 	8U\]=R-R-R[`[q-R!Z;;E<LeNlmmN!!9>$U%56266u7GHHH,7&&.DJ<Q*QQ&&!$^S9W5X5X[\5\!]!]161OP^P_P_1`.%%7%% <=111"4NN #;Nr   rf   c                    |j         dk    rB|t          |          dz
  k    r,t          |          dz
  }| j                            |           t          |          |k    r{|j        t
          j        k    r)|| j        |j        <   |	                    |j                   |j        t
          j
        k    r&|j        |_        g |_        t
          j        |_        dS dS |j        t
          j        k    r:|| j        |j        <   t
          j
        |_        |	                    |j                   ||d         |_        |d|         |_        dS )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_childrenr5   r&   r,   r[   r
   r\   r!   r+   rE   r`   r_   rd   rc   )r   r)   rf   r.   rX   s        r   _schedule_requestzScheduler._schedule_request   sD    !!lc.6I6IA6M&M&M~..2L"))%000 ~,..|}4449>$U%56266u7GHHH|}777*/*H'13.  -5 87 |}4449>$U%56,7266u7GHHH-;LMM-JE*&4]l]&CE###r           
candidatessafety_marginc           	         g }d}| j         j        dk    }|| j         j        z  }	||}}
|D ]7}| j                                         }||	k     }|r4|r2|j        t
          j        k    rt          j        d|d|	            n| 	                    ||          }t          t          |          |          }|dk    o|j        | j        k     }|                                }| j        t          || j                  }|r|s||k     r|                     ||          }|s8d}|dk    r.|j        | j        v r t          j        d|j         d	            n,|                     ||||           t          |j                  }||dk    o|j        | j        k     z  }||z  }||z  }| j         j        r6|                                | j         j        z  }||z   }|| j         j        z  }nd}|j         }|                    t3          ||||                     |j        }| j                            |d          du}|r|                    |           |dk    s|dk    r|s n9|
|z
  }||z
  }|||||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.
        Fr   zJOutside safety margin, breaking out of scheduling loop. num_free_blocks = z safety_margins = r   NTzBreaking mid-loop for request z because the cache is full)r   r   
num_blocksget_num_free_blocksr[   r
   rc   r   inforg   ra   r5   rb   r   rQ   r   rW   r+   r"   rj   rd   allow_block_sharingr   r_   r,   r   r9   rE   )r   rl   r.   r/   rX   rm   scheduled_requestsone_allocation_faileddecode_fast_pathsafety_marginsoriginal_token_budgetoriginal_cache_budgetr)   num_free_blocksoutside_safety_marginrf   request_lenis_decode_eligibleread_cache_neededallocation_successfultokens_in_current_blocktokens_after_forwardcomplete_blockshas_new_tokenreq_idwas_waitingnum_q_tokensmax_kv_reads                               r   _process_candidateszScheduler._process_candidates   s.      %:<q@&)>>7C\4 F	 F	E"j<<>>O$3n$D!$ ); P]Pf@f@fwwwdrww    "77?abbNc.11<@@K
 "-!1!ne6KdNn6n % 1 1 3 3$0$'(94;P$Q$Q!$ ); PaAaAa %)$C$CE;$W$W! ) (,% #a''E,<@U,U,UK mAQ m m mnnnE ""5.,Hjkkke566K q 0 mU5JTMm5mm K'L--L z- $*/*;*;*=*=
@U*U''>'L$"6$*:O"O"# !& >>M%%&8`k&l&lmmm %F/33FDAAMK ?266v>>> q  \Q%6%6?O%6,|;+l:!#8:JLZeeer   c                 `   t                      }t                      }| j        D ]-}| j        |         }|j        r|n|                    |           .g }|s|rV|r'|                    |                                           |r'|                    |                                           |T|V|S )zReturns waiting requests in priority order. Since CPU-offloaded requests are cheaper to restore than fresh
        requests, they get priority, but we interleave them with fresh request to not saturate new batches with only
        offloaded requests.)r   r#   r"   r]   r,   popleft)r   	offloadedfreshr   r)   ordereds         r   _get_waiting_candidatesz!Scheduler._get_waiting_candidates%  s     */	%*WW1 	K 	KF)&1E0;YYeCCEJJJJ&( 	05 	0 4y0022333 0u}}///	  	05 	0
 r   c                 R    t          fd| j        D                       | _        dS )z8Removes processed requests from the waiting queue order.c                     g | ]}|v|	S r1   r1   ).0r   rX   s     r   
<listcomp>z4Scheduler._cleanup_waiting_queue.<locals>.<listcomp>9  s$    rrrOqAqAqVAqAqAqr   N)r   r#   )r   rX   s    `r   _cleanup_waiting_queuez Scheduler._cleanup_waiting_queue6  s5    &+rrrr$"=rrr'
 '
###r   )r   N)rk   ) __name__
__module____qualname____doc__r   r   r   r	   r-   r   inttuplelistr   r4   r2   r6   strr;   r@   rC   rF   rL   rN   rW   r$   rg   rj   floatr   r   r   r1   r   r   r   r      s<        1    ( ( ( (= = = = =
 mm/2m	t&'$.c3>	?m m m ^mMd M M M M3 3 3 3 3 3@eC,=&> @ @ @ @C DI    53 5 5 5 5
 $|*<        "
s 
t 
 
 
 
 s W[    $< ]`ad]e jnorjs    2$D$D S	$D 	$D
 -0H$D 
$D $D $D $DX  #^f ^f&^f ^f 	^f
 -0H^f ^f 
t&'tS#=	>^f ^f ^f ^f@l);    "
S 
VZ 
 
 
 
 
 
r   r   c            
       h     e Zd ZdZddedef fdZdededee	e
         d	z  eeef         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   rm   c                 X    t                                          |           || _        dS )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   rm   )r   r   rm   	__class__s      r   r   zFIFOScheduler.__init__C  s+    
 	*r   r.   r/   r   Nc                    g }g }| j                                         D ]W}|j        t          j        k    r|                    |           -|j        t          j        k    r|                    |           X| j        s'|                    | 	                                           ||z   }t                      }|                     ||||| j                  \  }}	}
}}|                     |           |s|	rd |
ddfS ||
||fS )Nrm   r   )r!   valuesr[   r
   rc   r,   r`   r'   extendr   r$   r   rm   r   r   r.   r/   priority_statessecond_priority_statesr)   rl   rX   rs   rt   ru   r   r   s                r   r2   zFIFOScheduler.schedule_batchK  sC    /157)0022 	5 	5E|}555&&u----!999&--e444 & 	J"))$*F*F*H*HIII$'==
-0UU*$$2"0 %   	_13C\S^ 	##$FGGG " 	0&; 	0)1a//!#3\;NNr   )r   )r   r   r   r   r   r   r   r   r   r   r   r4   r2   __classcell__)r   s   @r   r   r   >  s        q q+ +1 +% + + + + + +#O#O/2#O	t&'$.c3>	?#O #O #O #O #O #O #O #Or   r   c            
       L    e Zd ZdZdededeee         dz  eeef         fdZ	dS )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.r.   r/   r   Nc                    g }g }| j                                         D ]W}|j        t          j        k    r|                    |           -|j        t          j        k    r|                    |           X| j        s'|                    | 	                                           ||z   }t                      }|                     ||||d          \  }}	}
}}|                     |           |s|	rd |
ddfS ||
||fS )Nrk   r   r   )r!   r   r[   r
   r`   r,   rc   r'   r   r   r$   r   r   r   s                r   r2   z$PrefillFirstScheduler.schedule_batchx  s@    /157)0022 	5 	5E|}777&&u----!777&--e444 & 	J"))$*F*F*H*HIII$'==
-0UU*$$2! %   	_13C\S^ 	##$FGGG " 	0&; 	0)1a//!#3\;NNr   )
r   r   r   r   r   r   r   r   r4   r2   r1   r   r   r   r   s  sl         $O$O/2$O	t&'$.c3>	?$O $O $O $O $O $Or   r   )fifoprefill_first)r   abcr   r   collectionsr   r   r   requestsr   r	   r
   r   r   r   r   SCHEDULER_MAPPINGr1   r   r   <module>r      s'       # # # # # # # #       & & & & & & M M M M M M M M M M M Md
 d
 d
 d
 d
 d
 d
 d
P	0O 0O 0O 0O 0OI 0O 0O 0Oj)O )O )O )O )OI )O )O )OZ *    r   