okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
53623e56f
main
1#!/usr/bin/env python3 2"""Замер параллельности Strata: сколько запросов одновременно и что с скоростью. 3 4Нужен для проверки `"parallel": N` / `--batch N` / `--batch-mtp` (docs/BATCHING.md): 5штатный strata-bench.py измеряет один запрос, а batching меняет именно картину 6нескольких клиентов. Здесь два режима: 7 8solo — по одному запросу (опора: что должно остаться на одном клиенте) 9conc — N запросов одновременно (2, 3, 4): что получает каждый и что — сервер в целом 10 11Каждый запрос содержит случайную метку -> кэш префиксов не переиспользуется. 12Скорость считаем из таймингов движка (поле timings в ответе без стриминга), 13TTFT и ожидание в очереди — из стриминга. Это два прохода на каждый размер: 14движковые тайминги и клиентские задержки в одном ответе не появляются. 15 16usage: strata-conc-bench.py [--levels 1,2,3,4] [--prompt-tokens 8000] [--max-tokens 256] 17[--repeats 2] [--json out.json] [--label TEXT] 18""" 19import argparse 20import datetime 21import json 22import os 23import random 24import re 25import statistics 26import string 27import subprocess 28import sys 29import threading 30import time 31import urllib .request 32 33REPO = os .environ .get ("STRATA_REPO" ,"/home/dgbox/Strata" ) 34CFG = os .environ .get ("STRATA_CFG" ,REPO + "/strata-200k.json" ) 35PORT = int (os .environ .get ("STRATA_PORT" ,"8080" )) 36BASE = f"http://127.0.0.1: { PORT } " 37 38FILLERS = [ 39"В документе описывается модуль разбора конфигурации: он читает список секций, " 40"проверяет обязательные поля и собирает структуру настроек, которую дальше использует планировщик." , 41"Далее разбирается обработка ошибок: сбой на одной секции не должен останавливать остальные, " 42"поэтому парсер собирает список замечаний и возвращает его вместе с частично прочитанными настройками." , 43"Отдельно описан кэш: ключом служит хэш секции, запись живёт до изменения исходного файла, " 44"а при несовпадении версии запись отбрасывается и секция читается заново." , 45] 46 47 48def cfg_value (key ): 49try : 50with open (CFG ,encoding = "utf-8" )as f : 51c = json .load (f ) 52except Exception : 53return None 54return c .get (key ) 55 56 57def api_key (): 58return cfg_value ("api_key" )or "" 59 60 61def server_cmdline (): 62"""Аргументы движка, с которыми он сейчас запущен (для провенанса).""" 63try : 64out = subprocess .run (["pgrep" ,"-f" ,"engine/strata --serve" ],capture_output = True ,text = True ).stdout .split () 65for pid in out [:1 ]: 66cmd = open (f"/proc/ { pid } /cmdline" ,"rb" ).read ().decode ().split ("\0" ) 67return " " .join (x for x in cmd if x ) 68except Exception : 69pass 70return "" 71 72 73def engine_version (): 74try : 75req = urllib .request .Request (BASE + "/props" ,headers = {"Authorization" :f"Bearer { api_key () } " }) 76with urllib .request .urlopen (req ,timeout = 15 )as r : 77return json .load (r ).get ("build_info" ) 78except Exception : 79return None 80 81 82def batch_slots (): 83"""Сколько слотов движок реально открыл (concurrency.serving из /v1/status).""" 84for path in ("/v1/status" ,"/metrics" ): 85try : 86req = urllib .request .Request (BASE + path ,headers = {"Authorization" :f"Bearer { api_key () } " }) 87with urllib .request .urlopen (req ,timeout = 15 )as r : 88d = json .load (r ) 89except Exception : 90continue 91for k in ("concurrency" ,"live" ): 92v = d .get (k ) 93if isinstance (v ,dict ): 94for kk in ("serving" ,"slots" ,"batch_slots" ): 95if isinstance (v .get (kk ),int ): 96return v [kk ] 97if isinstance (v .get ("slots" ),dict ): 98return len (v ["slots" ]) 99return None 100 101 102def make_prompt (tokens ,ratio ): 103"""Промпт нужной длины со случайной меткой. 104 105ratio — токенов на символ (у этой модели на русском ~0.28). Значит нужное число 106символов = tokens / ratio. Фактическую длину в токенах видно по prompt_n в ответе. 107""" 108marker = "" .join (random .choices (string .ascii_uppercase + string .digits ,k = 10 )) 109body = [] 110n = 0 111while n < tokens / ratio : 112body .append (f"[ { marker } - { len ( body ) } ] " + random .choice (FILLERS )) 113n += len (body [- 1 ]) 114text = "\n" .join (body ) 115return text ,marker 116 117 118def post (path ,payload ,stream = False ,timeout = 900 ): 119data = json .dumps (payload ).encode () 120req = urllib .request .Request (BASE + path ,data = data ,method = "POST" , 121headers = {"Content-Type" :"application/json" , 122"Authorization" :f"Bearer { api_key () } " }) 123return urllib .request .urlopen (req ,timeout = timeout ) 124 125 126def one_request (prompt_tokens ,max_tokens ,ratio ,stream_mode ): 127"""Один запрос. Возвращает dict с движковыми таймингами и (если стрим) TTFT/wall.""" 128text ,marker = make_prompt (prompt_tokens ,ratio ) 129payload = {"messages" : [{"role" :"user" ,"content" :text + "\nКратко перескажи, что здесь описано." }], 130"max_tokens" :max_tokens ,"temperature" :0 ,"reasoning_effort" :"none" } 131t0 = time .time () 132ttft = None 133if stream_mode : 134payload ["stream" ]= True 135payload ["stream_options" ]= {"include_usage" :True } 136resp = post ("/v1/chat/completions" ,payload ,stream = True ) 137gen = 0 138timings = None 139for raw in resp : 140line = raw .decode ("utf-8" ,"ignore" ).strip () 141if not line .startswith ("data:" ): 142continue 143body = line [5 :].strip () 144if body == "[DONE]" : 145break 146try : 147d = json .loads (body ) 148except Exception : 149continue 150if d .get ("timings" ): 151timings = d ["timings" ] 152if d .get ("usage" ): 153gen = d ["usage" ].get ("completion_tokens" ,gen ) 154for ch in d .get ("choices" , []): 155delta = ch .get ("delta" )or {} 156piece = (delta .get ("content" )or "" )+ (delta .get ("reasoning_content" )or "" ) 157if piece and ttft is None : 158ttft = time .time ()- t0 159gen += len (piece ) 160wall = time .time ()- t0 161return {"ok" :True ,"ttft_s" :ttft ,"wall_s" :wall ,"gen_n" :gen , 162"prompt_s" : (timings or {}).get ("prompt_per_second" ), 163"gen_s" : (timings or {}).get ("predicted_per_second" ), 164"prompt_n" : (timings or {}).get ("prompt_n" )} 165resp = post ("/v1/chat/completions" ,payload ) 166d = json .loads (resp .read ().decode ()) 167wall = time .time ()- t0 168t = d .get ("timings" )or {} 169return {"ok" :True ,"wall_s" :wall ,"ttft_s" :None , 170"gen_n" :d .get ("usage" , {}).get ("completion_tokens" ), 171"prompt_n" :t .get ("prompt_n" ),"prompt_s" :t .get ("prompt_per_second" ), 172"gen_s" :t .get ("predicted_per_second" ), 173"draft_ok" :t .get ("draft_n_accepted" ),"draft_n" :t .get ("draft_n" )} 174 175 176def run_level (n ,prompt_tokens ,max_tokens ,ratio ,repeats ): 177"""n одновременных запросов; repeats повторов уровня.""" 178rows = [] 179for _ in range (repeats ): 180results = [None ]* n 181errs = [None ]* n 182 183def worker (i ): 184try : 185results [i ]= one_request (prompt_tokens ,max_tokens ,ratio ,stream_mode = True ) 186except Exception as e : 187errs [i ]= f" { type ( e ). __name__ } : { e } " 188 189ths = [threading .Thread (target = worker ,args = (i ,))for i in range (n )] 190t0 = time .time () 191for t in ths : 192t .start () 193for t in ths : 194t .join () 195wall_all = time .time ()- t0 196rows .append ({"n" :n ,"wall_all_s" :wall_all , 197"clients" : [r for r in results if r ],"errors" : [e for e in errs if e ]}) 198return rows 199 200 201def med (v ): 202v = [x for x in v if isinstance (x , (int ,float ))] 203return statistics .median (v )if v else None 204 205 206def summarize (level_rows ): 207out = [] 208for row in level_rows : 209cl = row ["clients" ] 210gen = [c .get ("gen_n" )or 0 for c in cl ] 211ttft = [c .get ("ttft_s" )for c in cl ] 212decode = [(c ["gen_n" ]/ (c ["wall_s" ]- c ["ttft_s" ]))for c in cl 213if c .get ("gen_n" )and c .get ("ttft_s" )is not None and c ["wall_s" ]> c ["ttft_s" ]] 214out .append ({"n" :row ["n" ],"clients_ok" :len (cl ),"errors" :row ["errors" ], 215"prompt_n" :med ([c .get ("prompt_n" )for c in cl ]), 216"wall_all_s" :round (row ["wall_all_s" ],2 ), 217"gen_per_client" :med (gen ),"gen_total" :sum (gen ), 218"ttft_med_s" :round (med (ttft )or 0 ,2 ), 219"ttft_max_s" :round (max ([t for t in ttft if t is not None ]or [0 ]),2 ), 220"decode_client_med" :round (med (decode )or 0 ,1 ), 221"throughput_total" :round (sum (gen )/ row ["wall_all_s" ],1 )if row ["wall_all_s" ]else 0 }) 222return out 223 224 225def main (): 226ap = argparse .ArgumentParser () 227ap .add_argument ("--levels" ,default = "1,2,3,4" ) 228ap .add_argument ("--prompt-tokens" ,type = int ,default = 8000 ) 229ap .add_argument ("--max-tokens" ,type = int ,default = 256 ) 230ap .add_argument ("--repeats" ,type = int ,default = 2 ) 231ap .add_argument ("--warm-tokens" ,type = int ,default = 2000 ) 232ap .add_argument ("--json" ,default = None ) 233ap .add_argument ("--label" ,default = "" ) 234a = ap .parse_args () 235 236ratio = float (os .environ .get ("STRATA_TOKENS_PER_CHAR" ,"0.28" ))# токенов на символ (русский текст) 237ver = engine_version () 238slots = batch_slots () 239f"сервер: { BASE } , движок: { ver } , слотов движка (concurrency.serving): { slots } " ) 240f"аргументы движка: { server_cmdline ()[: 400 ] } " ) 241f"прогрев ( { a . warm_tokens } токенов)..." ) 242one_request (a .warm_tokens ,64 ,ratio ,stream_mode = False ) 243 244data = {"label" :a .label ,"engine" :ver ,"batch_slots" :slots , 245"cmdline" :server_cmdline (),"config" :CFG , 246"prompt_tokens" :a .prompt_tokens ,"max_tokens" :a .max_tokens , 247"repeats" :a .repeats ,"levels" : [],"ts" :datetime .datetime .now ().isoformat ()} 248for n in [int (x )for x in a .levels .split ("," )]: 249f"\n=== уровень { n } одновременных запросов ( { a . repeats } повтора) ===" ) 250rows = run_level (n ,a .prompt_tokens ,a .max_tokens ,ratio ,a .repeats ) 251summ = summarize (rows ) 252for s in summ : 253f" n= { s [ 'n' ] } ок= { s [ 'clients_ok' ] } wall= { s [ 'wall_all_s' ] } с " 254f"токенов на клиента= { s [ 'gen_per_client' ] } всего= { s [ 'gen_total' ] } " 255f"TTFT мед= { s [ 'ttft_med_s' ] } с макс= { s [ 'ttft_max_s' ] } с " 256f"генерация на клиента= { s [ 'decode_client_med' ] } ток/с " 257f"итоговая скорость= { s [ 'throughput_total' ] } ток/с" ) 258if s ["errors" ]: 259" ошибки:" ,s ["errors" ]) 260data ["levels" ].append ({"n" :n ,"runs" :rows ,"summary" :summ }) 261time .sleep (3 ) 262 263out = a .json or f"/home/dgbox/logs/conc- { datetime . date . today () } - { re . sub ( r'[^a-z0-9]+' , '-' , a . label . lower ()). strip ( '-' ) } .json" 264os .makedirs (os .path .dirname (out ),exist_ok = True ) 265with open (out ,"w" ,encoding = "utf-8" )as f : 266json .dump (data ,f ,ensure_ascii = False ,indent = 1 ) 267f"\nJSON: { out } " ) 268 269 270if __name__ == "__main__" : 271main ()