okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
1be32e9c7
main
1"""GET /metrics in the Prometheus text format, with vLLM's metric names, so the dashboards and alerts written for a 2vLLM server read a Strata server unchanged. Everything comes from the server's own record (Service.metrics(), the 3same dict the JSON /metrics returns) plus three latency histograms observed when a request finishes. 4 5What vLLM has no name for is the JSON's own facts under `strata:`, named after the JSON's keys (live.tok_s -> 6strata:live_tok_s, totals.decode_ms -> strata:totals_decode_seconds_total, hardware.gpu_util -> strata:gpu_util), so 7the two formats say the same thing and a panel can be moved from the Monitor tab to Grafana by its key.""" 8import threading 9 10# vLLM's buckets for the request latencies (seconds) 11BUCKETS = (0.001 ,0.005 ,0.01 ,0.02 ,0.04 ,0.06 ,0.08 ,0.1 ,0.25 ,0.5 ,0.75 ,1.0 ,2.5 ,5.0 ,7.5 ,10.0 ,20.0 ,40.0 , 1280.0 ,160.0 ,640.0 ,2560.0 ) 13CONTENT_TYPE = "text/plain; version=0.0.4; charset=utf-8" 14 15 16def wants_prometheus (accept :str ,query :str )-> bool : 17"""Prometheus asks with Accept: text/plain or application/openmetrics-text; a person can add ?format=prometheus. 18Anything else (the Monitor tab, curl without a header) keeps the JSON.""" 19return "format=prometheus" in (query or "" )or "openmetrics" in (accept or "" )or "text/plain" in (accept or "" ) 20 21 22class Histogram : 23def __init__ (self ): 24self .counts = [0 ]* len (BUCKETS ) 25self .sum = 0.0 26self .n = 0 27 28def observe (self ,v :float ,times :int = 1 ): 29if v is None or times <= 0 : 30return 31for i ,b in enumerate (BUCKETS ): 32if v <= b : 33self .counts [i ]+= times 34self .sum += v * times 35self .n += times 36 37 38class Latencies : 39"""Time to first token, the time between tokens and the whole request, per finished request.""" 40 41def __init__ (self ): 42self .lock = threading .Lock () 43self .ttft ,self .itl ,self .e2e = Histogram (),Histogram (),Histogram () 44 45def observe (self ,ttft_s ,output_tokens ,decode_s ,total_s ): 46with self .lock : 47self .ttft .observe (ttft_s ) 48if output_tokens and output_tokens > 1 and decode_s : 49# the mean gap, once per gap: the engine reports the decode time, not each token's 50self .itl .observe (decode_s / (output_tokens - 1 ),output_tokens - 1 ) 51self .e2e .observe (total_s ) 52 53def snapshot (self ): 54with self .lock : 55return {k : (list (h .counts ),h .sum ,h .n )for k ,h in 56 (("ttft" ,self .ttft ), ("itl" ,self .itl ), ("e2e" ,self .e2e ))} 57 58 59def _num (v ,default = 0 ): 60return v if isinstance (v , (int ,float ))and not isinstance (v ,bool )else default 61 62 63def render (m :dict ,lat :dict )-> str : 64"""The text for one scrape. `m` is Service.metrics(), `lat` Latencies.snapshot().""" 65model = str ((m .get ("engine" )or {}).get ("model" )or "strata" ).replace ("\\" ,"\\\\" ).replace ('"' ,'\\"' ) 66lab = f'model_name=" { model } "' 67live ,totals = m .get ("live" )or {},m .get ("totals" )or {} 68out = [] 69 70def metric (name ,kind ,help_ ,value ): 71out .append (f"# HELP { name } { help_ } \n# TYPE { name } { kind } \n { name } {{ { lab } }} { value } " ) 72 73busy = live .get ("state" )in ("reading" ,"generating" ) 74ctx = _num ((m .get ("engine" )or {}).get ("max_context" ),0 ) 75used = _num (live .get ("prompt_tokens" ))+ _num (live .get ("generated" ))if busy else 0 76# "parallel": live.running / live.waiting count the requests together (waiting: for a slot or the control lines) 77metric ("vllm:num_requests_running" ,"gauge" ,"Requests reading their prompt or generating." , 78_num (live .get ("running" ),int (busy ))) 79metric ("vllm:num_requests_waiting" ,"gauge" ,"Requests waiting for their turn." , 80_num (live .get ("queued" ))+ _num (live .get ("waiting" ))) 81metric ("vllm:kv_cache_usage_perc" ,"gauge" ,"The running request's share of the context (1 = full)." , 82round (min (1.0 ,used / ctx ),4 )if ctx else 0 ) 83metric ("vllm:prompt_tokens_total" ,"counter" ,"Prompt tokens of the finished requests." , 84_num (totals .get ("prompt_tokens" ))) 85metric ("vllm:generation_tokens_total" ,"counter" ,"Generated tokens." ,_num (totals .get ("output_tokens" ))) 86metric ("vllm:request_success_total" ,"counter" ,"Finished requests." ,_num (totals .get ("requests" ))) 87metric ("vllm:prefix_cache_queries_total" ,"counter" ,"Prompt tokens looked up in the prompt cache." , 88_num (totals .get ("prompt_tokens" ))) 89metric ("vllm:prefix_cache_hits_total" ,"counter" ,"Prompt tokens the prompt cache already held." , 90_num (totals .get ("reused" ))) 91metric ("vllm:spec_decode_num_draft_tokens_total" ,"counter" ,"MTP draft tokens offered." , 92_num (totals .get ("drafts_offered" ))) 93metric ("vllm:spec_decode_num_accepted_tokens_total" ,"counter" ,"MTP draft tokens accepted." , 94_num (totals .get ("drafts_accepted" ))) 95metric ("vllm:num_preemptions_total" ,"counter" ,"Preempted requests (Strata does not preempt)." ,0 ) 96for name ,key ,help_ in (("vllm:time_to_first_token_seconds" ,"ttft" ,"Time to the first token." ), 97 ("vllm:inter_token_latency_seconds" ,"itl" ,"Time between two tokens." ), 98 ("vllm:e2e_request_latency_seconds" ,"e2e" ,"A request from start to end." )): 99counts ,total ,n = lat [key ] 100out .append (f"# HELP { name } { help_ } \n# TYPE { name } histogram" ) 101for b ,c in zip (BUCKETS ,counts ): 102out .append (f' { name } _bucket{{ { lab } ,le=" { b } "}} { c } ' ) 103out .append (f' { name } _bucket{{ { lab } ,le="+Inf"}} { n } ' ) 104out .append (f" { name } _sum{{ { lab } }} { round ( total , 6 ) } \n { name } _count{{ { lab } }} { n } " ) 105strata (m ,out ,lab ) 106return "\n" .join (out )+ "\n" 107 108 109def strata (m :dict ,out :list ,lab :str ): 110"""The JSON's facts vLLM has no name for, under `strata:` and the JSON's key.""" 111live ,totals = m .get ("live" )or {},m .get ("totals" )or {} 112hw ,eng = m .get ("hardware" )or {},m .get ("engine" )or {} 113reqs = m .get ("requests" )or [] 114 115typed = set () 116 117def metric (name ,kind ,help_ ,value ,labels = "" ): 118if not isinstance (value , (int ,float ))or isinstance (value ,bool ): 119return # unknown here (no GPU telemetry, an older engine): no sample 120if name not in typed :# one HELP / TYPE per family, before its first sample 121typed .add (name ) 122out .append (f"# HELP strata: { name } { help_ } \n# TYPE strata: { name } { kind } " ) 123out .append (f"strata: { name } {{ { lab } { labels } }} { value } " ) 124 125for state in ("unloaded" ,"idle" ,"reading" ,"generating" ): 126metric ("live_state" ,"gauge" ,"1 for what the engine is doing (live.state)." ,int (live .get ("state" )== state ), 127f',state=" { state } "' ) 128metric ("live_tok_s" ,"gauge" ,"Decode rate over the last seconds (live.tok_s)." ,live .get ("tok_s" )or 0 ) 129metric ("live_prefill_tok_s_mean" ,"gauge" ,"Prompt reading rate of the running request (live.prefill_tok_s_mean)." , 130live .get ("prefill_tok_s_mean" )or 0 ) 131metric ("live_prompt_read" ,"gauge" ,"Prompt tokens read so far by the running request (live.prompt_read)." , 132live .get ("prompt_read" )or 0 ) 133for state in ("idle" ,"reading" ,"generating" ): 134slots = live .get ("slots" ) 135if isinstance (slots ,list )and slots : 136metric ("live_slots" ,"gauge" ,"The batch slots in each state (live.slots)." , 137sum (1 for x in slots if isinstance (x ,dict )and x .get ("state" )== state ),f',state=" { state } "' ) 138metric ("engine_max_context" ,"gauge" ,"The engine's context (engine.max_context)." ,eng .get ("max_context" )) 139metric ("totals_prompt_seconds_total" ,"counter" ,"Time spent reading prompts (totals.prompt_ms)." , 140round ((totals .get ("prompt_ms" )or 0 )/ 1000 ,3 )) 141metric ("totals_decode_seconds_total" ,"counter" ,"Time spent generating (totals.decode_ms)." , 142round ((totals .get ("decode_ms" )or 0 )/ 1000 ,3 )) 143last = reqs [0 ]if reqs else {} 144metric ("last_hit_rate" ,"gauge" ,"The last request's expert cache hit rate (requests[0].hit_rate)." , 145last .get ("hit_rate" )) 146metric ("last_decode_tok_s" ,"gauge" ,"The last request's decode rate (requests[0].decode_tok_s)." , 147last .get ("decode_tok_s" )) 148gpus = hw .get ("gpus" )or ([{"index" :0 ,"util" :hw .get ("gpu_util" ),"mem_used" :hw .get ("gpu_mem_used" ), 149"mem_total" :hw .get ("gpu_mem_total" ),"temp" :hw .get ("gpu_temp" ), 150"power" :hw .get ("gpu_power" )}]if hw .get ("gpu_util" )is not None else []) 151for name ,key ,help_ in (("gpu_util" ,"util" ,"GPU busy, percent (hardware.gpu_util)." ), 152 ("gpu_mem_used_bytes" ,"mem_used" ,"GPU memory in use (hardware.gpu_mem_used)." ), 153 ("gpu_mem_total_bytes" ,"mem_total" ,"GPU memory (hardware.gpu_mem_total)." ), 154 ("gpu_temp_celsius" ,"temp" ,"GPU temperature (hardware.gpu_temp)." ), 155 ("gpu_power_watts" ,"power" ,"GPU power draw (hardware.gpu_power)." )): 156for g in gpus :# a family's samples together, one per card 157metric (name ,"gauge" ,help_ ,g .get (key ),f',gpu=" { g . get ( "index" ) } "' ) 158metric ("cpu" ,"gauge" ,"CPU busy, percent (hardware.cpu)." ,hw .get ("cpu" )) 159metric ("ram_used_bytes" ,"gauge" ,"RAM in use (hardware.ram_used)." ,hw .get ("ram_used" )) 160metric ("ram_total_bytes" ,"gauge" ,"RAM (hardware.ram_total)." ,hw .get ("ram_total" ))