-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathonline_gate.py
More file actions
executable file
·4075 lines (3916 loc) · 165 KB
/
Copy pathonline_gate.py
File metadata and controls
executable file
·4075 lines (3916 loc) · 165 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Fail-closed orchestration helpers for ``SERVE-GATE-ONLINE``.
The timed client remains the unmodified pinned vLLM ``bench serve`` command.
This wrapper mirrors its CLI and result schema from:
* ``vllm/benchmarks/serve.py:321-353,563-748,1188-1284,2082-2284``
* ``vllm/benchmarks/datasets/datasets.py:2482-2610``
* ``tests/benchmarks/test_serve_cli.py:58-132``
at executable-oracle commit ``702f4814fe54fabff350d43cb753ae3e47c0c276``. It
does not reimplement request timing. It constructs the exact upstream client
command, validates every detailed artifact, and makes partial request sets
fatal instead of allowing their aggregate metrics to look successful.
"""
from __future__ import annotations
import argparse
import dataclasses
import datetime as dt
import gzip
import hashlib
import importlib.metadata
import json
import mmap
import os
import pathlib
import platform
import re
import shlex
import sqlite3
import subprocess
import sys
from collections import Counter
from collections.abc import Mapping, Sequence
from typing import Any
from tools.bench.serve_low_common import (
HarnessError,
VLLM_COMMIT,
canonical_json,
read_jsonl,
require_number,
sha256_file,
write_json_atomic,
write_jsonl_atomic,
)
INPUT_LEN = 1024
OUTPUT_LEN = 128
VLLM_ORACLE_VERSION = "0.25.0"
FLASHINFER_VERSION = "0.6.13"
PANDAS_VERSION = "2.2.3"
TRACE_CONCURRENCY = 16
TRACE_PROMPTS = 48
TRACE_REPETITIONS = 3
TRACE_CAPTURE_GRAPH_REPLAYS = 4
TRACE_RANGE_REPORTS = TRACE_REPETITIONS * TRACE_CAPTURE_GRAPH_REPLAYS
TRACE_STATUS_SCHEMA_VERSION = 5
BUILD_CONTRACT_SCHEMA_VERSION = 2
NSYS_CAPTURE_RANGE = "cudaProfilerApi"
NSYS_CAPTURE_RANGE_END = f"repeat:{TRACE_CAPTURE_GRAPH_REPLAYS}:sync"
NSYS_CUDA_GRAPH_TRACE = "node:host-only"
NSYS_CUDA_FLUSH_INTERVAL_MS = 0
NSYS_PRODUCT_VERSION = "2025.3.2.474"
DGX_CUDA_COMPILER = pathlib.Path("/usr/local/cuda-13.0/bin/nvcc")
DGX_CUDA_COMPILER_VERSION = "13.0.88"
NVFP4_PLAN_FIXTURE_SHA256 = (
"e81e9181db20d0537a43a101fe4f93aa57df9e42900e8a21c91cafa61e107edd"
)
NVFP4_SELECTED_PLAN_SHA256 = (
"f2d9be7fc4a89de1cfa994ab9be08a423e0c4f6981fe46cb808cef485f4c1fa4"
)
NVFP4_PLAN_METADATA = "2e429d4cd3977f0f"
TRACE_REQUIRED_ENV = {
"VT_FP4_AUTOTUNE": "1",
"VT_FP4_AUTOTUNE_CACHE_READONLY": "1",
"VT_FP4_AUTOTUNE_DELAY_US": "5000",
"VT_FP4_FULL_TACTICS": "1",
"VT_FP4_PERSISTENT_CACHE": "1",
"VT_FP4_PLAN_CACHE": "1",
"VT_FP4_PRE_SERVE_WARMUP": "1",
}
TRACE_SYSTEM_PATH = (
"/usr/local/cuda-13.0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:"
"/usr/bin:/sbin:/bin:/snap/bin"
)
TRACE_CLEAN_FIXED_ENV = {
"LANG": "C.UTF-8",
"LC_ALL": "C.UTF-8",
"TMPDIR": "/tmp",
"TZ": "UTC",
}
TRACE_GDN_BA_MODES = ("merged", "split")
TRACE_GDN_BA_ENV = {"merged": "1", "split": "0"}
TRACE_GDN_PACKED_MODES = ("packed", "rollback")
TRACE_GDN_PACKED_ENV = {"packed": "1", "rollback": "0"}
TRACE_GDN_PACKED_STRUCTURAL_FAMILIES = (
"gdn_packed_recurrence",
"gdn_decomposed_recurrence",
"gdn_post_conv",
)
TRACE_GDN_PACKED_COUPLED_BA_NODE_COUNT = 48
TRACE_GDN_PACKED_COUPLED_BA_GRID = (8, 1, 1)
_TRACE_27_COMMON_FAMILIES = {
"fa2_combine": ("flash_fwd_splitkv_combine_kernel", 16),
"fa2_main": ("flash_fwd_splitkv_kernel", 16),
"fp4_gemm": (
"cutlass::device_kernel<cutlass::gemm::kernel::GemmUniversal",
208,
),
"fused_fp4_producer": ("SiluAndMulFp4QuantKernel", 64),
"gdn_recurrence": ("GdnDecodeFusedKernel", 48),
"normal_fp4_producer": ("ScaledFp4QuantKernel", 144),
}
TRACE_PRIMARY_GRAPH_CONTRACTS = {
"27": {
"graph_child_nodes": {"kernel": 1_107, "memcpy": 7, "memset": 1},
"node_count": 1_107,
"families": dict(_TRACE_27_COMMON_FAMILIES),
}
}
TRACE_PRIMARY_GRAPH_CONTRACTS_BY_BATCH = {
("27", TRACE_CONCURRENCY): TRACE_PRIMARY_GRAPH_CONTRACTS["27"],
("27", 2): {
"graph_child_nodes": {"kernel": 1_011, "memcpy": 7, "memset": 1},
"node_count": 1_011,
"families": dict(_TRACE_27_COMMON_FAMILIES),
},
}
TRACE_PRIMARY_GRAPH_CONTRACTS_BY_GDN_BA_MODE = {
("27", 2, "merged"): {
"graph_child_nodes": {"kernel": 963, "memcpy": 7, "memset": 1},
"node_count": 963,
"families": {
**_TRACE_27_COMMON_FAMILIES,
"bf16_gemm": ("gemm_bf16", 145),
},
},
("27", 2, "split"): {
"graph_child_nodes": {"kernel": 1_011, "memcpy": 7, "memset": 1},
"node_count": 1_011,
"families": {
**_TRACE_27_COMMON_FAMILIES,
"bf16_gemm": ("gemm_bf16", 193),
},
},
}
_TRACE_27_NON_GDN_FAMILIES = {
family: contract
for family, contract in _TRACE_27_COMMON_FAMILIES.items()
if family != "gdn_recurrence"
}
TRACE_PRIMARY_GRAPH_CONTRACTS_BY_GDN_PACKED_MODE = {
("27", 2, "packed"): {
"graph_child_nodes": {"kernel": 915, "memcpy": 7, "memset": 1},
"node_count": 915,
"families": {
**_TRACE_27_NON_GDN_FAMILIES,
"bf16_gemm": ("gemm_bf16", 145),
"gdn_packed_recurrence": ("GdnPackedDecodeKernel", 48),
"gdn_decomposed_recurrence": ("GdnDecodeFusedKernel", 0),
"gdn_post_conv": ("GdnPostConvKernel", 0),
},
},
("27", 2, "rollback"): {
"graph_child_nodes": {"kernel": 963, "memcpy": 7, "memset": 1},
"node_count": 963,
"families": {
**_TRACE_27_NON_GDN_FAMILIES,
"bf16_gemm": ("gemm_bf16", 145),
"gdn_packed_recurrence": ("GdnPackedDecodeKernel", 0),
"gdn_decomposed_recurrence": ("GdnDecodeFusedKernel", 48),
"gdn_post_conv": ("GdnPostConvKernel", 48),
},
},
}
VLLM_DECODE_FAMILY_CONTRACTS = {
"27": {
"fa2_combine": ("flash_fwd_splitkv_combine_kernel", 16),
"fa2_main": ("flash_fwd_splitkv_kernel", 16),
"fp4_gemm": ("MainloopSm120TmaWarpSpecializedBlockScaled", 208),
"fused_fp4_producer": ("silu_mul_cvt_fp16_to_fp4", 64),
"gdn_recurrence": (
"fused_recurrent_gated_delta_rule_packed_decode_kernel",
48,
),
"normal_fp4_producer": ("cvt_fp16_to_fp4<__nv_bfloat16, false>", 144),
}
}
VLLM_GENERATION_WINDOW_CONTRACTS = {
"27": {"all": 1_588, "clean": 1_476},
}
REPETITIONS = (1, 2, 3)
# The GDN packed-vs-rollback component runs five timed repetitions per
# (concurrency, arm) under CLAIM-GDN-BA-ROUNDING-1, so an ``OnlineRun`` may carry
# a repetition beyond the three-rep online-serving grid. The online gate itself
# never emits a repetition outside ``REPETITIONS``; this bound only widens the
# accepted domain so the component can reuse ``OnlineRun`` / ``build_client_command``.
MAX_ONLINE_REPETITION = 5
POINTS = ((1, 6), (2, 6), (4, 12), (8, 24), (16, 96), (32, 192))
MODEL_REVISIONS = {
"27": "890bdef7a42feba6d83b6e17a03315c694112f2a",
"35": "491c2f1ea524c639598bf8fa787a93fed5a6fbce",
}
MODEL_REPOSITORIES = {
"27": "unsloth/Qwen3.6-27B-NVFP4",
"35": "nvidia/Qwen3.6-35B-A3B-NVFP4",
}
MAX_NUM_SEQS = 32
MAX_NUM_BATCHED_TOKENS = {"27": 2048, "35": 8192}
MAX_MODEL_LEN = {"27": 262144, "35": 262144}
ENGINES = ("ours", "vllm")
PERCENTILE_METRICS = ("ttft", "tpot", "itl", "e2el")
PERCENTILES = (50, 90, 99)
CACHE_DROP_METHOD = "posix_fadvise-dontneed+mincore"
_SHA_RE = re.compile(r"[0-9a-f]{40}")
_NSYS_ALLOWED_DIAGNOSTIC = re.compile(
r"CUDA device \d+: Unified Memory trace is not supported by the current "
r"driver version or configuration\."
)
_NSYS_CAPTURE_BOUNDARY_DIAGNOSTIC = (
"Not all CUDA events might have been collected."
)
_NSYS_COLLECTED_EVENTS_RE = re.compile(
r"Number of CUDA events collected:\s+(\d+)\."
)
_NSYS_PRODUCED_EVENTS_RE = re.compile(
r"Number of CUPTI events produced:\s+(\d+), CUPTI buffers:\s+(\d+)\."
)
_PLAN_PREPARED_RE = re.compile(
r"^\[VT_FP4_CACHE\] prepared mode=(\S+) native=(\S+) flashinfer=(\S+) "
r"loaded=(\d+) \(flashinfer=(\d+) native=(\d+)\) rejected=(\d+) "
r"delay_us=(\d+) metadata=([0-9a-f]+) selected=(\d+)$"
)
_PLAN_COMPLETE_RE = re.compile(
r"^\[VT_FP4_CACHE\] complete mode=(\S+) loaded=(\d+) tuned=(\d+) "
r"rejected=(\d+) saved=(\d+) selected=(\d+) metadata=([0-9a-f]+)$"
)
_PLAN_SELECTED_RE = re.compile(
r"^\[VT_FP4_CACHE\] selected M=(\d+) N=(\d+) K=(\d+) tactic=(\d+)$"
)
_PLAN_WARMUP_RE = re.compile(
r"^\[VT_FP4_AUTOTUNE\] pre-serve warmup complete max_tokens=(\d+) "
r"profiles_requested=(\d+) profiles_tuned=(\d+) cached_plans=(\d+)$"
)
_CUDA_PROFILE_READY_RE = re.compile(
r"^\[VT_CUDA_PROFILE\] ready pid=(\d+) signal=SIGUSR2 target_replays=(\d+)$"
)
_CUDA_PROFILE_STARTED_RE = re.compile(
r"^\[VT_CUDA_PROFILE\] started target_replays=(\d+) "
r"graph=(0x[0-9a-f]+) real_batch=(\d+) padded_batch=(\d+) "
r"prior_replays=(\d+)$"
)
_CUDA_PROFILE_STOPPED_RE = re.compile(
r"\[VT_CUDA_PROFILE\] stopped captured_replays=(\d+) "
r"graph=(0x[0-9a-f]+)"
)
_BENCH_SHUTDOWN_READY_RE = re.compile(
r"^\[VT_BENCH_SHUTDOWN\] ready pid=(\d+) control=fifo$"
)
_BENCH_SHUTDOWN_REQUESTED_RE = re.compile(
r"^\[VT_BENCH_SHUTDOWN\] requested control=fifo$"
)
_BENCH_SHUTDOWN_COMPLETED_RE = re.compile(
r"^\[VT_BENCH_SHUTDOWN\] completed control=fifo$"
)
def prompts_for(concurrency: int) -> int:
try:
return dict(POINTS)[concurrency]
except KeyError as error:
raise HarnessError(f"unsupported online-gate concurrency: {concurrency}") from error
def trace_primary_graph_contract(
model_key: str,
expected_batch: int,
*,
gdn_ba_mode: str | None = None,
gdn_packed_mode: str | None = None,
) -> Mapping[str, Any]:
"""Resolve an exact graph contract without reinterpreting old evidence."""
if gdn_ba_mode is not None and gdn_packed_mode is not None:
raise HarnessError("GDN BA and packed trace modes are mutually exclusive")
if gdn_ba_mode is None and gdn_packed_mode is None:
contract = TRACE_PRIMARY_GRAPH_CONTRACTS_BY_BATCH.get(
(model_key, expected_batch)
)
elif gdn_ba_mode is not None:
if gdn_ba_mode not in TRACE_GDN_BA_MODES:
raise HarnessError(f"unknown GDN BA trace mode: {gdn_ba_mode}")
contract = TRACE_PRIMARY_GRAPH_CONTRACTS_BY_GDN_BA_MODE.get(
(model_key, expected_batch, gdn_ba_mode)
)
else:
if gdn_packed_mode not in TRACE_GDN_PACKED_MODES:
raise HarnessError(f"unknown GDN packed trace mode: {gdn_packed_mode}")
contract = TRACE_PRIMARY_GRAPH_CONTRACTS_BY_GDN_PACKED_MODE.get(
(model_key, expected_batch, gdn_packed_mode)
)
if contract is None:
suffix = ""
if gdn_ba_mode:
suffix = f" in GDN BA mode {gdn_ba_mode}"
elif gdn_packed_mode:
suffix = f" in GDN packed mode {gdn_packed_mode}"
raise HarnessError(
"no exact Nsight graph contract for "
f"model {model_key} at batch {expected_batch}{suffix}"
)
return contract
@dataclasses.dataclass(frozen=True)
class OnlineRun:
client: pathlib.Path
tokenizer: pathlib.Path
evidence_root: pathlib.Path
model_key: str
engine: str
base_url: str
concurrency: int
repetition: int
artifact_tag: str = ""
num_prompts_override: int | None = None
num_warmups_override: int | None = None
def __post_init__(self) -> None:
if self.model_key not in MODEL_REVISIONS:
raise HarnessError(f"unknown model key: {self.model_key}")
if self.engine not in ENGINES:
raise HarnessError(f"unknown engine arm: {self.engine}")
if (
isinstance(self.repetition, bool)
or not isinstance(self.repetition, int)
or not 1 <= self.repetition <= MAX_ONLINE_REPETITION
):
raise HarnessError(f"unsupported repetition: {self.repetition}")
if self.artifact_tag and re.fullmatch(r"[a-z0-9-]+", self.artifact_tag) is None:
raise HarnessError(f"invalid artifact tag: {self.artifact_tag}")
if self.num_prompts_override is not None and self.num_prompts_override <= 0:
raise HarnessError("num-prompts override must be positive")
if self.num_warmups_override is not None and self.num_warmups_override < 0:
raise HarnessError("num-warmups override must be non-negative")
prompts_for(self.concurrency)
@property
def filename_stem(self) -> str:
suffix = f"-{self.artifact_tag}" if self.artifact_tag else ""
return f"c{self.concurrency}-r{self.repetition}{suffix}"
@property
def num_prompts(self) -> int:
return (
self.num_prompts_override
if self.num_prompts_override is not None
else prompts_for(self.concurrency)
)
@property
def num_warmups(self) -> int:
return (
self.num_warmups_override
if self.num_warmups_override is not None
else self.concurrency
)
@property
def corpus_path(self) -> pathlib.Path:
return self.evidence_root / "corpus" / self.model_key / "vllm" / (
f"c{self.concurrency}-r{self.repetition}.jsonl"
)
@property
def result_path(self) -> pathlib.Path:
return self.evidence_root / "raw" / self.model_key / self.engine / (
f"{self.filename_stem}.json"
)
@property
def log_path(self) -> pathlib.Path:
return self.evidence_root / "logs" / self.model_key / self.engine / (
f"{self.filename_stem}.log"
)
def _require_full_sha(value: str, field: str) -> str:
if _SHA_RE.fullmatch(value) is None:
raise HarnessError(f"{field} must be a full lowercase commit ID")
return value
def _sha256_canonical(value: Any) -> str:
return hashlib.sha256(canonical_json(value).encode("utf-8")).hexdigest()
def _fingerprint_tree(root: pathlib.Path) -> dict[str, Any]:
"""Hash a dependency tree by relative path, byte size, and file content."""
if not root.is_dir():
raise HarnessError(f"dependency source tree is absent: {root}")
inventory = []
for path in sorted(root.rglob("*"), key=lambda item: item.relative_to(root).as_posix()):
if path.is_symlink():
raise HarnessError(f"dependency source tree contains a symlink: {path}")
if not path.is_file():
continue
relative = path.relative_to(root).as_posix()
inventory.append(
{
"path": relative,
"sha256": sha256_file(path),
"size": path.stat().st_size,
}
)
if not inventory:
raise HarnessError(f"dependency source tree contains no files: {root}")
return {
"file_count": len(inventory),
"logical_bytes": sum(item["size"] for item in inventory),
"path": str(root.absolute()),
"sha256": _sha256_canonical(inventory),
}
def _file_contains(path: pathlib.Path, needle: bytes) -> bool:
if not path.is_file() or path.stat().st_size == 0:
return False
with path.open("rb") as source, mmap.mmap(
source.fileno(), 0, access=mmap.ACCESS_READ
) as mapped:
return mapped.find(needle) >= 0
def _require_sqlite_columns(
connection: sqlite3.Connection,
table: str,
expected: set[str],
) -> None:
actual = {
str(row[1]) for row in connection.execute(f"PRAGMA table_info({table})")
}
missing = sorted(expected - actual)
if missing:
raise HarnessError(
f"Nsight SQLite table {table} omits required columns: "
+ ", ".join(missing)
)
def _option_value(tokens: Sequence[str], flag: str) -> str | None:
matches = []
prefix = f"{flag}="
for index, token in enumerate(tokens):
if token.startswith(prefix):
matches.append(token[len(prefix) :])
elif token == flag:
if index + 1 >= len(tokens):
raise HarnessError(f"command option {flag} has no value")
matches.append(tokens[index + 1])
if len(matches) > 1:
raise HarnessError(f"command option {flag} is repeated")
return matches[0] if matches else None
def _parse_clean_environment_prefix(
tokens: Sequence[str], stop_index: int, *, label: str
) -> dict[str, str]:
if list(tokens[:2]) != ["/usr/bin/env", "-i"]:
raise HarnessError(
f"{label} command must start with the exact /usr/bin/env -i prefix"
)
environment_tokens = list(tokens[2:stop_index])
if not environment_tokens or any(
"=" not in token or not token.split("=", 1)[0]
for token in environment_tokens
):
raise HarnessError(f"{label} command clean environment is malformed")
environment_names = [token.split("=", 1)[0] for token in environment_tokens]
if len(set(environment_names)) != len(environment_names):
raise HarnessError(f"{label} command clean environment repeats a variable")
return dict(token.split("=", 1) for token in environment_tokens)
def _validate_clean_host_environment(
environment: Mapping[str, str],
*,
source_root: pathlib.Path,
expected_path: str,
label: str,
) -> None:
for name, expected in TRACE_CLEAN_FIXED_ENV.items():
if environment.get(name) != expected:
raise HarnessError(
f"{label} command clean environment {name} differs from H1d"
)
if environment.get("PATH") != expected_path:
raise HarnessError(f"{label} command clean PATH differs from H1d")
home_value = environment.get("HOME")
if home_value is None:
raise HarnessError(f"{label} command clean environment omits HOME")
home = pathlib.Path(home_value)
if not home.is_absolute() or not home.is_dir():
raise HarnessError(f"{label} command HOME is not an existing absolute directory")
pythonpath_value = environment.get("PYTHONPATH")
if (
pythonpath_value is None
or os.pathsep in pythonpath_value
or pathlib.Path(pythonpath_value).resolve() != source_root.resolve()
):
raise HarnessError(f"{label} command PYTHONPATH differs from the source root")
def _require_option(tokens: Sequence[str], flag: str, expected: str) -> None:
actual = _option_value(tokens, flag)
if actual != expected:
raise HarnessError(f"command {flag}={actual!r}; expected {expected!r}")
def build_client_command(run: OnlineRun) -> list[str]:
"""Build the unmodified pinned ``vllm bench serve`` invocation."""
if not run.client.is_file():
raise HarnessError(f"missing pinned vLLM client: {run.client}")
if not run.tokenizer.is_dir():
raise HarnessError(f"missing tokenizer snapshot: {run.tokenizer}")
if not run.corpus_path.is_file():
raise HarnessError(f"missing frozen corpus partition: {run.corpus_path}")
return [
str(run.client),
"bench",
"serve",
"--backend",
"openai",
"--base-url",
run.base_url,
"--endpoint",
"/v1/completions",
"--model",
"gate",
"--tokenizer",
str(run.tokenizer),
"--dataset-name",
"custom",
"--dataset-path",
str(run.corpus_path),
"--custom-output-len",
str(OUTPUT_LEN),
"--skip-chat-template",
"--disable-shuffle",
"--num-prompts",
str(run.num_prompts),
"--max-concurrency",
str(run.concurrency),
"--request-rate",
"inf",
"--num-warmups",
str(run.num_warmups),
"--ready-check-timeout-sec",
"0",
"--seed",
"0",
"--ignore-eos",
"--temperature",
"0",
"--percentile-metrics",
",".join(PERCENTILE_METRICS),
"--metric-percentiles",
",".join(str(value) for value in PERCENTILES),
"--save-result",
"--save-detailed",
"--result-dir",
str(run.result_path.parent),
"--result-filename",
run.result_path.name,
"--disable-tqdm",
]
def _require_list(record: Mapping[str, Any], field: str, length: int) -> list[Any]:
value = record.get(field)
if not isinstance(value, list) or len(value) != length:
actual = len(value) if isinstance(value, list) else type(value).__name__
raise HarnessError(f"{field} has cardinality {actual}; expected {length}")
return value
def precise_max_concurrent_requests(record: Mapping[str, Any]) -> int:
"""Compute exact request overlap from detailed half-open time intervals.
Pinned vLLM's reported ``max_concurrent_requests`` uses inclusive one-second
buckets, so sequential requests that straddle a bucket boundary can be
reported as overlapping. Detailed start/TTFT/ITL arrays retain the exact
intervals needed for the binding concurrency check.
"""
start_times = record.get("start_times")
ttfts = record.get("ttfts")
itls = record.get("itls")
if (
not isinstance(start_times, list)
or not isinstance(ttfts, list)
or not isinstance(itls, list)
):
raise HarnessError("precise concurrency requires start_times, ttfts and itls")
if not start_times or len(start_times) != len(ttfts) or len(start_times) != len(itls):
raise HarnessError("precise concurrency arrays have inconsistent cardinality")
events: list[tuple[float, int]] = []
for index, (start_value, ttft_value, itl_values) in enumerate(
zip(start_times, ttfts, itls)
):
start = require_number(start_value, f"start_times[{index}]")
ttft = require_number(ttft_value, f"ttfts[{index}]")
if not isinstance(itl_values, list):
raise HarnessError(f"itls[{index}] is not a list")
latency = ttft + sum(
require_number(value, f"itls[{index}][{value_index}]")
for value_index, value in enumerate(itl_values)
)
if start < 0.0 or latency < 0.0:
raise HarnessError("precise concurrency interval contains a negative value")
events.append((start, 1))
events.append((start + latency, -1))
# End events sort before starts at identical timestamps: [start, end).
active = 0
peak = 0
for _, delta in sorted(events, key=lambda item: (item[0], item[1])):
active += delta
if active < 0:
raise HarnessError("precise concurrency event order is invalid")
peak = max(peak, active)
if active != 0:
raise HarnessError("precise concurrency intervals did not close")
return peak
def validate_raw_result(
record: Mapping[str, Any],
*,
concurrency: int,
expected_requests: int | None = None,
) -> None:
"""Validate the detailed vLLM result schema and exact request contract."""
expected = prompts_for(concurrency) if expected_requests is None else expected_requests
if record.get("num_prompts") != expected:
raise HarnessError(
f"num_prompts={record.get('num_prompts')!r}; expected {expected}"
)
if record.get("completed") != expected or record.get("failed") != 0:
raise HarnessError(
"request set is partial: "
f"completed={record.get('completed')!r}, failed={record.get('failed')!r}, "
f"expected={expected}"
)
if record.get("max_concurrency") != concurrency:
raise HarnessError(
f"configured max_concurrency={record.get('max_concurrency')!r}; "
f"expected {concurrency}"
)
if record.get("total_input_tokens") != expected * INPUT_LEN:
raise HarnessError("total input tokens do not match the frozen corpus")
if record.get("total_output_tokens") != expected * OUTPUT_LEN:
raise HarnessError("total output tokens are not exact")
input_lens = _require_list(record, "input_lens", expected)
output_lens = _require_list(record, "output_lens", expected)
ttfts = _require_list(record, "ttfts", expected)
itls = _require_list(record, "itls", expected)
start_times = _require_list(record, "start_times", expected)
generated = _require_list(record, "generated_texts", expected)
errors = _require_list(record, "errors", expected)
if any(value != INPUT_LEN for value in input_lens):
raise HarnessError("raw input lengths do not all equal 1024")
if any(value != OUTPUT_LEN for value in output_lens):
raise HarnessError("raw output lengths do not all equal 128")
if any(value for value in errors):
raise HarnessError("raw result contains request errors")
if any(not isinstance(value, str) for value in generated):
raise HarnessError("raw result did not retain every generated text")
# RequestOutputCollector deliberately merges DELTA outputs when the
# producer gets ahead of the consumer (matching pinned vLLM). The pinned
# benchmark client consequently treats ITLs as inter-*chunk* timings and
# uses native usage for the exact token count; one chunk may carry more
# than one token. Reject impossible extra timing events, but do not reject
# an upstream-legal merged delta merely because it retained fewer than
# OUTPUT_LEN - 1 intervals.
if any(
not isinstance(row, list) or len(row) > OUTPUT_LEN - 1
for row in itls
):
raise HarnessError("request ITL samples exceed output_len-1 chunk intervals")
for name, values in (("ttfts", ttfts), ("start_times", start_times)):
for index, value in enumerate(values):
if require_number(value, f"{name}[{index}]") < 0.0:
raise HarnessError(f"{name} contains a negative value")
for row_index, row in enumerate(itls):
for value_index, value in enumerate(row):
if require_number(value, f"itls[{row_index}][{value_index}]") < 0.0:
raise HarnessError("itls contains a negative value")
bucketed_peak = record.get("max_concurrent_requests")
if isinstance(bucketed_peak, bool) or not isinstance(bucketed_peak, int):
raise HarnessError("max_concurrent_requests is not an integer")
precise_peak = precise_max_concurrent_requests(record)
expected_peak = min(concurrency, expected)
if precise_peak != expected_peak:
raise HarnessError(
f"precise peak concurrency {precise_peak}; expected {expected_peak}"
)
if bucketed_peak < precise_peak:
raise HarnessError("upstream bucketed peak is below precise concurrency")
numeric_fields = (
"duration",
"request_throughput",
"output_throughput",
"total_token_throughput",
"mean_ttft_ms",
"median_ttft_ms",
"p90_ttft_ms",
"p99_ttft_ms",
"mean_tpot_ms",
"median_tpot_ms",
"p90_tpot_ms",
"p99_tpot_ms",
"mean_itl_ms",
"median_itl_ms",
"p90_itl_ms",
"p99_itl_ms",
"mean_e2el_ms",
"median_e2el_ms",
"p90_e2el_ms",
"p99_e2el_ms",
)
for field in numeric_fields:
if require_number(record.get(field), field) < 0.0:
raise HarnessError(f"{field} is negative")
if require_number(record.get("duration"), "duration") <= 0.0:
raise HarnessError("duration must be positive")
def run_benchmark(run: OnlineRun) -> dict[str, Any]:
command = build_client_command(run)
for path in (run.result_path, run.log_path):
if path.exists():
raise HarnessError(f"refusing to overwrite online-gate evidence: {path}")
path.parent.mkdir(parents=True, exist_ok=True)
with run.log_path.open("x", encoding="utf-8", newline="\n") as log:
log.write(f"command: {shlex.join(command)}\n")
log.flush()
completed = subprocess.run(command, stdout=log, stderr=subprocess.STDOUT)
if completed.returncode != 0:
raise HarnessError(f"pinned vLLM client exited {completed.returncode}")
try:
record = json.loads(run.result_path.read_text(encoding="utf-8"))
except FileNotFoundError as error:
raise HarnessError("pinned client did not write its result") from error
except json.JSONDecodeError as error:
raise HarnessError(f"{run.result_path}: invalid JSON: {error}") from error
if not isinstance(record, dict):
raise HarnessError(f"{run.result_path}: result is not an object")
validate_raw_result(
record,
concurrency=run.concurrency,
expected_requests=run.num_prompts,
)
return record
def prepare_corpus_views(
source_root: pathlib.Path,
output_root: pathlib.Path,
*,
model_key: str,
repetitions: tuple[int, ...] | None = None,
) -> dict[str, Any]:
"""Convert the exact-token shared corpus into vLLM CustomDataset rows.
``repetitions`` defaults to the three-rep online-serving grid (resolved at
call time so callers/tests may patch ``REPETITIONS``); the GDN packed
component passes its five-rep domain so the same source corpus yields the
r1..r5 views its 20 timed legs consume.
"""
if repetitions is None:
repetitions = tuple(REPETITIONS)
if model_key not in MODEL_REVISIONS:
raise HarnessError(f"unknown model key: {model_key}")
if sorted(repetitions) != list(range(1, len(repetitions) + 1)):
raise HarnessError(f"corpus repetitions must be 1..N contiguous: {repetitions}")
source_manifest = source_root / "manifest.json"
if not source_manifest.is_file():
raise HarnessError(f"missing source corpus manifest: {source_manifest}")
if output_root.exists() and any(output_root.iterdir()):
raise HarnessError(f"refusing to mix corpus views in non-empty {output_root}")
files: list[dict[str, Any]] = []
prompt_hashes: set[str] = set()
for repetition in repetitions:
for concurrency, expected in POINTS:
source = source_root / f"c{concurrency}-r{repetition}.jsonl"
rows = list(read_jsonl(source))
if len(rows) < expected:
raise HarnessError(
f"{source}: found {len(rows)} rows; expected at least {expected}"
)
converted: list[dict[str, Any]] = []
for index, row in enumerate(rows[:expected]):
conversations = row.get("conversations")
if not isinstance(conversations, list) or not conversations:
raise HarnessError(f"{source}:{index + 1}: no conversation prompt")
first = conversations[0]
prompt = first.get("value") if isinstance(first, dict) else None
token_ids = row.get("prompt_token_ids")
prompt_hash = row.get("prompt_sha256")
if not isinstance(prompt, str):
raise HarnessError(f"{source}:{index + 1}: prompt is not text")
if not isinstance(token_ids, list) or len(token_ids) != INPUT_LEN:
raise HarnessError(f"{source}:{index + 1}: token IDs are not exact")
if not isinstance(prompt_hash, str) or len(prompt_hash) != 64:
raise HarnessError(f"{source}:{index + 1}: prompt hash is invalid")
if prompt_hash in prompt_hashes:
raise HarnessError("online-gate prompt partitions are not disjoint")
prompt_hashes.add(prompt_hash)
if row.get("output_len") != OUTPUT_LEN:
raise HarnessError(f"{source}:{index + 1}: output length drift")
converted.append(
{
"output_tokens": OUTPUT_LEN,
"prompt": prompt,
"prompt_sha256": prompt_hash,
"prompt_token_ids": token_ids,
"source_index": row.get("index"),
}
)
target = output_root / source.name
write_jsonl_atomic(target, converted)
files.append(
{
"concurrency": concurrency,
"file": target.name,
"repetition": repetition,
"requests": expected,
"sha256": sha256_file(target),
"source_sha256": sha256_file(source),
}
)
manifest = {
"files": files,
"format": "vllm-custom-jsonl-v1",
"input_len": INPUT_LEN,
"model_key": model_key,
"output_len": OUTPUT_LEN,
"source_manifest_sha256": sha256_file(source_manifest),
"tokenizer_revision": MODEL_REVISIONS[model_key],
"total_prompts": sum(item["requests"] for item in files),
"vllm_commit": VLLM_COMMIT,
}
write_json_atomic(output_root / "manifest.json", manifest)
return manifest
def build_plan(
*,
claim_root: pathlib.Path,
vllm_cpp_sha: str,
client: pathlib.Path,
) -> dict[str, Any]:
_require_full_sha(vllm_cpp_sha, "vllm.cpp SHA")
trace_model_command = [
"scripts/dgx-online-serving.sh",
"--trace-only",
"--model",
"27",
"--snapshot",
"<27_MODEL_SNAPSHOT>",
"--source-corpus",
"<EVIDENCE>/corpus/27",
"--evidence",
"<EVIDENCE>",
"--build-dir",
"<H1D_TRACE_BUILD>",
"--configure-log",
"<H1D_TRACE_CONFIGURE_LOG>",
"--client",
str(client),
"--vllm-cpp-sha",
vllm_cpp_sha,
]
return {
"artifact_root": str(claim_root / "evidence" / vllm_cpp_sha),
"client": str(client),
"client_contract_source_commit": VLLM_COMMIT,
"dry_run": True,
"generated_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
"gpu_lock_acquisitions_planned": 2,
"host": {
"kernel": platform.release(),
"machine": platform.machine(),
"node": platform.node(),
"python": platform.python_version(),
},
"interleaving": [
{"engine": engine, "repetition": repetition}
for repetition in REPETITIONS
for engine in ENGINES
],
"models": {
key: {
"repository": MODEL_REPOSITORIES[key],
"revision": MODEL_REVISIONS[key],
}
for key in MODEL_REVISIONS
},
"points": [
{"concurrency": concurrency, "num_prompts": prompts}
for concurrency, prompts in POINTS
],
"planned_commands": {
"corpus": [
str(client.parent / "python"),
"-m",
"tools.bench.make_serve_low_corpus",
"--tokenizer-json",
"<MODEL_SNAPSHOT>/tokenizer.json",
"--tokenizer-revision",
"<MODEL_REVISION>",
"--model-key",
"<27|35>",
"--out",
"<EVIDENCE>/corpus/<27|35>",
"--target-input-len",
str(INPUT_LEN),
"--output-len",
str(OUTPUT_LEN),
"--requests-per-partition",
"192",
"--warmup-requests",
"1",
"--concurrencies",
",".join(str(concurrency) for concurrency, _ in POINTS),
"--repetitions",
str(len(REPETITIONS)),
],
"execute_model": [
"BLOCKED_UNTIL_H1D_G4_AND_SEPARATE_PRODUCTION_TRACE_BUILDS"
],
"trace_model": trace_model_command,
"trace_gdn_ba": [
*trace_model_command,
"--trace-concurrency",
"2",
"--gdn-ba-mode",
"both",
],
"trace_gdn_packed": [
*trace_model_command,
"--trace-concurrency",
"2",
"--gdn-packed-mode",
"both",
],
},
"required_artifacts": [
"manifest.json",
"corpus/<model>/vllm/manifest.json",
"execution/<model>.json (production timing only)",
"execution/<model>-trace.json (H1d diagnostic only)",
"execution/<model>-oracle.json",
"execution/<model>-build-command.txt",
"execution/<model>-build.log",
"raw/<model>/<engine>/c<conc>-r<rep>.json",
"logs/<model>/<engine>/c<conc>-r<rep>.log",
"memory/<model>/<engine>/r<rep>.samples.jsonl",
"memory/<model>/<engine>/r<rep>.summary.json",
"thermal/<model>/<engine>/r<rep>-{before,after}.txt",
"cache-drop/<model>/<engine>/r<rep>-{before,after}.json",
"memory-return/<model>/<engine>/r<rep>.json",
"trace/<model>/ours-r{1,2,3}.{1,2,3,4}.nsys-rep",
"trace/<model>/ours-r{1,2,3}.{1,2,3,4}.sqlite",
"trace/<model>/ours-r{1,2,3}.{1,2,3,4}-cuda_gpu_kern_sum.txt",
"trace/<model>/ours-r{1,2,3}.{1,2,3,4}-nsys-validation.json",
"trace/<model>/ours-r{1,2,3}-profile-control.json",
"raw/<model>/ours/c16-r1-trace{1,2,3}-probe.json",
"trace/<model>/vllm-profile/*.pt.trace.json.gz",
"trace/<model>/vllm-kernels.json",
"trace/<model>/cache-{before-ours,between-engines,after-vllm}.json",
"trace/<model>/status.json",
"trace/27/gdn-ba-{merged,split}/ours-r{1,2,3}.{1,2,3,4}.nsys-rep",
"trace/27/gdn-ba-{merged,split}/vllm-profile/*.pt.trace.json.gz",
"trace/27/{gdn-ba-summary,gdn-ba-manifest,status-gdn-ba}.json",
"trace/27/gdn-{packed,rollback}/ours-r{1,2,3}.{1,2,3,4}.nsys-rep",
"trace/27/gdn-{packed,rollback}/vllm-profile/*.pt.trace.json.gz",