ó
    qyüi=  ã                   óD  • S SK r S SKrS SKrS SKJr  S SKJr  S SKJr  SSK	J
r
   " S S\5      r\
" 5       (       a  S S	KJr  S S
KJrJrJr  SrOSrSS jr SSSSS.S\\\\\\\/\4   -  4      S-  4S jjjr\R0                  " \5      r\" 5        " S S5      5       rg)é    N)ÚCallable)ÚEnum)ÚAnyé   )Úis_opentelemetry_availablec                   ó4   • \ rS rSrSrSrSrSrSrSr	Sr
S	rS
rg)ÚRequestStatusé   z5Status of a generation request through its lifecycle.ÚpendingÚ
prefillingÚprefilling_splitÚsplit_pending_remainderÚdecodingÚfinishedÚfailed© N)Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__ÚPENDINGÚ
PREFILLINGÚPREFILLING_SPLITÚSPLIT_PENDING_REMAINDERÚDECODINGÚFINISHEDÚFAILEDÚ__static_attributes__r   ó    ÚW/home/mande/repo/quber/.venv/lib/python3.13/site-packages/transformers/utils/metrics.pyr	   r	      s*   † Ù?à€GØ€JØ)ÐØ7ÐØ€HØ€HØƒFr    r	   )Úmetrics)ÚStatusÚ
StatusCodeÚ
get_tracerTFc                 ó0   ^ • [         (       d  S $ U 4S jnU$ )aÃ  
Decorator that attaches a tracer to a class.

This decorator should be applied to classes that need OpenTelemetry tracing.
It adds a tracer attribute to the class instance that can be used by the traced decorator.

Args:
    tracer_name_template: Optional template string for the tracer name.
        If provided, it should contain {module} which will be replaced with the class's full module path
        and {class_name} for the class name.
        If None, a default naming scheme will be used where:
          - If the module already starts with "transformers.", it will use that directly
          - Otherwise, it will prepend "transformers." to the module name

Returns:
    Class decorator function
c                 ó   • U $ ©Nr   )Úclss    r!   Ú<lambda>Úattach_tracer.<locals>.<lambda>3   s   € ™3r    c                 ót   >^ ^• T R                   m[        R                  " T5      U UU4S j5       nUT l         T $ )Nc                 óà   >• T" U /UQ70 UD6  TR                   nTR                  nTc'  UR                  S5      (       a  U SU 3nOSU SU 3nOTR                  X4S9n[	        U5      U l        g )Nútransformers.Ú.)ÚmoduleÚ
class_name)r   r   Ú
startswithÚformatr%   Útracer)	ÚselfÚargsÚkwargsÚmodule_namer1   Útracer_namer)   Úoriginal_initÚtracer_name_templates	         €€€r!   Úinit_with_tracerÚ:attach_tracer.<locals>.decorator.<locals>.init_with_tracer8   s�   ø€ á˜$Ð0 Ò0¨Ò0àŸ.™.ˆKØ×)Ñ)ˆJà#Ñ+Ø×)Ñ)¨/×:Ñ:Ø%0 M°°:°,Ð"?‘Kà$1°+°¸aÀ
¸|Ð"L‘Kà2×9Ñ9ÀÐ9Ðd�ä$ [Ó1ˆD�Kr    )Ú__init__Ú	functoolsÚwraps)r)   r<   r:   r;   s   ` @€r!   Ú	decoratorÚ attach_tracer.<locals>.decorator5   s5   ú€ ØŸ™ˆä	�Š˜Ó	'ö	2ó 
(ð	2ð  (ˆŒØˆ
r    )Ú_has_opentelemetry)r;   rA   s   ` r!   Úattach_tracerrD       s   ø€ ÷$ ÒÙÐõð. Ðr    )Ú	span_nameÚ
standaloneÚadditional_attributesrG   c                ó2   ^^^• UUU4S jnU c  U$ U" U 5      $ )a^  
Decorator to trace function calls with OpenTelemetry.

Can be used as @traced or @traced(span_name="custom_name")

Args:
    func: The function to trace
    span_name: Optional custom name for the span (defaults to function name)
    standalone: If True, creates a parentless span
    additional_attributes: Optional list of additional attributes to set on the span.
      Each item is a tuple of (instance_attribute_name, span_attribute_key, value_or_transform_function)
      where:
        - instance_attribute_name: Name of the attribute to get from the class instance
        - span_attribute_key: Key to use when setting the attribute on the span
        - value_or_transform_function: Either a raw value to use directly, or a function to transform
          the attribute value before setting it on the span

Returns:
    Decorated function with tracing
c                 óh   >^ • [         (       d  T $ [        R                  " T 5      UU UU4S j5       nU$ )Nc            
      óæ  >• U (       a#  [        TS5      (       a  TR                  b  U S   OS nUS LnU(       a  [        US5      (       a  UR                  nO%[        STR                   STR
                   35      nT=(       d    TR
                  nT(       a  UR                  OUR                  nU" U5       nUR                  STR
                  5        UR                  STR                  5        UR                  SU5        U (       aƒ  [        U 5       Ht  u  p‰[        U	[        [        [        [        45      (       d  U	c   UR                  S	U 3[        U	5      5        MM  UR                  S	U 3[        [        U	5      5      5        Mv     U(       aˆ  UR!                  5        Ht  u  p«[        U[        [        [        [        45      (       d  Uc   UR                  S
U
 3[        U5      5        MM  UR                  S
U
 3[        [        U5      5      5        Mv     T(       a_  U(       aX  T HR  nUu  pÞn[        X-5      (       d  M  [#        X-5      n[%        U5      (       a	  U" U5      nOUnUR                  UU5        MT      T" U 0 UD6nUsS S S 5        $ ! [&         a?  nUR)                  [+        [,        R.                  5      5        UR1                  U5        e S nAff = f! , (       d  f       g = f)NÚ__self__r   r4   r.   r/   zfunction.namezfunction.modulezfunction.is_methodzargs.zkwargs.)ÚhasattrrK   r4   r%   r   r   Ú
start_spanÚstart_as_current_spanÚset_attributeÚ	enumerateÚ
isinstanceÚstrÚintÚfloatÚboolÚtypeÚitemsÚgetattrÚcallableÚ	ExceptionÚ
set_statusr#   r$   ÚERRORÚrecord_exception)r6   r7   ÚinstanceÚ	is_methodr4   ÚnameÚspan_fnÚspanÚiÚargÚkeyÚvalueÚattr_configÚinstance_attribute_nameÚspan_attribute_keyÚvalue_or_transform_functionÚattribute_valueÚtransformed_valueÚresultÚerG   ÚfuncrE   rF   s                       €€€€r!   ÚwrapperÚ*traced.<locals>.decorator.<locals>.wrappero   sa  ø€ æ"&¬G°D¸*×,EÑ,EÈ$Ï-É-ÑJc�t˜A’wÐjnˆHØ ¨Ð,ˆIæœW X¨x×8Ñ8Ø!Ÿ™‘ä# m°D·O±OÐ3DÀAÀdÇmÁmÀ_Ð$UÓV�à×- §¡ˆDÞ+5�f×'Ò'¸6×;WÑ;WˆGÙ˜” $Ø×"Ñ" ?°D·M±MÔBØ×"Ñ"Ð#4°d·o±oÔFØ×"Ñ"Ð#7¸ÔCæÜ"+¨D¦/™˜Ü% c¬C´´e¼TÐ+B×CÑCÀsÁ{Ø ×.Ñ.°°q°c¨{¼CÀ»HÖEà ×.Ñ.°°q°c¨{¼CÄÀSÃ	»NÖKñ	 #2ö
 Ø&,§l¡l¦n™
˜Ü% e¬c´3¼¼tÐ-D×EÑEÈÉØ ×.Ñ.°¸¸¨ÄÀEÃ
ÖKà ×.Ñ.°¸¸¨ÄÄDÈÃKÓ@PÖQñ	 '5ö )®YÛ'<˜ØcnÑ`Ð/ÐE`Ü" 8×EÓEÜ.5°hÓ.X˜OÜ'Ð(C×DÑDÙ4OÐP_Ó4`Ñ 1à4OÐ 1Ø ×.Ñ.Ð/AÐCTÖUñ (=ðÙ! 4Ð2¨6Ñ2�FØ!÷? ‘øô@ !ó Ø—O‘O¤F¬:×+;Ñ+;Ó$<Ô=Ø×)Ñ)¨!Ô,Øûðú÷A •ús1   Â8F
K"É<K"Ê	JÊ
KÊ :KËKËK"Ë"
K0)rC   r?   r@   )ro   rp   rG   rE   rF   s   ` €€€r!   rA   Útraced.<locals>.decoratork   s1   ù€ ß!Ò!ØˆKä	�Š˜Ó	÷.	ó 
ð.	ð` ˆr    r   )ro   rE   rF   rG   rA   s    ``` r!   Útracedrs   O   s    ú€ ÷85ðn �|ØÐÙ�T‹?Ðr    c                   ó¼   • \ rS rSrSrS\4S jrS r\S\	S\
SS	4S
 j5       r\S\SS	4S j5       r\SS j5       r\S\S\SS	4S j5       r\S\	S\
SS	4S j5       rSrg	)ÚContinuousBatchProcessorMetricséª   z0Metrics collection for ContinuousBatchProcessor.Úmax_batch_tokensc                 ó0   • Xl         U R                  5         g)ztInitialize metrics for continuous batch processor.

Args:
    max_batch_tokens: Maximum number of tokens in a batch
N)rw   Ú_setup_metrics)r5   rw   s     r!   r>   Ú(ContinuousBatchProcessorMetrics.__init__®   s   € ð !1Ôà×ÑÕr    c                 ó  • [         (       d  [        R                  S5        g[        R                  " S5      U l        / SQnU R
                  R                  SSSUS9U l        U R
                  R                  S	S
SS9U l	        U R
                  R                  SSSS9U l
        / SQnU R
                  R                  SSSUS9U l        U R
                  R                  SSSS9U l        U R
                  R                  SSSS9U l        U R
                  R                  SSSS9U l        / SQnU R
                  R                  SSSUS9U l        U R
                  R                  SSS S9U l        U R
                  R                  S!S"S S9U l        g)#zIInitialize OpenTelemetry metrics and tracing if the library is available.zˆOpenTelemetry is not installed. Metrics and tracing will not be recorded.You can install it with `pip install opentelemetry-api>=1.30.0`Nz2transformers.generation.continuous_batch_processor)é
   é   é2   éK   éd   é–   éÈ   i,  éô  iî  éè  éÐ  éˆ  é'  Úttft_millisecondsz#Time to first token in millisecondsÚms)r`   ÚdescriptionÚunitÚ#explicit_bucket_boundaries_advisoryÚactive_requests_countz3Number of active requests currently being processedÚrequests)r`   rŠ   r‹   Úwaiting_requests_countz*Number of requests waiting to be processed)r~   r€   éú   rƒ   r„   r…   r†   r‡   i N  i0u  i`ê  Úrequest_latency_millisecondsz9End-to-end latency for completed requests in millisecondsÚdecode_prefill_ratioz3Ratio of decode tokens to prefill tokens in a batchÚratioÚprefill_tokens_processedz"Number of prefill tokens processedÚtokensÚdecode_tokens_processedz!Number of decode tokens processed)é   r|   é   é   é(   r~   é<   éF   éP   éZ   é_   éb   r€   Úbatch_fill_percentagez5Percentage of max_batch_tokens utilized in each batchÚpercentÚkv_cache_free_memory_bytesz/Free memory of the PagedAttentionCache in bytesÚbytesÚkv_cache_memory_bytesz0Memory usage of the PagedAttentionCache in bytes)rC   ÚloggerÚinfor"   Ú	get_meterÚmeterÚcreate_histogramÚttft_histogramÚcreate_gaugeÚactive_requests_gaugeÚwaiting_requests_gaugeÚrequest_latency_histogramÚdecode_prefill_ratio_gaugeÚcreate_counterÚprefill_tokens_counterÚdecode_tokens_counterÚbatch_fill_percentage_histogramÚkv_cache_free_memory_gaugeÚkv_cache_memory_gauge)r5   Úttft_bucketsÚlatency_bucketsÚbatch_fill_bucketss       r!   ry   Ú.ContinuousBatchProcessorMetrics._setup_metrics¸   sÛ  € ÷ "Ò!Ü�K‰KðRôð ä×&Ò&Ð'[Ó\ˆŒ
ò _ˆà"Ÿj™j×9Ñ9Ø$Ø=ØØ0<ð	 :ð 
ˆÔð &*§Z¡Z×%<Ñ%<Ø(ØMØð &=ð &
ˆÔ"ð '+§j¡j×&=Ñ&=Ø)ØDØð '>ð '
ˆÔ#ò \ˆà)-¯©×)DÑ)DØ/ØSØØ0?ð	 *Eð *
ˆÔ&ð +/¯*©*×*AÑ*AØ'ØMØð +Bð +
ˆÔ'ð '+§j¡j×&?Ñ&?Ø+Ø<Øð '@ð '
ˆÔ#ð &*§Z¡Z×%>Ñ%>Ø*Ø;Øð &?ð &
ˆÔ"ò RÐà/3¯z©z×/JÑ/JØ(ØOØØ0Bð	 0Kð 0
ˆÔ,ð +/¯*©*×*AÑ*AØ-ØIØð +Bð +
ˆÔ'ð &*§Z¡Z×%<Ñ%<Ø(ØJØð &=ð &
ˆÕ"r    Úcreated_timeÚ
request_idÚreturnNc                 ó"  • [         (       d  g[        R                  " 5       U-
  S-  n U R                  R                  U5        [        R                  SU SUS S35        g! [         a"  n[        R                  SU 35         SnAgSnAff = f)zƒRecord Time to First Token (TTFT).

Args:
    created_time: The time the request was created
    request_id: The ID of the request
Nç     @�@zRecorded TTFT for request ú: ú.2fr‰   zFailed to record TTFT metric: )rC   Útimer«   Úrecordr¦   ÚdebugrZ   Úwarning)r5   r»   r¼   Úttft_msrn   s        r!   Úrecord_ttft_metricÚ2ContinuousBatchProcessorMetrics.record_ttft_metric  s„   € ÷ "Ò!Øä—9’9“; Ñ-°Ñ7ˆð	AØ×Ñ×&Ñ& wÔ/Ü�L‰LÐ5°j°\ÀÀGÈCÀ=ÐPRÐSÕTøÜó 	AÜ�N‰NÐ;¸A¸3Ð?×@Ñ@ûð	Aúó   ©8A" Á"
BÁ,B	Â	BÚfuture_statesc                 ó$  • [         (       a  U(       d  gSnSnU H|  nUR                  nUR                  [        R                  :X  a  US-  nM4  UR                  [        R
                  [        R                  4;   d  Md  U[        UR                  5      -  nM~     X#-   n US:”  a  U R                  R                  U5        US:”  a  U R                  R                  U5        US:”  a  X#-  nU R                  R                  U5        X`R                  -  S-  nU R                  R!                  U5        ["        R%                  SU SU SUS S	U S
U R                   S35        g! [&         a"  n	["        R)                  SU	 35         Sn	A	gSn	A	ff = f)z¯Record metrics about the batch composition including decode/prefill ratio and batch fill percentage.

Args:
    requests_in_batch: List of request states in the current batch
Nr   r   g      Y@zBatch metrics: z decode tokens, z prefill tokens, batch fill: rÁ   z% (Ú/Ú)z Failed to record batch metrics: )rC   ÚstateÚstatusr	   r   r   r   ÚlenÚ
prompt_idsr²   Úaddr³   r°   Úsetrw   r´   rÃ   r¦   rÄ   rZ   rÅ   )
r5   rÊ   Údecode_tokensÚprefill_tokensÚfuture_staterÎ   Útotal_batch_tokensr“   Úfill_percentagern   s
             r!   Úrecord_batch_metricsÚ4ContinuousBatchProcessorMetrics.record_batch_metrics  s‚  € ÷ "Ò!®ØàˆØˆã)ˆLØ ×&Ñ&ˆEØ�|‰|œ}×5Ñ5Ó5Ø Ñ"’Ø—‘¤-×":Ñ":¼M×<ZÑ<ZÐ![Õ[Ø¤# e×&6Ñ&6Ó"7Ñ7’ñ *ð +Ñ;Ðð	CØ Ó!Ø×+Ñ+×/Ñ/°Ô?à˜qÓ Ø×*Ñ*×.Ñ.¨}Ô=à Ó!Ø%Ñ6�Ø×/Ñ/×3Ñ3°EÔ:à1×4IÑ4IÑIÈUÑRˆOØ×0Ñ0×7Ñ7¸ÔHÜ�L‰LØ! - Ð0@ÀÐ@Pð QØ.¨sÐ3°3Ð7IÐ6JÈ!ÈD×LaÑLaÐKbÐbcðeõøô ó 	CÜ�N‰NÐ=¸a¸SÐA×BÑBûð	Cús   ÂCE# Å#
FÅ-F
Æ
Fc                 óh  • [         (       d  g UR                  UR                  -  nX!R                  R                  -  nS[        UR                  5      -  UR                  -  U-  nUR                  5       nUR                  U-
  nXd-  nXT-  nU R                  R                  U5        U R                  R                  U5        [        R                  SUS-  S SU SUR                   SXaR                  -  S	-  S
 S3	5        g! [         a"  n	[        R!                  SU	 35         Sn	A	gSn	A	ff = f)zþRecord memory usage of the PagedAttentionCache without GPU synchronization.

This calculates the theoretical memory usage based on cache configuration
and the number of blocks currently in use.

Args:
    cache: The PagedAttentionCache object to measure
Né   zKV Cache memory: i   rÁ   zMB, Used blocks: rÌ   z (r€   z.1fz%)z*Failed to record KV cache memory metrics: )rC   Úhead_dimÚnum_key_value_headsÚdtypeÚitemsizerÐ   Ú	key_cacheÚ
block_sizeÚget_num_free_blocksÚ
num_blocksr¶   rÓ   rµ   r¦   rÄ   rZ   rÅ   )
r5   ÚcacheÚ	page_sizeÚpage_mem_in_bytesÚblock_mem_in_bytesÚfree_blocksÚused_blocksÚused_memory_bytesÚfree_memory_bytesrn   s
             r!   Úrecord_kv_cache_memory_metricsÚ>ContinuousBatchProcessorMetrics.record_kv_cache_memory_metricsI  sD  € ÷ "Ò!Øð	MàŸ™¨×)BÑ)BÑBˆIØ )¯K©K×,@Ñ,@Ñ @Ðð "#¤S¨¯©Ó%9Ñ!9¸E×<LÑ<LÑ!LÐO`Ñ!`Ðð  ×3Ñ3Ó5ˆKØ×*Ñ*¨[Ñ8ˆKð !,Ñ @ÐØ +Ñ @Ðð ×&Ñ&×*Ñ*Ð+<Ô=Ø×+Ñ+×/Ñ/Ð0AÔBÜ�L‰LØ#Ð$5¸Ñ$EÀcÐ#Jð K Ø +˜}¨A¨e×.>Ñ.>Ð-?ð @Ø×"2Ñ"2Ñ2°SÑ8¸Ð=¸RðAõøô
 ó 	MÜ�N‰NÐGÈÀsÐK×LÑLûð	Mús   ŽC6D Ä
D1ÄD,Ä,D1Úactive_requestsÚwaiting_requestsc                 ó   • [         (       d  g U R                  R                  U5        U R                  R                  U5        [        R                  SU SU S35        g! [         a"  n[        R                  SU 35         SnAgSnAff = f)z™Record metrics about active and waiting requests.

Args:
    active_requests: Number of active requests
    waiting_requests: Number of waiting requests
NzQueue metrics: z active requests, z waiting requestsz Failed to record queue metrics: )rC   r­   rÓ   r®   r¦   rÄ   rZ   rÅ   )r5   rï   rð   rn   s       r!   Úrecord_queue_metricsÚ4ContinuousBatchProcessorMetrics.record_queue_metricsq  s…   € ÷ "Ò!Øð	CØ×&Ñ&×*Ñ*¨?Ô;Ø×'Ñ'×+Ñ+Ð,<Ô=Ü�L‰L˜?¨?Ð*;Ð;MÐN^ÐM_Ð_pÐqÕrøÜó 	CÜ�N‰NÐ=¸a¸SÐA×BÑBûð	Cús   ŽAA! Á!
BÁ+BÂBc                 ó"  • [         (       d  g[        R                  " 5       U-
  S-  n U R                  R                  U5        [        R                  SU SUS S35        g! [         a"  n[        R                  SU 35         SnAgSnAff = f)zŠRecord metrics about a completed request.

Args:
    created_time: The time the request was created
    request_id: The ID of the request
Nr¿   z Recorded request completion for rÀ   rÁ   r‰   z,Failed to record request completion metric: )rC   rÂ   r¯   rÃ   r¦   rÄ   rZ   rÅ   )r5   r»   r¼   Ú
latency_msrn   s        r!   Úrecord_request_completionÚ9ContinuousBatchProcessorMetrics.record_request_completionƒ  s†   € ÷ "Ò!Øä—i’i“k LÑ0°FÑ:ˆ
ð	OØ×*Ñ*×1Ñ1°*Ô=ä�L‰LÐ;¸J¸<ÀrÈ*ÐUXÐIYÐY[Ð\Õ]øÜó 	OÜ�N‰NÐIÈ!ÈÐM×NÑNûð	OúrÉ   )r­   r´   r°   r³   rµ   r¶   rw   r©   r²   r¯   r«   r®   )r½   N)r   r   r   r   r   rS   r>   ry   rs   rT   rR   rÇ   ÚlistrÙ   rí   rò   rö   r   r   r    r!   ru   ru   ª   sâ   † á:ð¨ô òR
ðh ðA¨uð AÀ#ð AÈ$ó Aó ðAð$ ð'C°$ð 'C¸4ó 'Có ð'CðR ó%Mó ð%MðN ðC°Cð CÈ3ð CÐSWó Có ðCð" ðO°eð OÈð OÐQUó Oó óOr    ru   r(   )r?   ÚloggingrÂ   Úcollections.abcr   Úenumr   Útypingr   Úimport_utilsr   r	   Úopentelemetryr"   Úopentelemetry.tracer#   r$   r%   rC   rD   rø   ÚtuplerR   rs   Ú	getLoggerr   r¦   ru   r   r    r!   Ú<module>r     sÍ   ðÛ Û Û Ý $Ý Ý å 4ô	�Dô 	ñ ×ÑÝ%ßBÑBàÑàÐô,ð` 
ðUð ØØVZòUð
    c¨3°°hÀ¸uÀc¸zÑ6JÑ0JÐ&JÑ KÑLÈtÑSöUðp 
×	Ò	˜8Ó	$€ñ ƒ÷jOð jOó ñjOr    