bench_scale_performance.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. #!/usr/bin/env python3
  2. """
  3. bench_scale_performance.py — Tier 5: 6-Tier CPU ISA Kernel Micro-Benchmark + Live 200-Station Scale Test
  4. Measures real hardware throughput of unmodified `build/native/libstl_kernels.a` and
  5. `build/native/stl_native_server` under 200 concurrent live TCP serial stations:
  6. Part A: All supported CPU ISA tiers (SSE2 -> SSSE3 -> SSE4.2+PCLMUL -> SHA-NI -> AVX2+BMI2 -> AVX-512)
  7. for Base64, Hex, IEEE CRC-32, 64B batch SIMD state-diff, ASM serial cleaner, and 200-station RMT eye.
  8. Part B: Live 200-station `stl_native_server` over 200 real simultaneous TCP serial streams with full detail trace
  9. enabled — measuring OS thread count, VmRSS, sustained aggregate MB/s, lines/s, and WS RPC latency.
  10. """
  11. import asyncio
  12. import contextlib
  13. import json
  14. import os
  15. from pathlib import Path
  16. import shutil
  17. import subprocess
  18. import sys
  19. import tempfile
  20. import time
  21. from typing import Any, Dict, List, Optional
  22. import aiohttp
  23. ROOT_DIR = Path(__file__).resolve().parents[1]
  24. sys.path.insert(0, str(ROOT_DIR / "sim" / "hil_cluster"))
  25. from cluster_harness import CONTRACTS_PATH, STL_SERVER_BIN, WEB_DIR, WsRpcClient # noqa: E402
  26. ISA_BENCH_C = r"""
  27. #include <stdint.h>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <unistd.h>
  32. #include "native/stl_accel/stl_accel.h"
  33. static double now_sec(void) {
  34. return (double)stl_mono_us() / 1e6;
  35. }
  36. int main(void) {
  37. int detected_tier = stl_cpu_tier_detect();
  38. StlOpenClInfo ocl;
  39. memset(&ocl, 0, sizeof(ocl));
  40. stl_opencl_query_info(&ocl);
  41. long nprocs = sysconf(_SC_NPROCESSORS_ONLN);
  42. const size_t PAYLOAD_SZ = 1024 * 1024; /* 1 MiB */
  43. uint8_t *src = (uint8_t *)malloc(PAYLOAD_SZ);
  44. uint8_t *dst = (uint8_t *)malloc(PAYLOAD_SZ * 2 + 64);
  45. uint32_t x = 0x13579BDFu;
  46. for (size_t i = 0; i < PAYLOAD_SZ; i++) {
  47. x = x * 1664525u + 1013904223u;
  48. src[i] = (uint8_t)(x >> 24);
  49. }
  50. /* Realistic 1 MiB BIOS/Training/RMT/ANSI/MT86 serial payload */
  51. const char *sample_lines[] = {
  52. "[HS_BIOS][Training][ScktId: 0][42]Read Vref Training -- SUCCEEDED,Time=128 ms\r\n",
  53. "\x1b[12;1HRunning test #7 [Moving inversions, 32 bit pattern] (Test: 7/26 26%) Errors: 0\r\n",
  54. "N0.C3.D0.R0 -18 19 -16 17 -14 15 -12 13 34500 mV\r\n",
  55. "[0][Hovsee]Current stage is 1 [HS_DRAM] N0.C0.D0 DDR5 Present Size:65536\r\n",
  56. };
  57. uint8_t *ser_buf = (uint8_t *)malloc(PAYLOAD_SZ);
  58. size_t spos = 0;
  59. int lidx = 0;
  60. while (spos < PAYLOAD_SZ) {
  61. const char *ln = sample_lines[lidx++ & 3];
  62. size_t ll = strlen(ln);
  63. size_t cp = (spos + ll <= PAYLOAD_SZ) ? ll : (PAYLOAD_SZ - spos);
  64. memcpy(ser_buf + spos, ln, cp);
  65. spos += cp;
  66. }
  67. /* 200-station x 320B snapshot diff buffers */
  68. const size_t N_ST = 200;
  69. const size_t STRIDE = 320;
  70. uint8_t *prev_st = (uint8_t *)calloc(N_ST, STRIDE);
  71. uint8_t *cur_st = (uint8_t *)calloc(N_ST, STRIDE);
  72. for (size_t i = 0; i < N_ST; i += 5) cur_st[i * STRIDE + 128] = 0x5A;
  73. uint64_t masks[200];
  74. /* 200-station RMT eye reduction buffers */
  75. float *margins = (float *)malloc(N_ST * 24 * 4 * sizeof(float));
  76. float *eye_out = (float *)malloc(N_ST * 24 * 256 * sizeof(float));
  77. float *sum_out = (float *)malloc(N_ST * 4 * sizeof(float));
  78. for (size_t i = 0; i < N_ST * 24 * 4; i++) margins[i] = 14.0f;
  79. printf("{\"detected_tier\":%d,\"detected_tier_name\":\"%s\",\"online_cpus\":%ld,\"opencl_available\":%d,\"opencl_device\":\"%s\",\"tiers\":[",
  80. detected_tier, stl_isa_tier_name(detected_tier), nprocs, ocl.available, ocl.device_name);
  81. int first = 1;
  82. for (int t = 0; t <= detected_tier; t++) {
  83. stl_force_isa_tier(t);
  84. if (!first) printf(",");
  85. first = 0;
  86. /* 1. Base64 */
  87. double t0 = now_sec();
  88. volatile size_t sink = 0;
  89. for (int it = 0; it < 48; it++) sink += stl_base64_encode(src, PAYLOAD_SZ, dst);
  90. double b64_mbps = (48.0 * 1.0) / (now_sec() - t0);
  91. /* 2. Hex */
  92. t0 = now_sec();
  93. for (int it = 0; it < 48; it++) sink += stl_hex_encode(src, PAYLOAD_SZ, dst);
  94. double hex_mbps = (48.0 * 1.0) / (now_sec() - t0);
  95. /* 3. CRC32 IEEE */
  96. t0 = now_sec();
  97. volatile uint32_t crc_sink = 0;
  98. for (int it = 0; it < 96; it++) crc_sink ^= stl_crc32_ieee(0, src, PAYLOAD_SZ);
  99. double crc_mbps = (96.0 * 1.0) / (now_sec() - t0);
  100. /* 4. 200-station batch 64B diff */
  101. t0 = now_sec();
  102. for (int it = 0; it < 50000; it++) {
  103. stl_batch_mem_diff_64b_masks(prev_st, cur_st, STRIDE, STRIDE, N_ST, masks);
  104. }
  105. double diff_dt = now_sec() - t0;
  106. double diff_mstations_s = ((double)50000 * (double)N_ST / 1e6) / diff_dt;
  107. /* 5. ASM single-pass serial cleaner */
  108. StlCleanStreamState cst;
  109. stl_clean_stream_init(&cst);
  110. uint8_t *out_clean = (uint8_t *)malloc(PAYLOAD_SZ * 2);
  111. StlCleanLineSpan *spans = (StlCleanLineSpan *)malloc(32768 * sizeof(StlCleanLineSpan));
  112. size_t total_lines = 0;
  113. t0 = now_sec();
  114. for (int it = 0; it < 32; it++) {
  115. StlCleanOutput co;
  116. memset(&co, 0, sizeof(co));
  117. co.clean_buf = out_clean;
  118. co.clean_cap = PAYLOAD_SZ * 2;
  119. co.spans = spans;
  120. co.spans_cap = 32768;
  121. stl_clean_split_classify(&cst, ser_buf, PAYLOAD_SZ, &co);
  122. total_lines += co.spans_count;
  123. }
  124. double clean_dt = now_sec() - t0;
  125. double clean_mbps = 32.0 / clean_dt;
  126. double clean_mlines_s = ((double)total_lines / 1e6) / clean_dt;
  127. free(out_clean);
  128. free(spans);
  129. /* 6. 200-station RMT eye reduction */
  130. int used_gpu = 0;
  131. t0 = now_sec();
  132. for (int it = 0; it < 10; it++) {
  133. stl_batch_rmt_eye_reduce(margins, N_ST, eye_out, sum_out, &used_gpu);
  134. }
  135. double rmt_ms = ((now_sec() - t0) / 10.0) * 1000.0;
  136. printf("{\"tier\":%d,\"tier_name\":\"%s\",\"b64_mbps\":%.1f,\"hex_mbps\":%.1f,\"crc32_mbps\":%.1f,"
  137. "\"diff200_mstations_s\":%.2f,\"clean_mbps\":%.1f,\"clean_mlines_s\":%.2f,"
  138. "\"rmt200_ms\":%.2f,\"rmt_used_gpu\":%d}",
  139. t, stl_isa_tier_name(t), b64_mbps, hex_mbps, crc_mbps, diff_mstations_s, clean_mbps, clean_mlines_s, rmt_ms, used_gpu);
  140. (void)sink; (void)crc_sink;
  141. }
  142. stl_force_isa_tier(-1);
  143. printf("]}\n");
  144. free(src); free(dst); free(ser_buf);
  145. free(prev_st); free(cur_st);
  146. free(margins); free(eye_out); free(sum_out);
  147. return 0;
  148. }
  149. """
  150. def clean_env() -> Dict[str, str]:
  151. env = dict(os.environ)
  152. for k in (
  153. "LD_LIBRARY_PATH",
  154. "http_proxy",
  155. "https_proxy",
  156. "HTTP_PROXY",
  157. "HTTPS_PROXY",
  158. "all_proxy",
  159. "ALL_PROXY",
  160. ):
  161. env.pop(k, None)
  162. return env
  163. def run_part_a_isa_bench() -> Dict[str, Any]:
  164. print("[Tier5][Part A] Running 6-tier CPU ISA kernel throughput benchmark...", flush=True)
  165. tmp_dir = Path(tempfile.mkdtemp(prefix="xjkj_isa_bench_"))
  166. try:
  167. c_file = tmp_dir / "isa_bench.c"
  168. bin_file = tmp_dir / "isa_bench"
  169. c_file.write_text(ISA_BENCH_C, encoding="utf-8")
  170. subprocess.run(
  171. [
  172. "gcc",
  173. "-O2",
  174. f"-I{ROOT_DIR}",
  175. str(c_file),
  176. f"-L{ROOT_DIR / 'build' / 'native'}",
  177. "-lstl_kernels",
  178. "-lfreeipmi",
  179. "-lipmiconsole",
  180. "-lssh",
  181. "-lutil",
  182. "-ldl",
  183. "-lpthread",
  184. "-lm",
  185. "-o",
  186. str(bin_file),
  187. ],
  188. check=True,
  189. cwd=str(ROOT_DIR),
  190. env=clean_env(),
  191. capture_output=True,
  192. text=True,
  193. )
  194. out = subprocess.run(
  195. [str(bin_file)],
  196. check=True,
  197. cwd=str(ROOT_DIR),
  198. env=clean_env(),
  199. capture_output=True,
  200. text=True,
  201. timeout=60,
  202. )
  203. data = json.loads(out.stdout.strip())
  204. for row in data.get("tiers", []):
  205. print(
  206. f" Tier {row['tier']}: B64={row['b64_mbps']} MB/s | Hex={row['hex_mbps']} MB/s | "
  207. f"CRC32={row['crc32_mbps']} MB/s | Clean={row['clean_mbps']} MB/s ({row['clean_mlines_s']}M ln/s) | "
  208. f"Diff200={row['diff200_mstations_s']}M st/s | RMT200={row['rmt200_ms']} ms",
  209. flush=True,
  210. )
  211. return data
  212. finally:
  213. shutil.rmtree(tmp_dir, ignore_errors=True)
  214. def read_proc_metrics(pid: int) -> Dict[str, Any]:
  215. threads = 0
  216. rss_kb = 0
  217. try:
  218. for line in Path(f"/proc/{pid}/status").read_text(encoding="utf-8").splitlines():
  219. if line.startswith("Threads:"):
  220. threads = int(line.split()[1])
  221. elif line.startswith("VmRSS:"):
  222. rss_kb = int(line.split()[1])
  223. except Exception:
  224. pass
  225. cpu_ticks = 0
  226. try:
  227. parts = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8").rsplit(")", 1)[1].split()
  228. cpu_ticks = int(parts[11]) + int(parts[12]) # utime + stime
  229. except Exception:
  230. pass
  231. return {"threads": threads, "rss_mb": round(rss_kb / 1024.0, 2), "cpu_ticks": cpu_ticks}
  232. async def run_part_b_200_stations(num_stations: int = 200, duration_s: float = 4.0) -> Dict[str, Any]:
  233. print(f"[Tier5][Part B] Running live {num_stations}-station concurrent TCP serial scale benchmark ({duration_s}s)...", flush=True)
  234. tmp_dir = Path(tempfile.mkdtemp(prefix="xjkj_scale200_"))
  235. data_dir = tmp_dir / "data"
  236. data_dir.mkdir(parents=True, exist_ok=True)
  237. web_port = 19885
  238. tcp_port = 19886
  239. # Build synthetic realistic BIOS/RMT/MT86 burst payload (~8 KiB per burst)
  240. burst_unit = (
  241. b"[HS_BIOS]Version:108_VD012\r\n"
  242. b"[HS_BIOS][Training][ScktId: 0][42]Read Vref Training -- SUCCEEDED,Time=120 ms\r\n"
  243. b"N0.C0.D0.R0 -16 18 -14 16 -12 14 -11 12\r\n"
  244. b"\x1b[10;1HRunning test #7 (Test: 7/26 26%) Errors: 0\r\n"
  245. )
  246. burst_payload = burst_unit * 32 # ~6.8 KiB, 128 lines per burst
  247. lines_per_burst = 4 * 32
  248. connected_writers: List[asyncio.StreamWriter] = []
  249. conn_event = asyncio.Event()
  250. stop_stream = asyncio.Event()
  251. sent_bytes = 0
  252. sent_lines = 0
  253. async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
  254. nonlocal sent_bytes, sent_lines
  255. connected_writers.append(writer)
  256. if len(connected_writers) >= num_stations:
  257. conn_event.set()
  258. try:
  259. # Wait until streaming starts, then pump bursts continuously until stop_stream
  260. await conn_event.wait()
  261. while not stop_stream.is_set():
  262. writer.write(burst_payload)
  263. await writer.drain()
  264. sent_bytes += len(burst_payload)
  265. sent_lines += lines_per_burst
  266. await asyncio.sleep(0.025) # ~270 KB/s per station -> ~54 MB/s across 200 stations
  267. except Exception:
  268. pass
  269. finally:
  270. with contextlib.suppress(Exception):
  271. writer.close()
  272. tcp_server = await asyncio.start_server(handle_client, "127.0.0.1", tcp_port, backlog=512)
  273. server_proc: Optional[subprocess.Popen] = None
  274. try:
  275. stations_cfg = []
  276. for i in range(1, num_stations + 1):
  277. sid = f"S{i:03d}"
  278. stations_cfg.append({
  279. "station_id": sid,
  280. "frontend_index": i - 1,
  281. "name": f"压测工位 {i:03d}",
  282. "mode": "hardware",
  283. "cpu_count": 2,
  284. "channels_per_cpu": 12,
  285. "bmc": {"enabled": False, "host": ""},
  286. "console": {
  287. "enabled": True,
  288. "transport": "tcp_serial",
  289. "host": "127.0.0.1",
  290. "port": tcp_port,
  291. },
  292. })
  293. cfg_path = tmp_dir / "scale200.json"
  294. cfg_path.write_text(json.dumps({"mode": "hardware", "data_dir": str(data_dir), "stations": stations_cfg}), encoding="utf-8")
  295. server_proc = subprocess.Popen(
  296. [
  297. str(STL_SERVER_BIN),
  298. "--config", str(cfg_path),
  299. "--data-dir", str(data_dir),
  300. "--web-listen", f"127.0.0.1:{web_port}",
  301. "--tftp-listen", "disabled",
  302. "--pxe-mode", "disabled",
  303. "--batch-window-ms", "100",
  304. "--detail-log", "on",
  305. "--web-dir", str(WEB_DIR),
  306. "--contracts", str(CONTRACTS_PATH),
  307. "--web-password", "disabled",
  308. ],
  309. cwd=str(ROOT_DIR),
  310. stdout=subprocess.DEVNULL,
  311. stderr=subprocess.PIPE,
  312. text=True,
  313. env=clean_env(),
  314. )
  315. # Wait for all 200 TCP serial connections to establish!
  316. await asyncio.wait_for(conn_event.wait(), timeout=20.0)
  317. clk_tck = os.sysconf(os.sysconf_names["SC_CLK_TCK"])
  318. m0 = read_proc_metrics(server_proc.pid)
  319. t_stream0 = time.monotonic()
  320. # While all 200 streams blast data simultaneously, also measure live WebSocket ListStations RPC latency!
  321. rpc_latencies_ms: List[float] = []
  322. async with aiohttp.ClientSession() as http:
  323. ws = WsRpcClient(http, f"ws://127.0.0.1:{web_port}/ws")
  324. await ws.connect()
  325. try:
  326. while time.monotonic() - t_stream0 < duration_s:
  327. tr0 = time.monotonic()
  328. lst = await ws.call("ListStations", {}, timeout=10.0)
  329. rpc_latencies_ms.append(round((time.monotonic() - tr0) * 1000.0, 2))
  330. assert len(lst.get("stations") or []) == num_stations
  331. await asyncio.sleep(0.5)
  332. stop_stream.set()
  333. await asyncio.sleep(0.25)
  334. m1 = read_proc_metrics(server_proc.pid)
  335. hw_info = await ws.call("GetHardwareInfo", {})
  336. trace_st = await ws.call("GetTraceStatus", {})
  337. finally:
  338. await ws.close()
  339. elapsed = max(0.01, time.monotonic() - t_stream0)
  340. cpu_sec = (m1["cpu_ticks"] - m0["cpu_ticks"]) / float(clk_tck)
  341. cpu_pct = round((cpu_sec / elapsed) * 100.0, 1)
  342. mb_sent = sent_bytes / (1024.0 * 1024.0)
  343. mb_per_s = round(mb_sent / elapsed, 2)
  344. lines_per_s = int(sent_lines / elapsed)
  345. avg_rpc_ms = round(sum(rpc_latencies_ms) / max(1, len(rpc_latencies_ms)), 2)
  346. assert m1["threads"] <= 32, f"Thread explosion! Expected <= 32 OS threads for 200 stations, got {m1['threads']}"
  347. assert mb_per_s >= 10.0, f"Throughput too low: {mb_per_s} MB/s"
  348. res = {
  349. "num_stations": num_stations,
  350. "connected_streams": len(connected_writers),
  351. "duration_s": round(elapsed, 2),
  352. "os_threads": m1["threads"],
  353. "vm_rss_mb": m1["rss_mb"],
  354. "cpu_percent_total": cpu_pct,
  355. "total_mb_ingested": round(mb_sent, 2),
  356. "sustained_mb_per_sec": mb_per_s,
  357. "sustained_lines_per_sec": lines_per_s,
  358. "list200_rpc_avg_ms": avg_rpc_ms,
  359. "trace_serial_mb_written": round(float(trace_st.get("serial_bytes_written", 0)) / (1024.0 * 1024.0), 2),
  360. "isa_tier_name": hw_info.get("tier_name"),
  361. "ok": True,
  362. }
  363. print(
  364. f" 200 Stations LIVE: Threads={res['os_threads']} | RSS={res['vm_rss_mb']} MiB | "
  365. f"CPU={res['cpu_percent_total']}% | Throughput={res['sustained_mb_per_sec']} MB/s "
  366. f"({res['sustained_lines_per_sec']} lines/s) | ListStations(200)={res['list200_rpc_avg_ms']} ms | "
  367. f"TraceRawDisk={res['trace_serial_mb_written']} MiB",
  368. flush=True,
  369. )
  370. return res
  371. finally:
  372. stop_stream.set()
  373. tcp_server.close()
  374. with contextlib.suppress(Exception):
  375. await tcp_server.wait_closed()
  376. if server_proc is not None and server_proc.poll() is None:
  377. with contextlib.suppress(Exception):
  378. server_proc.terminate()
  379. server_proc.wait(timeout=3.0)
  380. if server_proc.poll() is None:
  381. with contextlib.suppress(Exception):
  382. server_proc.kill()
  383. shutil.rmtree(tmp_dir, ignore_errors=True)
  384. def main() -> None:
  385. t0 = time.monotonic()
  386. part_a = run_part_a_isa_bench()
  387. part_b = asyncio.run(run_part_b_200_stations(num_stations=200, duration_s=4.0))
  388. report = {
  389. "tier": "Tier5_6Tier_ISA_And_200Station_Scale_Benchmark",
  390. "ok": True,
  391. "elapsed_s": round(time.monotonic() - t0, 2),
  392. "isa_kernels": part_a,
  393. "live_200_stations": part_b,
  394. }
  395. out_file = ROOT_DIR / "build" / "sim" / "tier5_scale_bench_report.json"
  396. out_file.parent.mkdir(parents=True, exist_ok=True)
  397. out_file.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
  398. print(f"\n[Tier5] 6-TIER ISA & 200-STATION SCALE BENCHMARK PASSED in {report['elapsed_s']}s! Report: {out_file}", flush=True)
  399. if __name__ == "__main__":
  400. main()