
    -`i              5       z   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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mZ ddlZddlZddlmZ dd	lmZmZm Z  dd
l!m"Z"m#Z#m$Z$m%Z% ddl&m'Z' ddl(m)Z)m*Z* ddl+m,Z,m-Z- ddl.m/Z/ ddl0m1Z1 dZ2ej3        4                    d          duo e	j5        d          duZ6	 dPde7de8dz  de9e7e7f         fdZ:e G d d                      Z;de7dej<        de;dz  fdZ= G d de          Z>e G d d                      Z?e G d d                       Z@d!ed"         dz  d#eAdz  d$eAdz  d%eAd&eAd'eBdeBfd(ZC	 	 	 	 dQd*eDe         d'eBd+eBd!ed"         dz  d#eAdz  d$eAdz  dee9eeBf         df         fd,ZEd-eDe%         d.eBd/eDeB         de@fd0ZFd*eDe         d-eDe%         d.eBd1e,d/eDeB         d2e8e7eBf         de9e?eDeA         f         fd3ZG	 	 	 	 dRd5e>d6e7d7e7de7d8e7d9e7d1e,d*eDe         d:eAdz  d'eBd+eBd;eHd<eAd=eHd>eDe7         d/eDeB         d?eHd2e8e7eBf         d@eAdz  dAee7         dz  dBe8dz  dCe8dz  d!ed"         dz  d#eAdz  d$eAdz  dDeAf4dEZIdF ZJdG ZKdHejL        dIe8e7ef         dJe7ddfdKZMdLejN        fdMZOdHejL        de8e7ef         fdNZPdHejL        de8e7ef         fdOZQdS )Sa  Benchmark online serving throughput.

On the server side, run one of the following commands
to launch the vLLM OpenAI API server:
    vllm serve <your_model> <engine arguments>

On the client side, run:
    vllm bench serve \
        --backend <backend or endpoint type. Default 'openai'> \
        --label <benchmark result label. Default using backend> \
        --model <your_model. Optional, defaults to first model from server> \
        --dataset-name <dataset_name. Default 'random'> \
        --input-len <general input length. Optional, maps to dataset-specific args> \
        --output-len <general output length. Optional, maps to dataset-specific args> \
        --request-rate <request_rate. Default inf> \
        --num-prompts <num_prompts. Default 1000>
    N)AsyncGeneratorIterable)	dataclass)datetime)Enum)AnyLiteral)tqdm)SampleRequestadd_dataset_parserget_samples)ASYNC_REQUEST_FUNCSOPENAI_COMPATIBLE_BACKENDSRequestFuncInputRequestFuncOutput)wait_for_endpoint)#convert_to_pytorch_benchmark_formatwrite_to_json)TokenizerLikeget_tokenizer)freeze_gc_heap)join_host_port  termplotlibgnuplotbase_urlheadersreturnc                   K   |  d}t          j                    4 d{V }	 |                    ||          4 d{V }|                                 |                                 d{V }d|v ret          |d                   dk    rL|d         d         d         |d         d         d         fcddd          d{V  cddd          d{V  S t          d|  d	          # 1 d{V swxY w Y   n9# t           j        t          j        f$ r}t          d
| d|           |d}~ww xY w	 ddd          d{V  dS # 1 d{V swxY w Y   dS )z<Fetch the first model from the server's /v1/models endpoint.z
/v1/modelsN)r   datar   idrootz!No models found on the server at z8. Make sure the server is running and has models loaded.z&Failed to fetch models from server at zK. Check that:
1. The server is running
2. The server URL is correct
Error: )
aiohttpClientSessiongetraise_for_statusjsonlen
ValueErrorClientErrorJSONDecodeErrorRuntimeError)r   r   
models_urlsessionresponser    es          i/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/vllm/benchmarks/serve.pyget_first_model_from_serverr2   >   s      (((J$&&       '	{{:w{?? 	 	 	 	 	 	 	8))+++%]]__,,,,,,T>>c$v,&7&7!&;&;<?40$v,q/&2II		 	 	 	 	 	 	 	 	 	 	 	 	              %QH Q Q Q  	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 #T%9: 	 	 	   	   		                             s_   E
C= A3C+3C=C++
C5	5C=8C5	9C=<E
=D3D..D33E


EEc                   L    e Zd ZU dZeed<   eed<   eed<   eeef         ed<   dS )SpecDecodeMetricszCSpeculative decoding metrics from the server's Prometheus endpoint.
num_draftsnum_draft_tokensnum_accepted_tokensaccepted_per_posN)__name__
__module____qualname____doc__int__annotations__dict     r1   r4   r4   Y   sM         MMOOO38n$$$$$rA   r4   r.   c           
      ,  K   |  d}	 |                     |          4 d{V }|j        dk    r	 ddd          d{V  dS |                                 d{V }d}d}d}i }d}	|                    d          D ]}
|
                                }
|
r|
                    d          r/|
                    d          rbd	}	|
                                }|rIt          j        t                    5  d
|
v r&|t          t          |d                             z  }nd|
v r&|t          t          |d                             z  }nd|
v rd}||
v r|
                    |          t          |          z   }|
                    d|          }t          |
||                   }t          t          |d                             }|                     |d          |z   ||<   n)d|
v r%|t          t          |d                             z  }ddd           n# 1 swxY w Y   |	s	 ddd          d{V  dS t          ||||          cddd          d{V  S # 1 d{V swxY w Y   dS # t          j        t           j        f$ r Y dS w xY w)zFetch speculative decoding metrics from the server's Prometheus endpoint.

    Returns None if speculative decoding is not enabled or metrics are not available.
    z/metricsN   r   F
#zvllm:spec_decodeTr5   r6   num_accepted_tokens_per_posz
position=""r7   )r5   r6   r7   r8   )r%   statustextsplitstrip
startswith
contextlibsuppressr)   r=   floatindexr(   r4   r#   r*   asyncioTimeoutError)r   r.   metrics_urlr/   rJ   r5   r6   r7   r8   found_spec_decodelineparts	pos_labelstartendposvals                    r1   fetch_spec_decode_metricsr]   c   s3      '''K1;;{++ .	 .	 .	 .	 .	 .	 .	x#%%.	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 "((((((DJ "#/1 %

4(( M Mzz|| ts33 ??#566 M(,% JJLLE M'0<< M M+t33 *c%b	2B2B.C.C C

!3t!;!; 0CeBi8H8H4I4I I 0 0!>$!F!F,8	#,#4#4,0JJy,A,AC	NN,RE*.**S%*@*@C*-d59o*>*>C*-eE"I.>.>*?*?C(8(<(<S!(D(Ds(J %5S$9 "7$!>!> 3s5r;K;K7L7L L 3!M M M M M M M M M M M M M M M$ % O.	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	R %%!1$7!1	  S.	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	 .	^ !56   ttsq   I4 I!I4 B0I!4DHI!HI! H!I!)I4 <I!I4 !
I++I4 .I+/I4 4JJc                       e Zd ZdZdZdS )TaskType
generationpoolingN)r9   r:   r;   
GENERATIONPOOLINGr@   rA   r1   r_   r_      s        JGGGrA   r_   c                      e Zd ZU eed<   eed<   eed<   eed<   eed<   eed<   eed<   eed<   eed	<   eed
<   eed<   eeeef                  ed<   eed<   eed<   eed<   eeeef                  ed<   eed<   eed<   eed<   eeeef                  ed<   eed<   eed<   eed<   eeeef                  ed<   eed<   eed<   dS )BenchmarkMetrics	completedfailedtotal_inputtotal_outputrequest_throughputrequest_goodputoutput_throughputtotal_token_throughputmean_ttft_msmedian_ttft_msstd_ttft_mspercentiles_ttft_msmean_tpot_msmedian_tpot_msstd_tpot_mspercentiles_tpot_msmean_itl_msmedian_itl_ms
std_itl_mspercentiles_itl_msmean_e2el_msmedian_e2el_msstd_e2el_mspercentiles_e2el_msmax_output_tokens_per_smax_concurrent_requestsN)r9   r:   r;   r=   r>   rP   listtupler@   rA   r1   re   re      s~        NNNKKK!!!!eE5L12222eE5L12222U5%<01111 eE5L12222""""      rA   re   c                   j    e Zd ZU eed<   eed<   eed<   eed<   eed<   eed<   eed<   eed<   eed	<   d
S )EmbedBenchmarkMetricsrf   rg   rh   rj   rm   rz   r|   r{   r}   N)r9   r:   r;   r=   r>   rP   r@   rA   r1   r   r      sx         NNNKKK!!!!rA   r   ramp_up_strategy)linearexponentialramp_up_start_rpsramp_up_end_rpsrequest_indextotal_requestsrequest_ratec                     | rR|P|N|t          |dz
  d          z  }| dk    r||z
  |z  }||z   S | dk    r||z  }|||z  z  S t          d|            |S )N   r   r   zUnknown ramp-up strategy: )maxr)   )	r   r   r   r   r   r   progressincreaseratios	            r1   _get_current_request_rater      s     	N)' 3~'91#=#==x'''*;;xGH$x//..#&77E$x88L:JLLMMMrA         ?input_requests
burstinessc           	       K   |dk    sJ d| d            t          | t                    r$t          | t                    st          |           } t          |           }|dk    s
J d            g }g }t	          |           D ]\  }	}
t          ||||	||          }|dk    sJ d| d            |                    |           |t          d          k    r|                    d           k|t          d          k    r|                    d|z             d||z  z  }|                    t          j	        
                    ||	                     t          d
t          |                    D ]}||xx         ||d
z
           z  cc<   |*|d         dk    r||z  }||d         z  fd|D             }t          j                    }t	          |           D ]_\  }	}
||	         dk    rAt          j                    }|||	         z   |z
  }|dk    rt          j        |           d{V  |
||	         fW V  `dS )a  
    Asynchronously generates requests at a specified rate
    with OPTIONAL burstiness and OPTIONAL ramp-up strategy.

    Args:
        input_requests:
            A list of input requests, each represented as a SampleRequest.
        request_rate:
            The rate at which requests are generated (requests/s).
        burstiness (optional):
            The burstiness factor of the request generation.
            Only takes effect when request_rate is not inf.
            Default value is 1, which follows a Poisson process.
            Otherwise, the request intervals follow a gamma distribution.
            A lower burstiness value (0 < burstiness < 1) results
            in more bursty requests, while a higher burstiness value
            (burstiness > 1) results in a more uniform arrival of requests.
        ramp_up_strategy (optional):
            The ramp-up strategy. Can be "linear" or "exponential".
            If None, uses constant request rate (specified by request_rate).
        ramp_up_start_rps (optional):
            The starting request rate for ramp-up.
        ramp_up_end_rps (optional):
            The ending request rate for ramp-up.
    r   z4A positive burstiness factor is expected, but given .zNo requests provided.        z#Obtained non-positive request rate infr   )shapescaler   NrF   c                     g | ]}|z  S r@   r@   ).0delaynormalize_factors     r1   
<listcomp>zget_request.<locals>.<listcomp>D  s    CCCE,,CCCrA   )
isinstancer   r   r(   	enumerater   appendrP   nprandomgammarangetimerR   sleep)r   r   r   r   r   r   r   request_ratesdelay_tsr   requestcurrent_request_ratethetaitarget_total_delay_sstart_ts
current_tssleep_interval_sr   s                     @r1   get_requestr      s     B >>>LzLLL >> .(++ .J~t4T4T .n--((NA6 MH"+N";"; L Lw8 
  
 $c)))I2FIII *)) 	12225<<//OOA5<<'' OOC"667777/*<=E OOBIOO*EOJJKKKK 1c(mm$$ ' 'xA&HRLA$5$5  .</(2,>CCCC(CCCy{{H"+N";"; 4 4wM"Q&&J'(=*AAJN!##m$4555555555}]33333334 4rA   outputsdur_sselected_percentilesc                    d}d}d}g t          t          |                     D ]J}| |         j        r6                    | |         j                   |dz  }|| |         j        z  }E|dz  }K|dk    rt          j        dd           t          |||||z  ||z  t          j
        pd          dz  t          j        pd          dz  t          j        pd          dz  fd|D             	  	        }|S )	a  Calculate the metrics for the embedding requests.

    Args:
        outputs: The outputs of the requests.
        dur_s: The duration of the benchmark.
        selected_percentiles: The percentiles to select.

    Returns:
        The calculated benchmark metrics.
    r   r   YAll requests failed. This is likely due to a misconfiguration on the benchmark arguments.   
stacklevelr   c                 H    g | ]}|t          j        pd |          dz  fS r   r   r   
percentiler   pe2elss     r1   r   z4calculate_metrics_for_embeddings.<locals>.<listcomp>z  @     
 
 
9:Qejq!,,t34
 
 
rA   )	rf   rg   rh   rj   rm   rz   r|   r{   r}   )r   r(   successr   latency
prompt_lenwarningswarnr   r   meanstdmedian)	r   r   r   rh   rf   rg   r   metricsr   s	           @r1    calculate_metrics_for_embeddingsr   P  sM    KIFE3w<<    1: 	LL+,,,NI71:00KKaKFFA~~*	
 	
 	
 	

 $$u,*U2WUZa((4/F5:A&&-y!,,t3
 
 
 
>R
 
 
  G NrA   	tokenizergoodput_config_dictc           	      v  )*+, g }d}d}d}	g *g +g }
g ,g )t          t          |                    D ]0}||         j        r
||         j        }|s*t           |||         j        d          j                  }|                    |           || |         j        z  }d}|dk    r8||         j        ||         j	        z
  }||dz
  z  }+                    |           |
                    |           *||         j
        z  *,                    ||         j	                   )                    ||         j                   |dz  }|                    d           2|rg }g }d|v r8|                    ,           |                    |d         t          z             d|v r8|                    |
           |                    |d         t          z             d|v r8|                    )           |                    |d         t          z             t          | D ]0}t          d t          ||          D                       }|r|	dz  }	1|dk    rt          j        d	d
           d}d}d |D             }d |D             }t          |          dk    rFt!          d           t#          |dd                   D ]\  }}t!          d| d|j                     |rkt'          d |D                       }t)          d |D                       }t+          t-          j        ||z
                      dz   }t-          j        |          }t-          j        |          }t#          |          D ]\  }}|j        |j	        z   g}|d         }|j
        D ]} || z  }|                    |           |D ]4}!t+          |!|z
            }"d|"cxk    r|k     rn $||"xx         dz  cc<   5t+          |j        |z
            }#t+          |j        |j        z   |z
            }$t          |#|$dz             D ]}%||%xx         dz  cc<   t          |          dk    rBt5          t-          j        |                    }t+          t-          j        |                    }t6          rddl}&|&                                }'|'                    t-          j        t          |                    |d           |'                    t-          j        t          |                    |d           |'                                  nt!          d           tC          d9i d|dt          |          d|dtE          |          d||z  d|	|z  d tE          |          |z  d!|tE          |          z   |z  d"t-          j#        ,pd          d#z  d$t-          j$        ,pd          d#z  d%t-          j%        ,pd          d#z  d&,fd'|D             d(t-          j#        +pd          d#z  d)t-          j$        +pd          d#z  d*t-          j%        +pd          d#z  d++fd,|D             d-t-          j#        *pd          d#z  d.t-          j$        *pd          d#z  d/t-          j%        *pd          d#z  d0*fd1|D             d2t-          j#        )pd          d#z  d3t-          j$        )pd          d#z  d4t-          j%        )pd          d#z  d5)fd6|D             d7|d8|}(|(|fS ):a  Calculate the metrics for the benchmark.

    Args:
        input_requests: The input requests.
        outputs: The outputs of the requests.
        dur_s: The duration of the benchmark.
        tokenizer: The tokenizer to use.
        selected_percentiles: The percentiles to select.
        goodput_config_dict: The goodput configuration.

    Returns:
        A tuple of the benchmark metrics and the actual output lengths.
    r   F)add_special_tokensr   ttfttpote2elc                      g | ]\  }}||k    S r@   r@   )r   srs      r1   r   z%calculate_metrics.<locals>.<listcomp>  s     NNN$!QqAvNNNrA   r   r   r   r   c                      g | ]}|j         	|S r@   r   r   outputs     r1   r   z%calculate_metrics.<locals>.<listcomp>  s    IIIV&.I&IIIrA   c                      g | ]}|j         	|S r@   r   r   s     r1   r   z%calculate_metrics.<locals>.<listcomp>  s    III&.IfIIIrA   z>Failed requests during benchmark run detected (capping to 10):N
   zError : c              3   $   K   | ]}|j         V  d S N
start_timer   s     r1   	<genexpr>z$calculate_metrics.<locals>.<genexpr>  s%      PP6V.PPPPPPrA   c              3   4   K   | ]}|j         |j        z   V  d S r   )r   r   r   s     r1   r   z$calculate_metrics.<locals>.<genexpr>  s=       
 
39F.
 
 
 
 
 
rA   zOutput tokens per second)titlezConcurrent requests per secondz8tip: install termplotlib and gnuplot to plot the metricsrf   rg   rh   ri   rj   rk   rl   rm   rn   r   rp   ro   rq   c                 H    g | ]}|t          j        pd |          dz  fS r   r   )r   r   ttftss     r1   r   z%calculate_metrics.<locals>.<listcomp>3  r   rA   rr   rt   rs   ru   c                 H    g | ]}|t          j        pd |          dz  fS r   r   )r   r   tpotss     r1   r   z%calculate_metrics.<locals>.<listcomp>9  r   rA   rv   rx   rw   ry   c                 H    g | ]}|t          j        pd |          dz  fS r   r   )r   r   itlss     r1   r   z%calculate_metrics.<locals>.<listcomp>?  s@     
 
 
89Qdia++d23
 
 
rA   rz   r|   r{   r}   c                 H    g | ]}|t          j        pd |          dz  fS r   r   r   s     r1   r   z%calculate_metrics.<locals>.<listcomp>E  r   rA   r~   r   r@   )&r   r(   r   output_tokensgenerated_text	input_idsr   r   r   r   itl"MILLISECONDS_TO_SECONDS_CONVERSIONzipallr   r   printr   errorminr   r=   r   ceilzerosr   rP   TERM_PLOTLIB_AVAILABLEr   figureplotarangeshowre   sumr   r   r   )-r   r   r   r   r   r   actual_output_lensrh   rf   good_completed	all_tpotsr   
output_lenr   latency_minus_ttftvalid_metrics
slo_values
req_metricis_good_reqr~   r   successful_outputsfailed_outputserrmin_start_timemax_end_timeduration_secondstokens_per_secondconcurrent_requests_per_secondr   token_timescurrent_time	itl_value
token_timesecond_bucketrequest_start_secondrequest_end_secondsecondtplfigr   r   r   r   r   s-                                            @@@@r1   calculate_metricsr    s	   * %'KINDEIEE3w<<   ) )1: 	) 1J 
 !I
1e   

 %%j111>!,77KDA~~%,QZ%7'!*/%I")Z!^<T"""T"""GAJN"DLL)))LL+,,,NII%%a(((( $
(((  '''#F+.PP   (((  +++#F+.PP   (((  '''#F+.PP   }- 	$ 	$JNN#j*2M2MNNNOOK $!#A~~*	
 	
 	
 	
 " JIwIIIII7IIIN
>QNOOOss 344 	- 	-FAs+1++	++,,,, 9NPP=OPPPPP 
 
=O
 
 
 
 

 rw|n'DEEFFJH%566)+2B)C)C&"#566 	< 	<IAv ",v{:;K&q>L#Z 1 1		)""<0000 * : :
 #J$? @ @8888(888888%m4449444 $'v'8>'I#J#J !$"V^3~E" "   46H16LMM < <.v666!;6666<
  !!A%%&+BF3D,E,E&F&F#&)"&1O*P*P&Q&Q#! 	N%%%%**,,CHH	#/0011!0    
 HH	#<==>>.6    
 HHJJJJLMMM $ $ $)$>"""$  K$ +,,,	$
 %u,,$ '..$ 011E99$ !,c2D.E.E ENN$ WUZa((
 $ F5:A&&--$ y!,,t33$
 
 
 
>R
 
 
 
$  WUZa((4//!$" F5:A&&--#$$ y!,,t33%$&
 
 
 
>R
 
 
 
'$, GDIA&&---$. 6$)!$$t++/$0 i	**T111$2
 
 
 
=Q
 
 
 
3$8 WUZa((4//9$: F5:A&&--;$< y!,,t33=$>
 
 
 
>R
 
 
 
?$D !8 7E$F !8 7G$GL &&&rA   X  	task_typeendpoint_typeapi_urlmodel_id
model_namelogprobsdisable_tqdmnum_warmupsprofileselected_percentile_metrics
ignore_eosmax_concurrencylora_modulesextra_headers
extra_bodyready_check_timeout_secc                 l  PQRSTUVWK   	 t           |         Qn!# t          $ r t          d|           d w xY wt          j        |pd|pddddddd|v           }t          j        |dt          j        d	
                    Tt          d           |d         j        |d         j	        |d         j
        |d         j        f\  }}}}|Mt          |t                    s8t          |t                    rt          d |D                       s
J d            t!          |||||||||||          U|dk    rGt#          QUT|           d {V }|j        st          d|j                   t          d           nt          d           |dk    rt          d| d           |rd nt)          |
          V|rt+          j        |          nt/          j                    Wg } QTUVWfd}!t3          |          D ]3}"t+          j         |!                      }#|                     |#           4t+          j        |   d {V }"VV                                 t          d           t          d           r5t=          fdt3          t?          |                    D                       |rUt          d           t!          ||||dz   |||||||          }$ Q|$T           d {V }%|%j        rt          d           |
dk    rdnd }&|*t          d!| d"           t          d#| d$| d%           nt          d&|	            t          d'|
 d(|& d)           t          d*|            tA          |T           d {V }'|rd nt)          t?          |          
          }(|rt+          j        |          nt/          j                    SQSfd+})tC          j"                    }*g }+g },d,}-|?|=|}-|,                    |-tG          j$                    %                                d-           tM          ||	|
|||          2 3 d {V \  }.}/|mtO          |/          }0|0|-k    rXtG          j$                    %                                }1t3          |-d.z   |0d.z             D ]}2|,                    |2|1d-           |0}-|.j        |.j	        |.j
        |.j        |.j(        f\  }3}4}5}6}7||}9}8rtS                    }:|:|:}9}8t!          |8|9|3||4|5||6||||7/          };|+                    t+          j         |)|;T|(0                               6 t+          j        |+  d {V }<|(|(                                 tC          j"                    |*z
  }=tA          |T           d {V }>d }?|'|>|>j*        |'j*        z
  }@|>j+        |'j+        z
  }A|>j,        |'j,        z
  }Bg }C|@dk    rt[          t]          |'j/        0                                          t]          |>j/        0                                          z            }D|DD ]U}E|'j/        1                    |Ed          }F|>j/        1                    |E|F          }G|G|Fz
  }H|C                    |H|@z             V|Adk    r!|B|Az  d1z  }I|@dk    rd.|B|@z  z   nd2}J|@|A|B|I|J|Cd3}?| td          j3        k    rti          ||<|=|||4          \  P}Kntk          |<|=|5          Pd}Kt          d66                    d7d8d9:                     t          d;6                    d<Pj7                             t          d;6                    d=Pj8                             |#t          d;6                    d>|                     |	ts          d?          k    r#t          d@6                    dA|	                     t          d@6                    dB|=                     t          d;6                    dCPj:                             t          Ptv                    r(t          d;6                    dDPj<                             t          d@6                    dEPj=                             |r(t          d@6                    dFPj>                             t          Ptv                    rxt          d@6                    dGPj?                             t          d@6                    dHPj@                             t          d@6                    dIPjA                             t          d@6                    dJPjB                             t          Ptv                    ri dK|=dLPj7        dMPj8        dNPj:        dOPj<        dPPj=        dQ|rPj>        nd dRPj?        dSPjB        dTdU |<D             dV|KdWdX |<D             dYdZ |<D             d[d\ |<D             d]d^ |<D             d_d` |<D             daPj@        dbPjA        iRn2|=Pj7        Pj:        Pj=        PjB        dc |<D             dd |<D             deR|,r|,Rdf<   |?w|?dg         Rdh<   |?di         Rdj<   tO          |?dk                   Rdl<   tO          |?dm                   Rdn<   tO          |?do                   Rdp<   |?1                    dqg           Rdr<   dst          dtt          dut          fPRfdv}L| td          j3        k    r' |Ldwdxdy            |Ldzd{d|            |Ld}d~d            |Lddd           |?t          d66                    dd8d:                     t          d@6                    d|?dg                              t          d@6                    d|?di                              t          d;6                    dtO          |?dk                                        t          d;6                    dtO          |?dm                                        t          d;6                    dtO          |?do                                        |?1                    dqg           }M|MrNt          d           t          |M          D ]/\  }N}Ot          d@6                    d|N d|Od1z                       0t          d           |rPt          d           t!          |||dz   |||          }$ Q|$T           d {V }%|%j        rt          d           T                                 d {V  RS )NzUnknown backend: r   i,  T<   Fzhttps://)limitlimit_per_hostttl_dns_cacheuse_dns_cachekeepalive_timeoutenable_cleanup_closedforce_closessli`T  )total)	connector	trust_envtimeoutz*Starting initial single prompt test run...c              3   @   K   | ]}t          |t                    V  d S r   )r   r?   )r   items     r1   r   zbenchmark.<locals>.<genexpr>  s,      GGtJtT**GGGGGGrA   z-multi_modal_data must be a dict or list[dict])modelr!  promptr  r   r  r"  multi_modal_contentr'  r*  r+  )timeout_secondsz_Initial test run failed - Please make sure benchmark arguments are correctly specified. Error: zInitial test run completed.zSkipping endpoint ready check.zWarming up with z requests...c                     K   4 d {V               d {V cd d d           d {V  S # 1 d {V swxY w Y   d S Nrequest_func_inputr.   pbarr@   )request_funcr.   
test_inputwarmup_pbarwarmup_semaphores   r1   warmup_limited_request_funcz.benchmark.<locals>.warmup_limited_request_func  s     '        )\'17                                        3
= =zWarmup run completed.zStarting main benchmark run...c                 8    g | ]}t          j                  S r@   )r   choice)r   _r)  s     r1   r   zbenchmark.<locals>.<listcomp>  s#    MMMQV]<((MMMrA   zStarting profiler...z/start_profile)rD  r.   zProfiler startedr   zPoisson processzGamma distributionzTraffic ramp-up strategy: r   zWill increase RPS from z to z( RPS over the duration of the benchmark.zTraffic request rate: zBurstiness factor: z ()zMaximum request concurrency: c                    K   4 d {V   | ||           d {V cd d d           d {V  S # 1 d {V swxY w Y   d S rB  r@   )rD  r.   rE  rF  	semaphores      r1   limited_request_funcz'benchmark.<locals>.limited_request_func   s      	 	 	 	 	 	 	 	%#5wT        	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	rK  rF   )rps	timestampr   )r=  r!  r>  r  r   r  r"  r?  r'  r*  r+  
request_idrC  d   r   )r5   draft_tokensaccepted_tokensacceptance_rateacceptance_lengthper_position_acceptance_rates)r   r   r   r   r   r   )r   r   r   {s:{c}^{n}}z Serving Benchmark Result 2   =r   ncz{:<40} {:<10}zSuccessful requests:zFailed requests:zMaximum request concurrency:r   {:<40} {:<10.2f}zRequest rate configured (RPS):zBenchmark duration (s):zTotal input tokens:zTotal generated tokens:zRequest throughput (req/s):zRequest goodput (req/s):z Output token throughput (tok/s):z%Peak output token throughput (tok/s):zPeak concurrent requests:zTotal token throughput (tok/s):durationrf   rg   total_input_tokenstotal_output_tokensrj   rk   rl   rm   
input_lensc                     g | ]	}|j         
S r@   r   r   s     r1   r   zbenchmark.<locals>.<listcomp>      CCC6,CCCrA   output_lensr   c                     g | ]	}|j         
S r@   )r   r   s     r1   r   zbenchmark.<locals>.<listcomp>  s    888ffk888rA   r   c                     g | ]	}|j         
S r@   )r   r   s     r1   r   zbenchmark.<locals>.<listcomp>  s    666FVZ666rA   start_timesc                     g | ]	}|j         
S r@   r   r   s     r1   r   zbenchmark.<locals>.<listcomp>  s    DDD&F-DDDrA   generated_textsc                     g | ]	}|j         
S r@   )r   r   s     r1   r   zbenchmark.<locals>.<listcomp>  s    LLL& 5LLLrA   errorsc                     g | ]	}|j         
S r@   r   r   s     r1   r   zbenchmark.<locals>.<listcomp>      :::v|:::rA   r~   r   c                     g | ]	}|j         
S r@   rh  r   s     r1   r   zbenchmark.<locals>.<listcomp>  ri  rA   c                     g | ]	}|j         
S r@   rs  r   s     r1   r   zbenchmark.<locals>.<listcomp>  rt  rA   )rc  rf   rd  rj   rm   rf  rq  rps_change_eventsrY  spec_decode_acceptance_raterZ  spec_decode_acceptance_lengthr5   spec_decode_num_draftsrW  spec_decode_draft_tokensrX  spec_decode_accepted_tokensr[  )spec_decode_per_position_acceptance_ratesmetric_attribute_namemetric_namemetric_headerc                     | vrd S t          d                    |dd                     t          d                    d| dt          d|  d	                               t          d                    d
| dt          d|  d	                               t          d|  d	          d|  d	<   t          d|  d	          d|  d	<   t          d|  d	          d|  d	<   t          d|  d	          D ]y\  }}t          |          |k    rt	          t          |                    nt	          |          }t          d                    d| d| d|                     |d| d|  d	<   zd S )Nr\  r]  -r_  rb  zMean z (ms):mean__mszMedian median_std_percentiles_P r   rN  )r   formatgetattrr=   str)	r~  r  r  r   valuep_wordr   resultr&  s	         r1   process_one_metricz%benchmark.<locals>.process_one_metric  s,    !(CCCFm""]bC"@@AAA%%++++!C)>!C!C!CDD 	
 	
 	
 	%%-+---!E+@!E!E!EFF 	
 	
 	
 6=727776
 6
1,1112 8?949998
 8
3.3334 5<616665
 5
0+0001  )R8M)R)R)RSS 	D 	DHAu$'FFaKKSQ[[[SVVF$++,L,L,L,L,L,LeTTUUU>CF:v:: 5:::;;	D 	DrA   r   TTFTzTime to First Tokenr   TPOTz'Time per Output Token (excl. 1st token)r   ITLzInter-token Latencyr   E2ELzEnd-to-end LatencyzSpeculative Decodingr  zAcceptance rate (%):zAcceptance length:zDrafts:zDraft tokens:zAccepted tokens:zPer-position acceptance (%):z  Position :z2==================================================zStopping profiler...z/stop_profile)r=  r>  r  r   r  r"  zProfiler stopped)Er   KeyErrorr)   r#   TCPConnectorr$   ClientTimeoutr   r>  r   expected_output_lenmulti_modal_datar   r?   r   r   r   r   r   r   r
   rR   	SemaphorerN   nullcontextr   create_taskr   gathercloseiterr(   r]   r   perf_counterr   now	isoformatr   r=   rU  nextr5   r6   r7   sortedsetr8   keysr%   r_   rb   r  r   r  rf   rg   rP   rh   re   ri   rj   rk   rl   r~   r   rm   r  r   )Xr  r  r  r   r   r!  r   r   r"  r   r   r#  r$  r%  r&  r   r'  r   r(  r)  r*  r+  r   r   r   r,  r8  test_prompttest_prompt_lentest_output_lentest_mm_contenttest_outputwarmup_tasksrJ  rN  request_taskprofile_inputprofile_outputdistributionspec_decode_metrics_beforerE  rR  benchmark_start_timetasksrw  last_int_rpsr   r   current_int_rpsrT  rps_valr>  r   r  
mm_contentrU  req_model_idreq_model_namereq_lora_modulerD  r   benchmark_durationspec_decode_metrics_afterspec_decode_statsdelta_draftsdelta_draft_tokensdelta_acceptedper_pos_rates	positionsr[   
before_val	after_val	delta_posrY  rZ  r   r  per_posr   rater   rF  r  rQ  r.   rG  rH  rI  sX                 `    `                                                            @@@@@@@@r1   	benchmarkr  O  sH     8H*=9 H H H<]<<==4GH $"&+!"7"	 	 	I #%K888  G 

6777q q$q-q*	FBK/? 	ot,, 	  -- 	  GGGGGGG	 	  7 	  	
 """+#  J ""-3	
 
 
 
 
 
 
 
 
 " 	1.%+. .   /0000.///Q::::;;;*Gdd;0G0G0G *Go...')) 	
 	 	 	 	 	 	 	 	 	 {## 	. 	.A"./J/J/L/LMML----.,///////"%&&&	
*+++ 
MMMM%N8K8K2L2LMMM
 
  &$%%%(!//&& /!'!
 
 
  ,|,g 
  
  
 
 
 
 
 
 
 ! 	&$%%%(2c(9(9$$?SL#>+;>>>???I&7 I II I I	
 	
 	
 	

 	5|55666	
=

=
=l
=
=
=>>>	
;/
;
;<<<'@7'S'S!S!S!S!S!S!SD44TN0C0C%D%D%DD 	&/***#%%        ,.. "EL#(9(E(  #%\^^5577 	
 	
 	
 0;0 0 /
 /
 /
 /
 /
 /
 /
+g+ '!"677O--$LNN4466	$\A%57JKK W WG%,,W9-U-UVVVV.N'$B
>
J
J (0n 	L"<00O+:O.L-%!! *!'!!
 
 
 	$$'97QU   	
 	
 	
 	
S0` .5^U-C'C'C'C'C'C'CG

*,,/CC&?'&R&R R R R R R R/3!-2K2W%03M3XX 	 &6(9: 	
 &9(<= 	 &(!.?DDFFGG/@EEGGHHI I ! ? ?7HLLSRSTT
5FJJ 	 &
2	$$Y%=>>>>!!-0BBcIO5AA5E5EN\1113  + 2#1#2%61>! ! H'''&7)$!5 3'
 '
 '
### 3$!5
 
 

 	-

!=s

K
KLLL	/
 
 !79J
K
KLLL	/
 
 !3W^
D
DEEE"o$$%C_UUVVVuU||## ''(H,WWXXX	

#
#$=?Q
R
RSSS	/
 
 !68K
L
LMMM'+,, Wo$$%>@TUUVVV	!!)7+E	
 	
  
  
%%*G,C 	
 	
 	

 '+,, 
%%2G4M 	
 	
 	

 	%%79X 	
 	
 	

 	%%+W-L 	
 	
 	

 
!!-w/M	
 	
   '+,, 

*
*
 gn
 !'"5	

 "7#7
 !'"<
 :MWw66SW
  !:
 %g&D
 CC7CCC
 -
 88888
 66g666
 DDGDDD
 LLGLLL
  ::':::!
" &w'F#
$ &w'F%
 
, + *")"5")"<&-&DCC7CCC::':::
 
  8&7"#$0ABS0T,-2CDW2X./+./@/N+O+O'(-01B>1R-S-S)*03/01
 1
,- ?P>S>S+R?
 ?
:;%D"%D 	%D %D %D %D %D %D %D %D %DN H'''66+@AAA66+TUUU5%)>???vv';<<<$m""%;rS"IIJJJ%%&(9:K(L 	
 	
 	

 	%%$&78K&L 	
 	
 	

 	o$$Y4El4S0T0TUUVVV""%6~%F!G!G 	
 	
 	

 	"""C(9:K(L$M$M 	
 	
 	

 $''(GLL 	Q0111$W-- Q Q4(//0Ba0B0B0BD3JOOPPPP	(OOO &$%%%(.&&
 
 
  ,|,g 
  
  
 
 
 
 
 
 
 ! 	&$%%%
--//Ms    :Uc                    i }g d}| j         rtt          | j                   }|                                D ]K\  }}||vr&t          d| d| dt	          |           d          |dk     rt          d| d| d          L|S )	N)r   r   r   zInvalid metric name found, r   z4. The service level objective name should be one of z. r   zInvalid value found, z;. The service level objective value should be non-negative.)goodputparse_goodputitemsr)   r  )argsr   VALID_NAMESslo_nameslo_vals        r1   check_goodput_argsr  A  s    ***K| +DL99!4!:!:!<!< 	 	Hg{** ,( , ,g , ,;'', , ,  
 {{ $H $ $ $ $ $    rA   c                     i }	 | D ],}|                     d          \  }}t          |          ||<   -n'# t          $ r}t          j        d          |d }~ww xY w|S )Nr  zInvalid format found for service level objectives. Specify service level objectives for goodput as "KEY:VALUE" pairs, where the key is a metric name, and the value is a number in milliseconds.)rK   rP   r)   argparseArgumentTypeError)	slo_pairsr   slo_pairr  r  r  s         r1   r  r  W  s    
! 	; 	;H (s 3 3Hg,1'NN))	;    (&
 

 	 s   /4 
AAAr  results	file_namec                     g dg dt          | fdD             fdD                       }|r:t          j                            |          d          d}t	          ||           d S d S )N)ro   rn   rp   p99_ttft_msrr   rs   rt   p99_tpot_msrw   rv   rx   
p99_itl_ms)r   r   ro  rq  c                 ,    i | ]}|v ||         gS r@   r@   )r   kr  s     r1   
<dictcomp>z4save_to_pytorch_benchmark_format.<locals>.<dictcomp>}  s&    BBBQQ'\\WQZL\\\rA   c                 2    i | ]}|v|v
||         S r@   r@   )r   r  ignored_metricsr   r  s     r1   r  z4save_to_pytorch_benchmark_format.<locals>.<dictcomp>~  s>     
 
 
A_$<$< wqz$<$<$<rA   )r  r   
extra_infor   z.pytorch.json)r   ospathsplitextr   )r  r  r  
pt_recordspt_filer  r   s    `   @@r1    save_to_pytorch_benchmark_formatr  g  s      G  EDDO4BBBB'BBB
 
 
 
 
 

 
 
  J  +W%%i003BBBgz*****+ +rA   parserc           	      6   t          |            |                     dt          d d           |                     dt          dt          t	          j                              d           |                     dt          d d	           |                     d
t          d           |                     dt          d           |                     dt          dd           |                     dddd           |                     dt          d d           |                     dt          dd d           |                     dt          d d           |                     dt          d d            |                     d!t          d"#           |                     d$t          d%d&           |                     d'd()           |                     d*t          d d+           |                     d,t          t          d-          d.           |                     d/t          d0d1           |                     d2d(d34           |                     d5d(d64           |                     d7t          d8d9           |                     d:d(d;4           |                     d<d(d=4           |                     d>d(d?4           |                     d@d(dA4           |                     dBdddC           |                     dDt          d dE           |                     dFt          d dG           |                     dHd(dI4           |                     dJt          d dK           |                     dLt          dMdN           |                     dOdPddQR           |                     dSt          ddTt          j	                    j
        d dU          dVdW           |                     dX          }|                    dYt          d dZ           |                    d[t          d d\           |                    d]t          d d^           |                    d_t          d d`           |                    dat          d db           |                    dct          d dd           |                    det          d df           |                     dgt          d dh           |                     didPd djk           |                     dlt          d dmdngdo           |                     dpt          d dq           |                     drt          d ds           |                     dtt          d8du           |                     dvdwt          j        d x           d S )yNz--labelzrThe label (prefix) of the benchmark results. If not specified, the value of '--backend' will be used as the label.)typedefaulthelpz	--backendopenaiz9The type of backend or endpoint to use for the benchmark.)r  r  choicesr  z
--base-urlz7Server or API base url if not using http host and port.z--hostz	127.0.0.1)r  r  z--porti@  z
--endpointz/v1/completionszAPI endpoint.z--headerz	KEY=VALUE*zKey-value pairs (e.g, --header x-additional-info=0.3.3) for headers to be passed with each request. These headers override per backend constants and values set via environment variable, and will be overridden by other arguments (such as request ids).)metavarnargsr  z--max-concurrencya  Maximum number of concurrent requests. This can be used to help simulate an environment where a higher level component is enforcing a maximum number of concurrent requests. While the --request-rate argument controls the rate at which requests are initiated, this argument will control how many are actually allowed to execute at a time. This means that when used in combination, the actual request rate may be lower than specified with --request-rate, if the server is not processing requests fast enough to keep up.z--modelFzfName of the model. If not specified, will fetch the first model from the server's /v1/models endpoint.)r  requiredr  r  z--input-lenzGeneral input length for datasets. Maps to dataset-specific input length arguments (e.g., --random-input-len, --sonnet-input-len). If not specified, uses dataset defaults.z--output-lenzGeneral output length for datasets. Maps to dataset-specific output length arguments (e.g., --random-output-len, --sonnet-output-len). If not specified, uses dataset defaults.z--tokenizerzBName or path of the tokenizer, if not using the default tokenizer.)r  r  z--tokenizer-modeautoa  Tokenizer mode:

        - "auto" will use the tokenizer from `mistral_common` for Mistral models
        if available, otherwise it will use the "hf" tokenizer.

        - "hf" will use the fast tokenizer if available.

        - "slow" will always use the slow tokenizer.

        - "mistral" will always use the tokenizer from `mistral_common`.

        - "deepseek_v32" will always use the tokenizer from `deepseek_v32`.

        - Other custom values can be supported via plugins.z--use-beam-search
store_true)actionz
--logprobsa  Number of logprobs-per-token to compute & return as part of the request. If unspecified, then either (1) if beam search is disabled, no logprobs are computed & a single dummy logprob is returned for each token; or (2) if beam search is enabled 1 logprob per token is computedz--request-rater   zNumber of requests per second. If this is inf, then all the requests are sent at time 0. Otherwise, we use Poisson process or gamma distribution to synthesize the request arrival times.z--burstinessr   au  Burstiness factor of the request generation. Only take effect when request_rate is not inf. Default value is 1, which follows Poisson process. Otherwise, the request intervals follow a gamma distribution. A lower burstiness value (0 < burstiness < 1) results in more bursty requests. A higher burstiness value (burstiness > 1) results in a more uniform arrival of requests.z--trust-remote-codez"Trust remote code from huggingface)r  r  z--disable-tqdmz%Specify to disable tqdm progress bar.z--num-warmupsr   zNumber of warmup requests.z	--profilezEUse vLLM Profiling. --profiler-config must be provided on the server.z--save-resultz0Specify to save benchmark results to a json filez--save-detailedzoWhen saving the results, whether to include per request information such as response, error, ttfts, tpots, etc.z--append-resultz6Append the benchmark result to the existing json file.z
--metadatazKey-value pairs (e.g, --metadata version=0.3.3 tp=1) for metadata of this run to be saved in the result JSON file for record keeping purposes.z--result-dirznSpecify directory to save benchmark json results.If not specified, results are saved in the current directory.z--result-filenamezSpecify the filename to save benchmark json results.If not specified, results will be saved in {label}-{args.request_rate}qps-{base_model_id}-{current_dt}.json format.z--ignore-eoszuSet ignore_eos flag when sending the benchmark request.Warning: ignore_eos is not supported in deepspeed_mii and tgi.z--percentile-metricsa  Comma-separated list of selected metrics to report percentiles. This argument specifies the metrics to report percentiles. Allowed metric names are "ttft", "tpot", "itl", "e2el". If not specified, defaults to "ttft,tpot,itl" for generative models and "e2el" for pooling models.z--metric-percentiles99zComma-separated list of percentiles for selected metrics. To report 25-th, 50-th, and 75-th percentiles, use "25,50,75". Default value is "99".Use "--percentile-metrics" to select metrics.z	--goodput+a  Specify service level objectives for goodput as "KEY:VALUE" pairs, where the key is a metric name, and the value is in milliseconds. Multiple "KEY:VALUE" pairs can be provided, separated by spaces. Allowed request level metric names are "ttft", "tpot", "e2el". For more context on the definition of goodput, refer to DistServe paper: https://arxiv.org/pdf/2401.09670 and the blog: https://hao-ai-lab.github.io/blogs/distserve)r  r  r  z--request-id-prefixzbench-   r  z!Specify the prefix of request id.zsampling parametersz--top-pzHTop-p sampling parameter. Only has effect on openai-compatible backends.z--top-kzHTop-k sampling parameter. Only has effect on openai-compatible backends.z--min-pzHMin-p sampling parameter. Only has effect on openai-compatible backends.z--temperaturezNTemperature sampling parameter. Only has effect on openai-compatible backends.z--frequency-penaltyzTFrequency penalty sampling parameter. Only has effect on openai-compatible backends.z--presence-penaltyzSPresence penalty sampling parameter. Only has effect on openai-compatible backends.z--repetition-penaltyzURepetition penalty sampling parameter. Only has effect on openai-compatible backends.z--served-model-namezmThe model name used in the API. If not specified, the model name will be the same as the `--model` argument. z--lora-moduleszA subset of LoRA module names passed in when launching the server. For each request, the script chooses a LoRA module at random.)r  r  r  z--ramp-up-strategyr   r   zThe ramp-up strategy. This would be used to ramp up the request rate from initial RPS to final RPS rate (specified by --ramp-up-start-rps and --ramp-up-end-rps.) over the duration of the benchmark.z--ramp-up-start-rpszcThe starting request rate for ramp-up (RPS). Needs to be specified when --ramp-up-strategy is used.z--ramp-up-end-rpszaThe ending request rate for ramp-up (RPS). Needs to be specified when --ramp-up-strategy is used.z--ready-check-timeout-secziMaximum time to wait for the endpoint to become ready in seconds. Ready check will be skipped by default.z--extra-bodyzA JSON string representing extra body parameters to include in each request.Example: '{"chat_template_kwargs":{"enable_thinking":false}}')r  r  r  )r   add_argumentr  r   r   r  r=   rP   uuiduuid4hexadd_argument_groupr'   loads)r  sampling_groups     r1   add_cli_argsr    s+   v
>	     (-//00H     F	     sK@@@
sD999
!	     G	     K	     1     3	     3	     Q    
 ?	     +LAAA
9     e3	     9	     1    
 4    
 )	     T    
 ?    
 B     E    
 '	     H	     	     I     )	  	 	 	 8	     E	     0)"1"-0000     ../DEENW	      W	      W	      &	      &	      &	      &	      +	     2	     =)B  	 	 	 A	     A	     #>	     J Z      rA   c                 D    t          j        t          |                     S r   )rR   run
main_async)r  s    r1   mainr    s    ;z$''(((rA   c                   K   t          |            t          j        | j                   t          j                            | j                   | j        | j        t          d          k    rt          d          | j        | j	        t          d          | j        dk     s| j	        dk     rt          d          | j        | j	        k    rt          d          | j        dk    r| j        dk    rt          d          | j
        }| j        | j         | j         }| j         }n+t          | j        | j                  }d	| | j         }d	| }d }| j        rji }| j        D ]`}d
|v rL|                    d
d          }|d                                         ||d                                         <   Rt          d          | j        >t          d           t)          ||           d {V \  }}	t          d| d|	            n| j        }| j        }	| j        | j        n|	}
| j        }t1          |
|| j                  }| j        t          d          | j        | j        | _        | j        | _        | j        T| j        | _        | j        | _         | j        | _!        | j        | _"        | j        | _#        | j        | _$        | j        | _%        | j        dv r| j&        tN          v rd| _(        tS          | |          }tU          |           }| j&        }d|v sd|v rtV          j,        ntV          j-        }|tV          j-        k    r~d | j.        | j/        | j0        | j1        | j2        | j3        | j4        d5                                D             }|r| j&        tN          vrt          d          d|vrt          d           d}ni }d}| j6        pi }i ||}| j7        p|}tq                       ts          dPi d|d|d|d |d!|	d"|d#|d$|d%| j:        d&| j        d'| j;        d(| j<        d)| j=        d*| j>        d+|                    d,          d-d. | j?                            d,          D             d/| j(        d0|d1| j@        d2| jA        d3|d4|d5| j        d6| j        d7| j	        d8| jB         d {V }i }t          jD                    E                    d9          }||d:<   | j&        |d<   | j&        |d;<   ||d<<   |	|d!<   |
|d=<   | jF        |d><   | jG        rh| jG        D ]`}d
|v rL|                    d
d          }|d                                         ||d                                         <   Rt          d?          | j        t          d          k     r| j        nd|d&<   | j;        |d'<   | j@        |d1<   | j        | j        |d5<   | j        |d6<   | j	        |d7<   i ||}| jH        sd@D ]}||v r||= ||v r||= | jI        s| jJ        r]|	                    dA          dB         }| j@        
dC| j@         ndD}|p| j&        }| j        '| dE| j         dF| j         dG| j	         dH| dF| dF| dI}n| dF| j         dH| dF| dF| dI
}| jK        r| jK        }| jL        r@t          jN        | jL        dJ           t          jO        P                    | jL        |          }t          || jJ        rdKndLdMN          5 }| jJ        r-|R                                dk    r|S                    dO           t          jU        ||           d d d            n# 1 swxY w Y   t          | ||           |S )QNr   zWhen using ramp-up, do not specify --request-rate. The request rate will be controlled by ramp-up parameters. Please remove the --request-rate argument.z_When using --ramp-up-strategy, both --ramp-up-start-rps and --ramp-up-end-rps must be specifiedr   z.Ramp-up start and end RPS must be non-negativez+Ramp-up start RPS must be less than end RPSr   z3For exponential ramp-up, the start RPS cannot be 0.zhttp://r^  r   z3Invalid header format. Please use KEY=VALUE format.z8Model not specified, fetching first model from server...zFirst model name: z, first model id: )tokenizer_modetrust_remote_codezSPlease specify '--dataset-name' and the corresponding '--dataset-path' if required.)r   z	random-mmT
embeddingsrerankc                     i | ]
\  }}|||S r   r@   )r   r  vs      r1   r  zmain_async.<locals>.<dictcomp>O  s/     
 
 
1 } q }}rA   )top_ptop_kmin_ptemperaturefrequency_penaltypresence_penaltyrepetition_penaltyzESampling parameters are only supported by openai-compatible backends.r  zWARNING: vllm bench serve no longer sets temperature==0 (greedy) in requests by default. The default will be determined on the server side and can be model/API specific. For the old behavior, include --temperature=0.zttft,tpot,itlr   r  r  r  r   r   r!  r   r   r"  r   r   r#  r$  r%  r&  ,r   c                 ,    g | ]}t          |          S r@   )rP   )r   r   s     r1   r   zmain_async.<locals>.<listcomp>  s    SSS1eAhhSSSrA   r'  r   r(  r)  r*  r+  r   r   r   r,  z%Y%m%d-%H%M%Sdatebackendlabeltokenizer_idnum_promptsz5Invalid metadata format. Please use KEY=VALUE format.)rf  rj  rm  r   r   ro  rq  /rF   z-concurrency z	-ramp-up-r  zqps-qpsz.json)exist_okza+wzutf-8)modeencodingrD   r@   )Wr   r   seedr   r   r   rP   r)   r   r   r  r   endpointr   hostportheaderrK   rL   r=  r2   served_model_namer   r  r   r	  dataset_name	input_lenrandom_input_lensonnet_input_lenr  random_output_lensonnet_output_lensharegpt_output_lencustom_output_lenhf_output_lenspec_bench_output_lenprefix_repetition_output_lenr  r   r'  r   r  r_   rc   rb   r  r  r  r  r  r  r  r  r+  percentile_metricsr   r  r"  r   r#  r$  r%  metric_percentilesr(  r)  r,  r   r  strftimer  metadatasave_detailedsave_resultappend_resultresult_filename
result_dirr  makedirsr  joinopentellwriter'   dumpr  )r  r  r  r   	host_portr   r<  kvstringr!  r   r  r  r   r   r   r  r  sampling_paramsdefault_percentile_metricsr+  r4  benchmark_resultresult_json
current_dtfieldbase_model_idmax_concurrency_strr  outfiles                                r1   r  r    st
     	$KKK
K	INN49 (e,,=  
 !)T-A-I6   !A%%)=)A)AMNNN!D$888JKKK M11d6LPQ6Q6QRSSSJE} ]3DM33m%"49di88	6I6t}66(Y(( G{ XK 	X 	XDd{{::c1--/7{/@/@/B/B))++,, !VWWW zHIII%@7%S%SSSSSSS
HK:KKKKLLLL+
:%)^%?4>>XL(N%0  I  ,
 
 	
 ~! $ $"!%!%#'? !%!_%)_",0O)
 	444L666 !y11N,T22lG 7""h'&9&9 	   H'''
 
 #/%)%;$($9&*&=  egg
 
 
  	t|3MMMW   //A   &5""%+"&BJ2O2z2J"5S9S &   )g  	
  : ) &~  && ?? && $$  %7$<$<S$A$A$A  TS0G0M0Mc0R0RSSSS!" ??#$ 0/%& ,,'( &&)* g+, :-. ../0 0012 ,,34 !% < <5      < #%K ((99J$K#'<K !\K	 K&K
".K!%!1K } M 	 	Dd{{::c1--3;A;3D3D3F3FHQK--//00 K   ".u==5  !%K%)%9K!"(*.*?&'+/+A'()-)=%& 6[5$45K ,
 	, 	,E ##&((($U+  G4- G s++B/ #/ 24/111 	
 % ,   p  p4+@  p  p4CY  p  p_c_s  p  p  yL  p  p  O\  p  p  _i  p  p  pII pp4#4pp9Lpp}pp_ipppI 	-,I? 	AK$7777T_i@@ID$6?DDC'
 
 
 	,! $gllnn&9&9d###Ik7+++	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	){IFFFs   	A
]]#&]#r   )r   NNN)NNNr  )Rr<   r  rR   rN   importlib.util	importlibr'   r  r   shutilr   r  r   collections.abcr   r   dataclassesr   r   enumr   typingr   r	   r#   numpyr   tqdm.asyncior
   vllm.benchmarks.datasetsr   r   r   )vllm.benchmarks.lib.endpoint_request_funcr   r   r   r   !vllm.benchmarks.lib.ready_checkerr   vllm.benchmarks.lib.utilsr   r   vllm.tokenizersr   r   vllm.utils.gc_utilsr   vllm.utils.network_utilsr   r   util	find_specwhichr   r  r?   r   r2   r4   r$   r]   r_   re   r   r=   rP   r   r   r   r   r  boolr  r  r  	Namespacer  ArgumentParserr  r  r  r@   rA   r1   <module>rd     s   $            				      4 4 4 4 4 4 4 4 ! ! ! ! ! !                                S S S S S S S S S S            @ ? ? ? ? ? X X X X X X X X 8 8 8 8 8 8 8 8 . . . . . . 3 3 3 3 3 3%) "#.22=AAM FL4'  +/  4K
38_   6 % % % % % % % %99#199 9 9 9x    t   
 ! ! ! ! ! ! ! !B 	 	 	 	 	 	 	 	56=Tz 4Z 	
      8 @D$("&a4 a4'a4a4 a4 56=	a4
 Tza4 4Za4 E-./56a4 a4 a4 a4H.#$.. u+. 	. . . .bK''K'#$K' K' 	K'
 u+K' c5j)K' T#Y&'K' K' K' K'J AE$("&#&5o ooo o 	o
 o o o 'o Djo o o o o o "&co  u+!o" #o$ c5j)%o& 4Z'o( 3-$&)o* $;+o, t-o. 56=/o0 Tz1o2 4Z3o4 !5o o o od  ,    +

 +'+CH~ +BE +	 +  +  +  +FU0 U U U Up
)x! )d38n ) ) ) )A8- A$sCx. A A A A A ArA   