
    ^jx              
          d Z ddlZddlZddlZddlZ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 ddlmZ ddlmZ er2ddlZddlZddlZdd	lmZmZmZmZmZ dd
lmZ ddlmZ ddl m!Z! ddl"m#Z#  ejH                  e%      Z&dZ' G d dejP                        Z) G d d      Z* G d de+      Z, G d de-      Z. G d de/      Z0ddi ddddddd id!d"ddd#d$d%d&d'id%d(d)d*d+d,d"d-Z1d.d/d0e2dz  fd1Z3d2e2d0e2fd3Z4d4e2d0e5e2   dz  fd5Z6d6gd7d%d&d'id&d'id8d9d:d;Z7d<g d=d>d?iZ8d`d.d/d0e2dz  fd@Z9dAe-dBe2d0e:e-e-dz  f   fdCZ;dDe5e<   d0e=fdEZ>dFe<d0e=fdGZ? G dH dI      Z@dJe
dKe-d0eAfdLZB G dM dN      ZC G dO dP      ZDdQe<d0dfdRZEdadSZF G dT dU      ZG G dV dWe      ZH G dX dYeH      ZI G dZ d[eH      ZJ G d\ d]      ZK G d^ d_      ZLy)bz?
Shared types, constants, and utilities for the serving layer.
    N)ABCabstractmethod)Callable)Future)Queue)TYPE_CHECKING)logging)ContinuousBatchingConfigGenerationConfigPreTrainedModelPreTrainedTokenizerFastProcessorMixin)ContinuousBatchingManager)GenerationOutput)	Scheduler   )ModelManagerzx-request-idc                        e Zd ZdZdZdZdZdZy)ModalityLLMVLM
MULTIMODALSTTTTSN)__name__
__module____qualname__r   r   r   r   r        i/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/cli/serving/utils.pyr   r   9   s    
C
CJ
C
Cr   r   c                       e Zd ZdZdefdZy)_StreamErrorz5Sentinel to signal an error from the generate thread.msgc                     || _         y N)r#   )selfr#   s     r    __init__z_StreamError.__init__D   s	    r   N)r   r   r   __doc__strr'   r   r   r    r"   r"   A   s    ?C r   r"   c                       e Zd ZdZy)_GenerationCancelledzERaised inside ``DirectStreamer.put()`` to abort ``model.generate()``.Nr   r   r   r(   r   r   r    r+   r+   H   s    Or   r+   c                       e Zd ZdZy)ReasoningTextzTagged str subclass: text chunk belonging to a thinking/reasoning block.

    Streamers wrap reasoning text with this so handlers can route it to
    ``reasoning_content`` deltas instead of ``content``.
    Nr,   r   r   r    r.   r.   L       r   r.   c                       e Zd ZdZy)CBWorkerDeadErrorzRaised when a request is submitted to a CB worker that has died.

    Surfaced as 503 by the FastAPI exception handler. Carries the original error message
    that killed the worker so the client knows why the server is in this state.
    Nr,   r   r   r    r1   r1   T   r/   r   r1   z<tool_call>z</tool_call>z<|im_start|>assistant

tool_callsTjson)opencloserepeatscontent)defaultsstart_anchorfields)stcetcschemaz9<function=(?P<name>[^>\n]+)>(?P<arguments>.*?)</function>arrayobjecttypestringz<<parameter=(?P<key>[^>\n]+)>\s*(?P<value>.*?)\s*</parameter>)r@   zx-regex-key-valuename	arguments)r@   
properties)zx-regex-iteratorr@   items))	qwen2	qwen2_moeqwen2_vl
qwen2_5_vlqwen3	qwen3_moe
qwen3_nextqwen3_vlqwen3_vl_moe)qwen3_5qwen3_5_moemodelr   returnc                    t        | d|       }t        |dd      }t        |dd      }t        |dd      }t        |dd      }d}|r;|r9|r7d|j                  di       v r#i d|d   d   id	}d
D ]  }||v s||   ||<    n` n^|r|r|r	|d   d   }nO|j                  j                  t	        fdt
        j                         D        d      }	|	y|	d   |	d   |	d   }}}|j                  |      }
|j                  |      }||
|dS )af  Return tool call config for the model, or ``None`` if tool calls are not supported.

    Returns a dict with:
        - ``schema`` (`dict`): Schema to pass to ``tokenizer.parse_response(block, schema)``.
        - ``stc_id`` (`int`): Token ID of the start-of-tool-call delimiter.
        - ``etc_id`` (`int`): Token ID of the end-of-tool-call delimiter.
    	tokenizer	stc_tokenN	etc_tokenresponse_templateresponse_schemar2   r:   )r8   r:   )r9   start_anchor_patternrE   c              3   2   K   | ]  \  }}|v s|  y wr%   r   ).0typesv
model_types      r    	<genexpr>z'get_tool_call_config.<locals>.<genexpr>   s     _xua:Y^K^_s   r;   r<   r=   )r=   stc_idetc_id)getattrgetconfigr_   next_TOOL_CALL_FALLBACKSrF   convert_tokens_to_ids)	processorrR   rU   r;   r<   rX   rY   r=   
anchor_keyfallbackra   rb   r_   s               @r    get_tool_call_configrl      sR    	;	:I
)[$
/C
)[$
/C	+>Ei):DAOF
s(\=N=R=RS[]_=`-`#%6x%@%NO

 C 	J..%6z%Bz"	
 
 .|< \\,,
_+?+E+E+G_aef#E?HUOXh=O&S,,S1F,,S1F&AAr   	tool_callc                     | j                  d|       }|j                  di       }|d   t        |t              st        j                  |      dS |dS )a  Normalize a parsed tool call to ``{"name": str, "arguments": str}``.

    Different models return different structures from ``parse_response``:
    - Gemma: ``{"function": {"name": ..., "arguments": {...}}}`` (nested, arguments as dict)
    - Qwen:  ``{"name": ..., "arguments": {...}}`` (flat, arguments as dict)

    The OpenAI API expects ``arguments`` as a JSON **string**, so we ``json.dumps`` it.
    functionrD   rC   rB   )rd   
isinstancer)   r3   dumps)rm   ro   rD   s      r    _normalize_tool_callrr      sX     }}Z3H["-I 2<Y2LTZZ	* R[ r   r=   c                     | j                  ||d      }t        |t              r	d|v r|d   }|syt        |t              s|g}|D cg c]  }t	        |       }}|r|S dS c c}w )a>  Parse tool calls from generated token IDs using ``tokenizer.parse_response``.

    Args:
        processor: The processor or tokenizer.
        generated_ids: Token IDs from generation. Passed directly to ``parse_response``
            which decodes them internally, preserving special tokens that
            ``skip_special_tokens=True`` would strip (e.g. Gemma's ``<|tool_call>``).
        schema: The tool call schema (from ``response_schema`` or ``_TOOL_CALL_FALLBACKS``).

    Returns a list of ``{"name": str, "arguments": str}`` dicts, or ``None`` if none found.
     )prefixr2   N)parse_responserp   dictlistrr   )ri   generated_idsr=   parsedrm   r2   s         r    parse_tool_callsr{      sy     %%mVB%GF&$LF$:%fd#CIJi&y1JJJ#:-- Ks   A"z<think>z</think>)thinkingr7   zK(?:<think>)?(?P<thinking>.*?)</think>(?P<content>.*?)(?:<\|[^|<>\s]+\|>)?\Z)r@   rE   zx-regex)startendr=   gemma4)z
<|channel>thought
z
<channel|>)r}   r~   c                   	
 t        | d|       
|j                  j                  j                         	t	        	fdt
        j                         D        t              }|d   D cg c]  }
j                  |       }}
j                  |d         }t        
fd|D              s|d
j                  fv ryt        
dd      }|rd|d	   v s	t        d
   }|||d}|t        ||      |d<   |S c c}w )a  Return reasoning config for the model, or ``None`` if not supported.

    The config drives both streaming detection (token IDs) and post-hoc parsing
    (response schema). Returns a dict with:
        - ``start_ids`` (`list[int]`): Token ID sequence that opens a thinking block.
        - ``end_id`` (`int`): Token ID that closes the block.
        - ``schema`` (`dict`): Response schema with ``thinking`` / ``content``
          properties for :func:`parse_reasoning`.
        - ``start_in_thinking`` (`bool`, only when ``input_ids`` is given): Whether
          the rendered prompt already opened an unclosed thinking block (prefilled
          by the template), so the model's output begins inside the block.
    rU   c              3   4   K   | ]  \  }}|k(  s|  y wr%   r   )r\   kr^   r_   s      r    r`   z'get_reasoning_config.<locals>.<genexpr>  s     Ctq!1
?Cs   r}   r~   c              3   >   K   | ]  }|d j                   fv   y wr%   )unk_token_id)r\   tidrU   s     r    r`   z'get_reasoning_config.<locals>.<genexpr>  s!     
FS34//00
Fs   NrY   r|   rE   r=   )	start_idsend_idr=   start_in_thinking)rc   re   r_   lowerrf   _THINKING_TOKENSrF   _DEFAULT_THINKING_TOKENSrh   anyr   _starts_in_thinking)ri   rR   	input_idsthinking_tokenstr   r   r=   re   r_   rU   s            @@r    get_reasoning_configr     s    	;	:I((..0JC'--/C O >MW=UV003VIV,,_U-CDF

FI
FF&UY[d[q[qTrJr Y 148FzVL%99)(3!*fOF&9)Y&O"#M Ws   &C1r7   reasoning_configc                     | j                  ||d         }|r(|j                  dd      }|r|j                  dd      |fS |j                  d      rd|fS |dfS )u  Split generated output into ``(content, reasoning_content)`` via ``parse_response``.

    If the schema's regex matches (closing marker present), use it. For prompts
    that prefill the opener (QwQ-32B, DeepSeek-R1) the entire output is reasoning
    until ``</think>`` arrives — when that's truncated, fall back to treating
    all decoded text as reasoning. Returns ``(content, None)`` otherwise.
    r=   r|   rt   r7   r   N)rv   rd   )ri   ry   r7   r   rz   	reasonings         r    parse_reasoningr   %  sm     %%m5Eh5OPFJJz2.	::i,i77 /07{D=r   r   c                    t        | d      r| j                         } | r't        | d   t              rt	        |       dk7  ry| d   } t	        |      }dD ]/  }t	        |       ||z   k\  st	        |       |z
  }| ||z
  | |k(  s/ y y)uy  True if the rendered prompt ends with an unclosed thinking block.

    Some reasoning-model chat templates prefill the thinking opener as the final
    prompt tokens (e.g. DeepSeek-R1, QwQ-32B emit ``<think>\n`` at the end when
    ``add_generation_prompt=True``). In those cases the model resumes *inside*
    the block, so its output contains only ``...reasoning</think>answer`` with
    no opening tag — the streamer must start with ``_inside_thinking=True``.

    The prefill always lands at the tail of the prompt (optionally followed by a
    single whitespace token like ``\n``), so we only inspect the last few tokens.
    tolistr   r   F)r   r   T)hasattrr   rp   rx   len)r   r   ntrailingr~   s        r    r   r   9  s     y(#$$&	Z	!d3y>QaL	IA y>Q\)i.8+Cq3'94	
 r   token_idc                 l   | j                   y| j                  r|| j                  k(  rd| _        yy| j                   t        | j                           }||k7  rg | _        y| j                  j                  |       t        | j                        t        | j                         k(  rd| _        g | _        y)uU  Mutate ``streamer``'s thinking state; return ``True`` if ``token_id`` is a start or end token.

    Shared between :class:`DirectStreamer` and :class:`CBStreamer` — both track the
    same four attributes (``_thinking_start_ids``, ``_thinking_end_id``,
    ``_inside_thinking``, ``_thinking_prefix``) and need identical edge handling.
    FT)_thinking_start_ids_inside_thinking_thinking_end_idr   _thinking_prefixappend)streamerr   expecteds      r    _advance_thinking_stater   U  s     ##+  x000(-H%++C0I0I,JKH8$&!$$X.
8$$%X-I-I)JJ$(!$&!r   c                   p    e Zd ZdZdedefdZdededz  ddfd	Zded
ededz  ddfdZ	deddfdZ
ddZy)DownloadAggregatora	  Aggregates byte-progress across multiple concurrent download tqdm bars.

    huggingface_hub opens one tqdm bar per file shard. This class tracks them all and emits
    a single aggregate ``{"stage": "download", "progress": {...}}`` event whenever any updates.
    enqueuemodel_idc                 <    || _         || _        i | _        d | _        y r%   )r   rR   barslast_emitted_current)r&   r   r   s      r    r'   zDownloadAggregator.__init__u  s    
79	04!r   bar_idtotalNrS   c                 F    d|f| j                   |<   | j                          y)z6Register a new download bar with its total byte count.r   Nr   _emit)r&   r   r   s      r    registerzDownloadAggregator.register{  s    J		&

r   currentc                 F    ||f| j                   |<   | j                          y)z>Update a bar's current byte count and emit aggregate progress.Nr   )r&   r   r   r   s       r    updatezDownloadAggregator.update  s    $e,		&

r   c                      y r%   r   )r&   r   s     r    r5   zDownloadAggregator.close      r   c                 T   t        d | j                  j                         D              }|| j                  k(  ry || _        | j                  j                         D cg c]
  \  }}|	| }}}|rt        |      nd }| j	                  d| j
                  d||dd       y c c}}w )Nc              3   &   K   | ]	  \  }}|  y wr%   r   )r\   c_s      r    r`   z+DownloadAggregator._emit.<locals>.<genexpr>  s     ;1!;   loadingdownloadr   r   statusrR   stageprogress)sumr   valuesr   r   rR   )r&   agg_currentr   r   totals	agg_totals         r    r   zDownloadAggregator._emit  s    ;		(8(8(:;;$333$/! $		 0 0 2D1am!DD#)CKt	##(3iH		
 Es   
B$*B$rS   N)r   r   r   r(   r   r)   r'   intr   r   r5   r   r   r   r    r   r   n  su    5 5C 5s 3: $ 
S 3 sTz d 
C D 
r   r   callbackr   c                 N     ddl m} t                G  fdd|      }|S )u  Create a tqdm subclass that routes progress to a callback.

    Bars with ``unit="B"`` are download bars — aggregated via ``DownloadAggregator``.
    Other bars (e.g. "Loading weights") emit ``weights`` stage events.

    Args:
        callback (`callable`): Called with a dict payload
            ``{"status": "loading", "model": ..., "stage": ..., "progress": ...}``.
        model_id (`str`): The model ID (included in progress payloads).

    Returns:
        A tqdm subclass that forwards progress to *callback*.
    r   )tqdmc                   L     e Zd Z fdZdfd	ZfdZ fdZ xZS ).make_progress_tqdm_class.<locals>.ProgressTqdmc                 
   |j                  d      xs d| _        d|d<   t        |   |i | d| _        d| _        | j                  dk(  r7t        |       | _        j                  | j                  | j                         y y )NunititTdisabler   B)
rd   sse_unitsuperr'   r   last_emittedid_bar_idr   r   )r&   argskwargs	__class__download_aggregators      r    r'   z7make_progress_tqdm_class.<locals>.ProgressTqdm.__init__  sw    "JJv.6$DM $F9Gd-f-DF "D}}#!$x#,,T\\4::F $r   c                 X   |d}| xj                   |z  c_         | j                  dk(  r2j                  | j                  | j                   | j                         y | j                   | j
                  k7  r6| j                   | _         dd| j                   | j                  dd       y y Nr   r   r   weightsr   r   )r   r   r   r   r   r   )r&   r   r   r   r   s     r    r   z5make_progress_tqdm_class.<locals>.ProgressTqdm.update  s    yFFaKF}}##**4<<L4,,,$(FF!"+!)!*04$L	 -r   c           	   3     K   | j                   D ]  }| xj                  dz  c_        | j                  dk(  r2j                  | j                  | j                  | j
                         nN| j                  | j                  k7  r5| j                  | _         dd| j                  | j
                  dd       |  y wr   )iterabler   r   r   r   r   r   )r&   itemr   r   r   s     r    __iter__z7make_progress_tqdm_class.<locals>.ProgressTqdm.__iter__  s      !==C''..t||TVVTZZPVVt000(,D%&/%-%.48FFTZZ(P	 
s   B;B>c                 v    | j                   dk(  rj                  | j                         t        |           y )Nr   )r   r5   r   r   )r&   r   r   s    r    r5   z4make_progress_tqdm_class.<locals>.ProgressTqdm.close  s*    }}##))$,,7GMOr   )r   )r   r   r   r'   r   r   r5   __classcell__)r   r   r   r   s   @r    ProgressTqdmr     s    	G	"	"	 	r   r   )	tqdm.autor   r   )r   r   	base_tqdmr   r   s   ``  @r    make_progress_tqdm_classr     s/     ,,Xx@0 0y 0d r   c                       e Zd ZdZ	 	 	 ddddej
                  dej                  dededz  d	edz  fd
Z	ddZ
ddZddZy)DirectStreamera  Streamer for ``model.generate()`` (used by :class:`GenerateManager`).

    Implements the ``put``/``end`` protocol that ``model.generate()`` expects:
    generate calls ``put(token_tensor)`` after each decode step, and ``end()``
    when generation is complete. Tokens are decoded incrementally via the Rust
    ``DecodeStream`` (O(1) per token) and pushed as text to an asyncio.Queue.
    NrU   tokenizers.Tokenizerloopqueueskip_special_tokenstool_configr   c                    ddl m} || _        || _        || _         |g |      | _        |r|d   nd| _        |r|d   nd| _        d| _        |r|d   nd| _	        |r|d   nd| _
        t        |xr |j                  d	            | _        g | _        d
| _        t!        j"                         | _        d| _        g | _        y)a  
        Args:
            tokenizer: The Rust tokenizer (``tokenizer._tokenizer``).
            loop (`asyncio.AbstractEventLoop`): The event loop to push decoded text to.
            queue (`asyncio.Queue`): The queue that receives decoded text chunks.
            skip_special_tokens (`bool`, *optional*, defaults to `True`):
                Whether to strip special tokens during decoding.
            tool_config (`dict`, *optional*): Tool call config from ``get_tool_call_config``.
                When set, tokens between stc/etc delimiters (inclusive) are suppressed
                from the queue so tool call markup is never streamed to the client.
            reasoning_config (`dict`, *optional*): Thinking config from ``get_reasoning_config``.
                When set, tokens between start/end delimiters are wrapped as
                :class:`ReasoningText` so handlers route them to ``reasoning_content``.
        r   DecodeStreamra   Nrb   Fr   r   r   T)tokenizers.decodersr   
_tokenizer_loop_queue_decode_stream_stc_id_etc_id_inside_tool_callr   r   boolrd   r   r   _first	threadingEvent
_cancelledtotal_tokensgenerated_token_ids)r&   rU   r   r   r   r   r   r   s           r    r'   zDirectStreamer.__init__  s    . 	5#
*2/BC0;{8,0;{8,!&DT#3K#@Z^ >N 0 :TX $%5%c:J:N:NOb:c d+-#//+.0 r   c                    | j                   j                         r
t               | j                  rd| _        y|j	                         D ]  }| xj
                  dz  c_        | j                  j                  |       || j                  k(  rd| _	        n|| j                  k(  rd| _	        t        | |      }| j                  j                  | j                  |      }|| j                  s|| j                  k(  s|r| j                  rt!        |      }| j"                  j%                  | j&                  j(                  |        y)zHCalled by ``model.generate()`` after each decode step with new token(s).FNr   T)r  is_setr+   r  r   r  r  r   r   r   r   r   r   stepr   r   r.   r   call_soon_threadsafer   
put_nowait)r&   valuer   is_start_or_end_tokentexts        r    putzDirectStreamer.put  s   ??!!#&((;;DK 	JH"$$++H54<<')-&T\\)).&$;D($K!&&++DOOXFD|t55T\\9QUj$$$T*JJ++DKK,B,BDI!	Jr   c                 d    | j                   j                  | j                  j                  d       y)z;Called by ``model.generate()`` when generation is complete.N)r   r
  r   r  r&   s    r    r~   zDirectStreamer.end,  s     

''(>(>Er   c                 8    | j                   j                          y)zWSignal cancellation. The next ``put()`` call will raise and abort ``model.generate()``.N)r  setr  s    r    cancelzDirectStreamer.cancel0  s    r   )TNN)r  torch.TensorrS   Nr   )r   r   r   r(   asyncioAbstractEventLoopr   r   rw   r'   r  r~   r  r   r   r    r   r     su     %)#'(,'1)'1 '''1 }}	'1
 "'1 D['1 +'1RJ4Fr   r   c                       e Zd ZdZ	 	 ddddedddej                  d	ej                  d
edz  dedz  fdZ	ddZ
ddZddZy)
CBStreamera  Streamer for continuous batching (used by :class:`CBGenerateManager`).

    Same ``put``/``end`` protocol as :class:`DirectStreamer`, but called manually
    by :class:`CBGenerateManager` instead of by ``model.generate()``:
    ``put(output)`` receives a CB ``GenerationOutput``, decodes new tokens, and
    pushes text to the asyncio.Queue. ``end()`` signals the stream is complete.
    N
cb_managerr   
request_idrU   r   r   r   r   r   c                 n   ddl m} || _        || _        || _        || _        || _         |g d      | _        |r|d   nd| _        |r|d   nd| _	        d| _
        |r|d   nd| _        |r|d	   nd| _        t        |xr |j                  d
            | _        g | _        d| _        d| _        g | _        y)aY  
        Args:
            cb_manager (`ContinuousBatchingManager`): The CB manager instance.
            request_id (`str`): The request ID to track in the CB scheduler.
            tokenizer: The Rust tokenizer (``tokenizer._tokenizer``).
            loop (`asyncio.AbstractEventLoop`): The event loop to push decoded text to.
            queue (`asyncio.Queue`): The queue that receives decoded text chunks.
            tool_config (`dict`, *optional*): Tool call config (see ``DirectStreamer``).
            reasoning_config (`dict`, *optional*): Thinking config (see ``DirectStreamer``).
        r   r   Tra   Nrb   Fr   r   r   )r   r   _cb_request_idr   r   r   r   r   r   r   r   r   r   rd   r   r   	_prev_lenr  r  )	r&   r  r  rU   r   r   r   r   r   s	            r    r'   zCBStreamer.__init__>  s    ( 	5%
#*2t40;{8,0;{8,!&DT#3K#@Z^ >N 0 :TX $%5%c:J:N:NOb:c d+-.0 r   c                 :   |j                   | j                  d }t        |j                         | _        |D ]  }| xj                  dz  c_        | j                  j                  |       || j                  k(  rd| _        n|| j                  k(  rd| _        t        | |      }| j                  j                  | j                  |      }|| j                  s|| j                  k(  s|r| j                  rt        |      }| j                  j!                  |        y)zLDecode new tokens from a CB ``GenerationOutput`` and push text to the queue.Nr   TF)generated_tokensr  r   r  r  r   r   r   r   r   r   r	  r   r   r.   r   r  )r&   output
new_tokensr   r  r  s         r    r  zCBStreamer.pute  s    ,,T^^-=>
V445" 	)H"$$++H54<<')-&T\\)).&$;D($K!&&++DOOXFD|t55T\\9QUj$$$T*KK""4(!	)r   c                 :    | j                   j                  d       y)zSignal end of stream.N)r   r  r  s    r    r~   zCBStreamer.end{  s    t$r   c                 N    | j                   j                  | j                         y)zCancel the CB request.N)r  cancel_requestr  r  s    r    r  zCBStreamer.cancel  s     0 01r   NN)r"  r   rS   Nr   )r   r   r   r(   r)   r  r  r   rw   r'   r  r~   r  r   r   r    r  r  5  sz     $((,%1/%1 %1 *	%1
 ''%1 }}%1 D[%1 +%1N),%2r   r  seedc                 0    ddl } |j                  |        y)z8Set the PyTorch random seed for reproducible generation.r   N)torchmanual_seed)r(  r*  s     r    set_torch_seedr,    s    Edr   c                  v    ddl } | j                  j                         r| j                  j                          yy)z+Empty the CUDA cache if a GPU is available.r   N)r*  cudais_availableempty_cache)r*  s    r    reset_torch_cacher1    s*    zz 

  !r   c                   J    e Zd ZdZd ZddZdefdZdej                  fdZ	y)	InferenceThreadzPersistent thread for ``model.generate()`` calls.

    ``torch.compile`` with CUDA graphs stores state in thread-local storage.
    All inference must run on the same thread to avoid corrupted graph state.
    c                     t               | _        t        j                  | j                  d      | _        | j
                  j                          y )NT)targetdaemon)r   r   r  Thread_run_threadr}   r  s    r    r'   zInferenceThread.__init__  s3    "W ''tyyFr   rS   Nc                 D   	 | j                   j                         \  }}}}}	  ||i |}||j                  |j                  |       n|j                  |       Z# t        $ r:}||j                  |j
                  |       n|j                  |       Y d }~?d }~ww xY wr%   )r   rd   r
  
set_result	Exceptionset_exception)r&   fnr   r   futurer   resultes           r    r8  zInferenceThread._run  s    -1[[__->*Bffd
,T,V,#--f.?.?H%%f-   ,#--f.B.BAF((+	,s   8A 	B%0BBc                 Z    t               }| j                  j                  ||||df       |S )ESubmit a callable to the inference thread. Returns a blocking Future.N)r   r   r  )r&   r>  r   r   r?  s        r    submitzInferenceThread.submit  s)    T66489r   c                     t        j                         }|j                         }| j                  j	                  |||||f       |S zOSubmit a callable to the inference thread. Returns an awaitable asyncio.Future.)r  get_running_loopcreate_futurer   r  )r&   r>  r   r   r   r?  s         r    async_submitzInferenceThread.async_submit  s>    '')##%T66489r   r   )
r   r   r   r(   r'   r8  r   rD  r  rI  r   r   r    r3  r3    s-    
,V 7>> r   r3  c                       e Zd ZdZddZe	 	 dddd	d
dedddededz  dedz  dee	j                  df   fd       Zeddd	d
dedddedeeeee   f   fd       Zedd       Zy)BaseGenerateManageru   Base class for generation managers.

    Subclasses:
    - :class:`GenerateManager` — sequential ``model.generate()`` on a persistent thread.
    - :class:`CBGenerateManager` — continuous batching with paged attention.
    rR   r   
gen_configr   rS   Nc                      y)z:Initialize continuous batching. No-op for non-CB managers.Nr   r&   rR   rL  s      r    init_cbzBaseGenerateManager.init_cb      r   ri   (ProcessorMixin | PreTrainedTokenizerFastinputsr  r   r   zDirectStreamer | CBStreamerc                      y)a  Start streaming generation.

        Args:
            model (`PreTrainedModel`): The loaded model.
            processor: The processor or tokenizer for decoding.
            inputs (`dict`): Tokenized inputs (tensors for sequential, lists for CB).
            gen_config (`GenerationConfig`): Generation parameters.
            request_id (`str`): Unique request identifier.
            tool_config (`dict`, *optional*): Tool call config from ``get_tool_call_config``.
                When set, tool call tokens (between stc/etc) are suppressed from output.
            reasoning_config (`dict`, *optional*): Thinking config from ``get_reasoning_config``.
                When set, thinking tokens are wrapped as :class:`ReasoningText`.

        Returns:
            `tuple[asyncio.Queue, DirectStreamer | CBStreamer]`: A ``(queue, streamer)`` pair
            where *queue* yields ``str | _StreamError | None`` and *streamer* exposes
            ``.total_tokens`` and ``.cancel()``.
        Nr   )r&   rR   ri   rR  rL  r  r   r   s           r    generate_streamingz&BaseGenerateManager.generate_streaming  rP  r   c                    K   yw)a  Run generation to completion.

        Args:
            model (`PreTrainedModel`): The loaded model.
            processor: The processor or tokenizer for decoding.
            inputs (`dict`): Tokenized inputs (tensors for sequential, lists for CB).
            gen_config (`GenerationConfig`): Generation parameters.
            request_id (`str`): Unique request identifier.

        Returns:
            `tuple[str, int, list[int]]`: ``(text, input_len, generated_ids)``.
        Nr   )r&   rR   ri   rR  rL  r  s         r    generate_non_streamingz*BaseGenerateManager.generate_non_streaming  s     s   c                      y)z/Stop the generation manager and free resources.Nr   r  s    r    stopzBaseGenerateManager.stop  rP  r   rR   r   rL  r   rS   Nr'  r   )r   r   r   r(   rO  r   rw   r)   tupler  r   rT  r   rx   rV  rX  r   r   r    rK  rK    s    I  $((,  > 	
 '  D[ + 
w}};;	< :   > 	
 '  
sCc"	# * > >r   rK  c                       e Zd ZdZd Z	 	 dddddded	d
dededz  dedz  deej                  e
f   fdZddddded	d
dedeeedf   fdZdedefdZdedej                  fdZddZy)GenerateManagerzFSequential generation via ``model.generate()`` on a persistent thread.c                 "    t               | _        y r%   )r3  r9  r  s    r    r'   zGenerateManager.__init__  s    &(r   NrR   r   ri   rQ  rR  rL  r   r  r   r   rS   c                    t        j                         t        j                         t        |d|      j                  }t        |||      }	i ||	||dt        d      rdd<   dfd}
| j                  |
       |	fS )	zLStart streaming generation via ``model.generate()`` on the inference thread.rU   r   r   )r   generation_configrU   
has_talkerr  generation_modec            	          	  j                   di  y # t        $ r j                  j                  d        Y y t        $ r8} j                  j                  t        t        |                    Y d } ~ y d } ~ ww xY w)Nr   )generater+   r
  r  r<  r"   r)   )rA  
gen_kwargsr   rR   r   s    r    r8  z0GenerateManager.generate_streaming.<locals>._run  sm    R,,' B))%*:*:DA R))%*:*:LQ<PQQRs    %A=A=.A88A=r   )r  rG  r   rc   r   r   r   rD  )r&   rR   ri   rR  rL  r  r   r   rust_tokenizerr   r8  re  r   r   s    `         @@@r    rT  z"GenerateManager.generate_streaming  s     '')&}} KCNN!D%[Sc
 onH:dmn
5,',2J()	R 	R 	Dhr   r  c                    K   i |||d}t        |d      rd|d<    | j                  |j                  fi | d{   }|d   j                  d   }|d|df   }	|j	                  |	d	
      }
|
||	fS 7 7w)zNRun generation to completion via ``model.generate()`` on the inference thread.)r`  rU   ra  r  rb  Nr   r   r   Tr   )r   rI  rd  shapedecode)r&   rR   ri   rR  rL  r  generate_kwargs	sequences	input_lenry   r  s              r    rV  z&GenerateManager.generate_non_streaming'  s      ^V]*S\]5,'17O-.+$++ENNNoNN	;'--b1	!!YZ-04HY--	 Os   ;A7A58A7r>  c                 B     | j                   j                  |g|i |S )rC  )r9  rD  r&   r>  r   r   s       r    rD  zGenerateManager.submit;  s#    "t||""27777r   c                 B     | j                   j                  |g|i |S rF  )r9  rI  ro  s       r    rI  zGenerateManager.async_submit?  s#    (t||((=d=f==r   c                      y r%   r   r  s    r    rX  zGenerateManager.stopC  r   r   r'  r   )r   r   r   r(   r'   rw   r)   rZ  r  r   r   rT  r   rV  r   r   rD  rI  rX  r   r   r    r\  r\     s    P) $((,  > 	
 '  D[ + 
w}}n,	-B. . >. 	.
 '. . 
sC'	(.(8 8v 8>x >W^^ >r   r\  c                       e Zd ZdZdddZdd	Zdefd
ZdeddfdZ		 	 dddddde
dddede
dz  de
dz  deej                  ef   fdZddddde
dddedeeeee   f   fdZedd       ZddZy)CBGenerateManagerau  Continuous batching generation via paged attention.

    Translates between the handler's text-level asyncio.Queue and CB's
    token-level interface. Per-request: ``max_new_tokens``, ``eos_token_id``.

    The CB manager is initialized lazily on the first request via
    :meth:`ensure_initialized`, using that request's ``gen_config`` for shared
    sampling params (temperature, top_p, do_sample).

    .. todo:: Remove :meth:`init_cb` when CB supports per-request
       generation config. At that point, ``gen_config`` can be passed directly
       to ``add_request`` and the CB manager no longer needs a shared config.
    Nc                      d | _         || _        y r%   )r  
_cb_config)r&   	cb_configs     r    r'   zCBGenerateManager.__init__V  s    59#r   rR   r   rL  r   rS   c                     | j                   y|j                  || j                        | _         | j                   j                          y)at  Initialize the CB manager on first call with the request's generation config.

        .. todo:: Remove when CB supports per-request generation config.

        Args:
            model (`PreTrainedModel`): The loaded model (must support ``init_continuous_batching``).
            gen_config (`GenerationConfig`): Generation config used for shared sampling params.
        N)r`  continuous_batching_config)r  init_continuous_batchingru  r}   rN  s      r    rO  zCBGenerateManager.init_cbZ  sA     8811(T__ 2 
 	r   c                 R    | j                   du xs | j                   j                  du S )zJWhether the CB worker is healthy. ``True`` before ``init_cb()`` is called.N)r  fatal_errorr  s    r    is_alivezCBGenerateManager.is_alivek  s%    xx4?488#7#74#??r   r  c                     | j                   <| j                   j                  %t        d| d| j                   j                         yy)u   Raise :class:`CBWorkerDeadError` if the CB worker has died.

        Called at request entry to fail fast — submitting to a dead worker would otherwise
        enqueue the request into a void where it never gets processed.
        Nz,CB worker is dead and cannot accept request : )r  r{  r1   )r&   r  s     r    _check_alivezCBGenerateManager._check_aliveo  sN     88DHH$8$8$D#>zl"TXXMaMaLbc  %Er   ri   rQ  rR  r   r   c           	         | j                   }|t        d      | j                  |       t        j                         }	t        j
                         |d   }
|j                  |
|d|j                  |j                        }t        |d|      j                  }t        | j                   |||	||      fd}|j                  ||       fS )zFStart streaming CB generation. Registers a per-request output handler.3CB manager not initialized. Call `init_cb()` first.r   T)r  	streamingmax_new_tokenseos_token_idrU   r_  c                 `   	 j                  |        | j                  5j                  t        | j                               j	                          y | j                         rj	                          y y # t        $ r-}j                  t        t        |                   Y d }~y d }~ww xY wr%   )r  errorr  r"   r~   is_finishedr<  r)   )r"  rA  r   
text_queues     r    
_on_outputz8CBGenerateManager.generate_streaming.<locals>._on_output  s    <V$ <<+)),v||*DELLN'')LLN * <%%l3q6&:;;<s   AA7  A7 7	B- #B((B-)r  RuntimeErrorr  r  rG  r   add_requestr  r  rc   r   r  register_result_handler)r&   rR   ri   rR  rL  r  r   r   cbr   r   rf  r  r   r  s                @@r    rT  z$CBGenerateManager.generate_streamingz  s     XX:TUU*%'')$+MMO
;'	^^!%44#00 $ 

 !KCNNHH#-
	< 	"":z:8##r   c                 F  K   | j                   }|t        d      | j                  |       |d   }t        |      }t	        j
                         }	|	j                         fd}
|j                  ||
       |j                  |||j                  d|j                          d{   }|j                  B|j                  t        d| d|j                         t        d	| d|j                         |j                  }|j                  |d
      }|||fS 7 vw)zcRun non-streaming CB generation. Registers a handler that resolves an asyncio.Future on completion.Nr  r   c                 J    j                         sj                  |        y y r%   )doner;  )r@  r?  s    r    
_on_resultz<CBGenerateManager.generate_non_streaming.<locals>._on_result  s    ;;=!!&) !r   F)r  r  r  r  zCB worker died during request r~  zCB generation failed for Trh  )r  r  r  r   r  rG  rH  r  r  r  r  r  r{  r1   r!  rj  )r&   rR   ri   rR  rL  r  r  r   rm  r   r  r@  ry   r  r?  s                 @r    rV  z(CBGenerateManager.generate_non_streaming  s5     XX:TUU*%;'		N	 '')##%	* 	"":z:
!%44#00 	 	
  <<#~~)'*HTVW]WcWcVd(eff!::,bWXX//4HY-- s   B%D!(D)A7D!c                     | j                   | j                   j                  t        d      | j                   j                  j                  S )z*The CB scheduler (for testing/monitoring).z.Continuous batching processor not initialized.)r  batch_processorr  	schedulerr  s    r    r  zCBGenerateManager.scheduler  s?     88txx77?OPPxx''111r   c                 X    | j                   | j                   j                  dd       y y )NT   )blocktimeout)r  rX  r  s    r    rX  zCBGenerateManager.stop  s%    88HHMMaM0  r   r%   )rv  ContinuousBatchingConfig | NonerY  r'  )rS   r   r   )r   r   r   r(   r'   rO  r   r|  r)   r  rw   rZ  r  r   r  rT  r   rx   rV  propertyr  rX  r   r   r    rs  rs  G  s   $"@$ @	s 	t 	$ $((,8$ 8$ >8$ 	8$
 '8$ 8$ D[8$ +8$ 
w}}j(	)8$t/. /. >/. 	/.
 '/. /. 
sCc"	#/.b 2 21r   rs  c                   j    e Zd ZdZ	 	 	 ddededdfdZdd	d
edefdZddedede	fdZ
ddZdefdZy)GenerationStatea'  Shared generation state across all handlers.

    Manages per-model :class:`GenerateManager` instances (each with its own
    :class:`InferenceThread` so different models can run concurrently while
    ``torch.compile`` / CUDA graphs require same-model-same-thread) and a
    single :class:`CBGenerateManager` for continuous batching.

    Args:
        continuous_batching (`bool`, *optional*, defaults to `False`):
            Whether to use continuous batching with paged attention instead of
            sequential ``model.generate()`` calls.
    Ncontinuous_batchingcompilerv  r  c                 X    || _         || _        || _        i | _        d | _        d | _        y r%   )_continuous_batching_compileru  _generate_managers_cb_manager_cb_model_id)r&   r  r  rv  s       r    r'   zGenerationState.__init__  s2     %8!#>@59(,r   rR   r   modalityrS   c                     | j                   syt        |d      xr |t        j                  k(  }|s,t        j                  |j                  j                   d       |S )aW  Check if continuous batching can be used for this model and modality.

        Args:
            model (`PreTrainedModel`): The loaded model.
            modality (`Modality`): The detected model modality (LLM, VLM, etc.).

        Returns:
            `bool`: ``True`` if CB is enabled and the model supports it, ``False`` otherwise.
        Fry  zM does not support continuous batching. Falling back to sequential generation.)r  r   r   r   loggerwarning_oncer   r   )r&   rR   r  cans       r    use_continuous_batchingz'GenerationState.use_continuous_batching  s]     ((e78UX=U??++, -9 9 
r   r   use_cbc                 Z   |rv| j                   |k7  r-| j                  !| j                  j                          d| _        | j                  "t        | j                        | _        || _         | j                  S || j
                  vrt               | j
                  |<   | j
                  |   S )af  Return a per-model generation manager, lazily created on first request.

        Args:
            model_id (`str`): The model ID in ``'model_id@revision'`` format.
            use_cb (`bool`): Whether to return a CB manager or a sequential one.

        Returns:
            `BaseGenerateManager`: Either a `GenerateManager` or `CBGenerateManager`.
        N)rv  )r  r  rX  rs  ru  r  r\  )r&   r   r  s      r    get_managerzGenerationState.get_manager   s       H,##/$$))+'+D$'#4t#O $,!###42220?0AD##H-&&x00r   c                 `    | j                   "| j                   j                          d| _         yy)z$Stop any active generation managers.N)r  rX  r  s    r    shutdownzGenerationState.shutdown7  s-    '!!##D (r   c                 V    | j                   du xs | j                   j                         S )zTWhether the CB worker is healthy. ``True`` if CB is disabled or not yet initialized.N)r  r|  r  s    r    is_cb_alivezGenerationState.is_cb_alive=  s'    4'F4+;+;+D+D+FFr   )FFNFr   )r   r   r   r(   r   r'   r   r  r)   rK  r  r  r  r   r   r    r  r    s}     %*7;	-!- - 5	--> ( W[ (1C 1 1BU 1.$GT Gr   r  c            	           e Zd ZU dZdZedz  ed<    e       Zee	   ed<   	 dddde
dedz  fd	Zd
eddfdZeddde	fd       Zd
edee	ddf   fdZ	 dd
edddeddfdZedee   dedee   fd       Zy)BaseHandlera  Shared logic for chat completion and responses handlers.

    Provides model resolution, generation config building, and SSE formatting.
    Generation is delegated to the shared :class:`GenerationState`.

    Args:
        model_manager (`ModelManager`):
            Handles model loading, caching, and lifecycle.
        generation_state (`GenerationState`):
            Shared state managing per-model generation managers.
    N_valid_params_class_unused_fieldsmodel_managerr   generation_statechat_template_kwargsc                 6    || _         || _        |xs i | _        y r%   )r  r  r  )r&   r  r  r  s       r    r'   zBaseHandler.__init__R  s!     + 0$8$>B!r   bodyrS   c                    ddl m} t        |j                               }| j                  1|t        | j                  dt                     z
  }|r |dd|       || j                  z  }|rt        j                  d|        yy)	zMValidate request fields against the handler's params class and unused fields.r   HTTPExceptionN__mutable_keys__i  z"Unexpected fields in the request: status_codedetailz,Ignoring unsupported fields in the request: )	fastapir  r  keysr  rc   r  r  r  )r&   r  r  
input_keys
unexpectedunuseds         r    _validate_requestzBaseHandler._validate_request\  s    )%
##/#gd.F.FHZ\_\a&bbJ#>`ak`l<mnnd111"Nvh WX r   chunkzstr | pydantic.BaseModelc                     t        | t              r| j                  d      r| S d|  dS d| j                  d       dS )z;Format a pydantic model or string as an SSE ``data:`` line.zdata: z

T)exclude_none)rp   r)   
startswithmodel_dump_json)r  s    r    chunk_to_ssezBaseHandler.chunk_to_ssei  sM     eS!!,,X65PfUG4<PP--4-@AFFr   r   rQ  c                    ddl m} | j                  j                  j|j	                  d      }|>|| j                  j                  k7  r% |dd| j                  j                   d| d      | j                  j                  |d<   | j                  j                  |d         }| j                  j                  |      \  }}|||fS )	zfApply force_model, load model + processor.

        Returns ``(model_id, model, processor)``.
        r   r  rR   i  zServer is pinned to 'z'; requested 'z'.r  )r  r  r  force_modelrd   process_model_nameload_model_and_processor)r&   r  r  	requestedr   rR   ri   s          r    _resolve_modelzBaseHandler._resolve_modelp  s    
 	*))5)I$d6H6H6T6T)T# #3D4F4F4R4R3SSabkallno  !..::DM%%88gG--FFxPy	))r   model_generation_configr   r  c                 B   ddl m} |j                  d       |di t        j                  |d         }n7t        j                  |      }|j                  |j                  dk  rd|_        |j                  d      +t        |d         |_	        t        |d         dk(  rd|_
        |j                  d      t        |d         |_        |j                  d	      t        |d	          | j                  j                  r|j                  d
|_        |rd|_        |S )a'  Build a GenerationConfig from shared params (temperature, top_p, seed, generation_config JSON).

        Subclasses should call ``super()._build_generation_config(...)`` then apply
        endpoint-specific params (``max_tokens``, ``max_output_tokens``, etc.).

        Args:
            body (`dict`):
                The raw request body.
            model_generation_config (`GenerationConfig`):
                The model's default generation config (will be deep-copied).
            use_cb (`bool`, *optional*, defaults to `False`):
                Whether continuous batching is active. If ``True``, disables the model's
                internal KV cache (CB manages its own paged cache).

        Returns:
            `GenerationConfig`: A new config with request-specific overrides applied.
        r   )r   r`  i   temperatureg        Ftop_pr(  staticr   )transformersr   rd   r3   loadscopydeepcopyr  floatr  	do_sampler  r,  r  r  cache_implementation	use_cache)r&   r  r  r  r   r`  s         r    _build_generation_configz$BaseHandler._build_generation_config  s   ( 	288'(4 0 Y4::dCV>W3X Y $.E F //7;L;[;[^b;b37!088M".,1$}2E,F)T-()S0.3!+88G(&+DM&:#88F'4<(   )).?.T.T.\5=2 */' ! r   messagesr  c                    g }| D ]v  }|d   g d}d|v rzg }|d   D ]k  }t        j                  |      }|j                  d      xs |}t        |d   t              rt        j                  |d         |d<   |j                  |       m ||d<   d|v r|d   |d<   d|v rg n|j                  d      xs g }t        |t              rd|d	g}|D ]h  }	|	d
   }
|
dv r|d   j                  d|	d   d	       (|
dv rT|t        j                  t        j                  fv r2|	d   }t        |t              r|d   }|d   j                  d|d       |
dk(  re|t        j                  k(  rR|	d   }t        |t              r#|d   }|j                  d      }|rd| d| n|}n|}|d   j                  d|d       |
dk(  rA|t        j                  t        j                  fv r|d   j                  d|	d   d   d       0|
dk(  s7|t        j                  k(  sL|d   j                  d|	d   d   d       k |t        j                  k(  rdj                  d |d   D              |d<   |j                  |       y |S )a=  Convert OpenAI-format messages to the format expected by HF processors.

        All modalities extract text. VLM additionally handles ``image_url`` and ``video_url``.
        MULTIMODAL handles all of the above plus ``input_audio`` and ``audio_url``.
        For LLMs, the content parts are collapsed into a plain text string.

        Args:
            messages (`list[dict]`): OpenAI-format chat messages.
            modality (`Modality`): The model modality (LLM, VLM, or MULTIMODAL).

        Returns:
            `list[dict]`: Processor-compatible messages.
        role)r  r7   r2   ro   rD   tool_call_idr7   r  )r@   r  r@   )r  
input_textoutput_text)	image_urlinput_imager  urlimage)r@   r  input_audiodataformatzdata:audio/z;base64,audio	video_urlvideo	audio_url c              3   &   K   | ]	  }|d      yw)r  Nr   )r\   r   s     r    r`   zABaseHandler.get_processor_inputs_from_messages.<locals>.<genexpr>  s     ,R1QvY,Rr   )r  r  rd   rp   r)   r3   r  r   r   r   r   rw   r   join)r  r  processor_inputsmessagerz   r2   tcr>  raw_contentr7   content_typer  r  	audio_b64fmts                  r    "get_processor_inputs_from_messagesz.BaseHandler.get_processor_inputs_from_messages  s     7	,G%fo"=F w&
!,/ *Br*B
+1rB!"[/37*.**R_*E;%%b)* (2|$()0)@~& !- 7"gkk)>T>ZXZK+s+(.DE& d&v#HH9%,,fgfo-VW!%AAhS[S_S_aiatatRuFu!+.C!#t,!%j9%,,gc-JK "]2x8CVCV7V")-"8K!+t4$/$7	)ooh7HKC5DQZ)9%,,gc-JK![0X(,,PXPcPcAd5d9%,,ggkFZ[`Fa-bc![0XATAT5T9%,,ggkFZ[`Fa-bc7d< 8<<'$'HH,Ry@Q,R$Ry!##F+o7	,p  r   r%   r  )r   r   r   r(   r  r@   __annotations__r  r  r)   r  rw   r'   r  staticmethodr  rZ  r  r   r  rx   r   r  r   r   r    r  r  B  s   
 (,+"uNCH$ -1	?%? *? #Tk	?Yd Yt Y G6 G3 G G*4 *E#7HJt2t,u *, W\0!0!3E0!OS0!	0!d H T$Z H 8 H X\]aXb H  H r   r  r%   r   )Mr(   r  r  enumr3   r  abcr   r   collections.abcr   concurrent.futuresr   r   r   typingr   transformers.utilsr	   pydantic
tokenizersr*  r  r
   r   r   r   r   :transformers.generation.continuous_batching.continuous_apir   4transformers.generation.continuous_batching.requestsr   5transformers.generation.continuous_batching.schedulerr   r  r   
get_loggerr   r  X_REQUEST_IDEnumr   r"   r<  r+   r)   r.   r  r1   rg   rw   rl   rr   rx   r{   r   r   r   rZ  r   r   r   r   r   r   r@   r   r   r  r,  r1  r3  rK  r\  rs  r  r  r   r   r    <module>r     s        # $ %    &   eUO+ 
		H	% tyy  P9 PC  0 5)+#%	
(  \ #X. (-l"	
!?1 h(B+< (B (BVD T ".t .T
T@Q .6 [*)
 b
 , 7M	 +< QUX\Q\ Ds d W\]`behlbl]lWm (d3i D 8  2(
 (
VDx D3 D4 DNR RjL2 L2^  !& &RA># A>HD) DNg1+ g1TNG NGb~  ~ r   