-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinference.py
More file actions
1874 lines (1735 loc) · 73 KB
/
Copy pathinference.py
File metadata and controls
1874 lines (1735 loc) · 73 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
from __future__ import annotations
import json
import math
from collections.abc import Iterator
from pathlib import Path
from statistics import median
from typing import Annotated, Any, Literal
import ijson
from ijson import IncompleteJSONError, JSONError
from pydantic import (
ConfigDict,
Field,
StrictFloat,
StrictInt,
ValidationError,
field_validator,
model_validator,
)
from flameox.domain import (
ArtifactKind,
DomainError,
ErrorCode,
EvidenceLevel,
RunType,
digest_model,
)
from flameox.evidence import (
CancelledInferenceRequestOutcome,
FailedInferenceRequestOutcome,
GenerationPublisher,
InferenceRequestItem,
ReportedInferenceRequestOutcome,
SucceededInferenceRequestOutcome,
inference_request_outcome_columns,
)
from flameox.models import ContractModel
from flameox.storage import ArtifactStore, RunStore, Workspace
# ---------------------------------------------------------------------------
# Mooncake streaming JSONL request-trace validation
# ---------------------------------------------------------------------------
#
# The Mooncake request trace (see kvcache-ai/Mooncake ``mooncake_trace.jsonl``
# and kobe0938/mooncake-trace-replayer) is a JSON Lines stream where each line
# is one request with four observed fields:
#
# {"timestamp": <int ms>, "input_length": <int>, "output_length": <int>,
# "hash_ids": [<int>, ...]}
#
# The parser validates the stream incrementally and yields one typed row per
# line. It never reads the whole file into memory: rows are produced as lines
# are consumed so a truncated or oversized trace fails fast with an explicit
# limitation rather than OOM. The caller bounds consumption via ``max_rows``.
_REQUIRED_FIELDS = frozenset({"timestamp", "input_length", "output_length"})
_SAFE_ERROR_CATEGORIES = {
"authentication",
"cancelled",
"connection",
"invalid_request",
"not_found",
"permission_denied",
"rate_limited",
"server_error",
"timeout",
"unavailable",
}
def _safe_error_category(value: Any) -> str:
"""Reduce provider-owned error text to a fixed, non-sensitive category."""
if not isinstance(value, str):
return "provider_error"
normalized = value.strip().lower().replace("-", "_").replace(" ", "_")
if normalized in _SAFE_ERROR_CATEGORIES:
return normalized
checks = (
(("timeout", "timed_out", "deadline"), "timeout"),
(("cancel",), "cancelled"),
(("rate_limit", "throttl"), "rate_limited"),
(("unauthor", "authenticat"), "authentication"),
(("forbidden", "permission"), "permission_denied"),
(("connect", "network"), "connection"),
(("validation", "invalid", "bad_request"), "invalid_request"),
(("not_found",), "not_found"),
(("unavailable",), "unavailable"),
(("server", "internal"), "server_error"),
)
for needles, category in checks:
if any(needle in normalized for needle in needles):
return category
return "provider_error"
def _safe_error_code(value: Any) -> str | None:
"""Keep bounded numeric status codes; collapse all provider strings."""
if isinstance(value, int) and not isinstance(value, bool) and 0 <= value <= 999:
return str(value)
if isinstance(value, str):
stripped = value.strip()
if stripped.isascii() and stripped.isdecimal() and len(stripped) <= 3:
numeric = int(stripped)
if 0 <= numeric <= 999:
return str(numeric)
return _safe_error_category(stripped)
return None
class MooncakeRequestRow(ContractModel):
"""One validated, typed request extracted from a Mooncake trace line."""
schema_version: Literal[1] = 1
request_id: str
line_index: Annotated[int, Field(ge=0)]
timestamp_ms: Annotated[int, Field(ge=0)]
input_length: Annotated[int, Field(ge=0)]
output_length: Annotated[int, Field(ge=0)]
prefix_hash_count: Annotated[int, Field(ge=0)]
evidence_level: EvidenceLevel = EvidenceLevel.OBSERVED
class MooncakeTraceSummary(ContractModel):
"""Bounded summary of a parsed Mooncake trace stream."""
schema_version: int = 1
request_count: int
prefix_hash_count: int
max_input_length: int
max_output_length: int
timestamp_span_ms: int
limitations: tuple[str, ...] = ()
class MooncakeTraceParser:
"""Streaming validator and normalizer for Mooncake request-trace JSONL.
``iter_rows`` yields validated :class:`MooncakeRequestRow` objects one line
at a time without loading the entire file. ``parse`` consumes up to
``max_rows`` lines and returns a bounded summary plus the materialized rows.
"""
max_line_bytes = 64 * 1024
def __init__(self, max_rows: int = 1_000_000) -> None:
if max_rows <= 0:
raise ValueError("max_rows must be positive")
self.max_rows = max_rows
self.truncated = False
def iter_rows(self, path: Path) -> Iterator[MooncakeRequestRow]:
"""Yield validated rows from a Mooncake trace JSONL file streamingly."""
try:
with path.open("rb") as stream:
index = 0
while raw := stream.readline(self.max_line_bytes + 1):
if not raw.strip():
index += 1
continue
if len(raw) > self.max_line_bytes:
raise ValueError(
f"trace line {index} exceeds the {self.max_line_bytes}-byte limit"
)
yield self._row_from_line(raw, index)
index += 1
except (OSError, UnicodeDecodeError, json.JSONDecodeError, ValueError) as exc:
raise DomainError(
ErrorCode.ARTIFACT_PARSE_FAILED,
"The Mooncake trace artifact is not a valid JSONL request stream.",
) from exc
def parse(self, path: Path) -> tuple[MooncakeTraceSummary, list[MooncakeRequestRow]]:
"""Consume up to ``max_rows`` lines and return a bounded summary."""
rows: list[MooncakeRequestRow] = []
limitations: list[str] = []
first_timestamp: int | None = None
last_timestamp: int | None = None
iterator = iter(self.iter_rows(path))
while len(rows) < self.max_rows:
try:
row = next(iterator)
except StopIteration:
break
if first_timestamp is None:
first_timestamp = row.timestamp_ms
if last_timestamp is not None and row.timestamp_ms < last_timestamp:
limitations.append(
f"Request {row.line_index} timestamp regressed below the prior line."
)
last_timestamp = row.timestamp_ms
rows.append(row)
if len(rows) == self.max_rows:
try:
next(iterator)
except StopIteration:
pass
else:
limitations.append(f"Trace truncated at {self.max_rows} requests.")
if not rows:
raise DomainError(
ErrorCode.ARTIFACT_PARSE_FAILED,
"The Mooncake trace artifact contains no request lines.",
)
if first_timestamp is not None and first_timestamp != 0:
limitations.append("The first request timestamp is not zero milliseconds.")
timestamps = [row.timestamp_ms for row in rows]
return (
MooncakeTraceSummary(
request_count=len(rows),
prefix_hash_count=sum(row.prefix_hash_count for row in rows),
max_input_length=max(row.input_length for row in rows),
max_output_length=max(row.output_length for row in rows),
timestamp_span_ms=max(timestamps) - min(timestamps),
limitations=tuple(dict.fromkeys(limitations)),
),
rows,
)
def _row_from_line(self, raw: bytes, index: int) -> MooncakeRequestRow:
entry = json.loads(raw)
timestamp, input_length, output_length, hash_ids = self._validate_entry(entry, index)
identity = {
"line_index": index,
"timestamp_ms": timestamp,
"input_length": input_length,
"output_length": output_length,
"hash_ids": hash_ids,
}
return MooncakeRequestRow(
request_id=digest_model(identity),
line_index=index,
timestamp_ms=timestamp,
input_length=input_length,
output_length=output_length,
prefix_hash_count=len(hash_ids),
)
@staticmethod
def _validate_entry(entry: Any, index: int) -> tuple[int, int, int, list[int]]:
if not isinstance(entry, dict):
raise ValueError(f"trace line {index} is not a JSON object")
missing = _REQUIRED_FIELDS.difference(entry)
if missing:
raise ValueError(f"trace line {index} is missing required fields: {sorted(missing)}")
timestamp = entry["timestamp"]
input_length = entry["input_length"]
output_length = entry["output_length"]
hash_ids = entry.get("hash_ids", [])
if not isinstance(timestamp, int) or isinstance(timestamp, bool) or timestamp < 0:
raise ValueError(f"trace line {index} timestamp must be a non-negative int")
if not isinstance(input_length, int) or isinstance(input_length, bool) or input_length < 0:
raise ValueError(f"trace line {index} input_length must be a non-negative int")
if (
not isinstance(output_length, int)
or isinstance(output_length, bool)
or output_length < 0
):
raise ValueError(f"trace line {index} output_length must be a non-negative int")
if not isinstance(hash_ids, list):
raise ValueError(f"trace line {index} hash_ids must be a list")
for value in hash_ids:
if not isinstance(value, int) or isinstance(value, bool) or value < 0:
raise ValueError(f"trace line {index} hash_ids must be non-negative ints")
return timestamp, input_length, output_length, hash_ids
class AIPerfRequestRow(ContractModel):
"""One AIPerf request whose export always reports a concrete outcome."""
source_request_id: str
provider_request_id: str | None
input_tokens: Annotated[int, Field(ge=0)]
output_tokens: Annotated[int, Field(ge=0)]
scheduled_ns: Annotated[int, Field(ge=0)] | None
observed_started_ns: Annotated[int, Field(ge=0)]
ttft_ns: Annotated[int, Field(ge=0)] | None
latency_ns: Annotated[int, Field(ge=0)] | None
tpot_ns: Annotated[int, Field(ge=0)] | None
mean_itl_ns: Annotated[int, Field(ge=0)] | None
outcome: ReportedInferenceRequestOutcome = Field(exclude=True)
queue_ns: None = None
prefill_ns: None = None
decode_ns: None = None
cache_hit: None = None
prefix_hash_count: None = None
evidence_level: EvidenceLevel = EvidenceLevel.OBSERVED
line_index: Annotated[int, Field(ge=0)]
@property
def success(self) -> bool:
success = inference_request_outcome_columns(self.outcome).success
assert success is not None
return success
@property
def cancelled(self) -> bool:
cancelled = inference_request_outcome_columns(self.outcome).cancelled
assert cancelled is not None
return cancelled
@property
def error_type(self) -> str | None:
return inference_request_outcome_columns(self.outcome).error_type
@property
def error_code(self) -> str | None:
return inference_request_outcome_columns(self.outcome).error_code
def evidence_columns(self) -> dict[str, Any]:
columns = self.model_dump(mode="python", exclude={"line_index"})
columns.update(
{
"success": self.success,
"cancelled": self.cancelled,
"error_type": self.error_type,
"error_code": self.error_code,
}
)
return columns
class AIPerfRecordParser:
"""Stream AIPerf 0.12 record exports without retaining provider payloads."""
max_line_bytes = 1024 * 1024
def __init__(self, max_rows: int = 1_000_000) -> None:
if max_rows <= 0:
raise ValueError("max_rows must be positive")
self.max_rows = max_rows
def iter_rows(
self, path: Path, *, inputs_index: AIPerfInputsIndex | None = None
) -> Iterator[AIPerfRequestRow]:
self.truncated = False
self._inputs_index = inputs_index
self._corr_matched = 0
self._corr_missing_session = 0
self._corr_turn_out_of_range = 0
self._corr_no_id = 0
record_count = 0
try:
with path.open("rb") as stream:
line_index = 0
while raw := stream.readline(self.max_line_bytes + 1):
if not raw.strip():
line_index += 1
continue
if record_count >= self.max_rows:
self.truncated = True
break
if len(raw) > self.max_line_bytes:
raise ValueError(f"record line {line_index} exceeds the byte limit")
payload = json.loads(raw)
if not isinstance(payload, dict):
raise ValueError(f"record line {line_index} is not an object")
if inputs_index is not None:
self._correlate(payload, inputs_index)
yield self._normalize(payload, line_index)
record_count += 1
line_index += 1
except (OSError, UnicodeDecodeError, json.JSONDecodeError, ValueError) as exc:
raise DomainError(
ErrorCode.ARTIFACT_PARSE_FAILED,
"The AIPerf profile export violates the supported 0.12 record schema.",
) from exc
def _correlate(self, payload: dict[str, Any], index: AIPerfInputsIndex) -> None:
"""Track correlation status against the inputs index without modifying the row.
Called before ``_normalize`` so the raw ``metadata`` is available for the
``conversation_id`` / ``turn_index`` lookup. Counts are stored on the
parser instance and read by :meth:`correlation_summary`.
"""
metadata = payload.get("metadata")
if not isinstance(metadata, dict):
self._corr_no_id += 1
return
conversation_id = metadata.get("conversation_id")
turn_index = metadata.get("turn_index")
if (
not isinstance(conversation_id, str)
or not isinstance(turn_index, int)
or isinstance(turn_index, bool)
):
self._corr_no_id += 1
return
if not index.has_session(conversation_id):
self._corr_missing_session += 1
return
if not index.has_turn(conversation_id, turn_index):
self._corr_turn_out_of_range += 1
return
self._corr_matched += 1
def correlation_summary(self, inputs_index: AIPerfInputsIndex) -> AIPerfCorrelationSummary:
"""Build a typed correlation summary from the counts accumulated during iteration."""
limitations: list[str] = []
if self._corr_missing_session > 0:
limitations.append(
f"{self._corr_missing_session} requests had no matching session in inputs.json."
)
if self._corr_turn_out_of_range > 0:
limitations.append(
f"{self._corr_turn_out_of_range} requests had a turn_index outside the "
"inputs.json payload range."
)
if self._corr_no_id > 0:
limitations.append(
f"{self._corr_no_id} requests lacked conversation_id and could not be correlated."
)
return AIPerfCorrelationSummary(
inputs_session_count=inputs_index.session_count,
matched_count=self._corr_matched,
missing_session_count=self._corr_missing_session,
turn_out_of_range_count=self._corr_turn_out_of_range,
no_correlation_id_count=self._corr_no_id,
limitations=tuple(limitations),
)
@staticmethod
def _metric(metrics: Any, name: str) -> tuple[float, str] | None:
if not isinstance(metrics, dict):
return None
item = metrics.get(name)
if not isinstance(item, dict):
return None
value, unit = item.get("value"), item.get("unit")
if (
isinstance(value, bool)
or not isinstance(value, int | float)
or not isinstance(unit, str)
):
return None
if not math.isfinite(float(value)):
return None
return float(value), unit
@staticmethod
def _duration_ns(metric: tuple[float, str] | None) -> int | None:
if metric is None:
return None
value, unit = metric
factors = {"ns": 1.0, "us": 1_000.0, "µs": 1_000.0, "ms": 1_000_000.0, "s": 1e9}
factor = factors.get(unit)
return round(value * factor) if factor is not None and value >= 0 else None
@classmethod
def _normalize(cls, payload: dict[str, Any], line_index: int) -> AIPerfRequestRow:
metadata, metrics = payload.get("metadata"), payload.get("metrics")
if not isinstance(metadata, dict) or not isinstance(metrics, dict):
raise ValueError("metadata and metrics must be objects")
def integer(name: str, *, required: bool = False) -> int | None:
value = metadata.get(name)
if value is None and not required:
return None
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
raise ValueError(f"metadata.{name} must be a non-negative integer")
return value
session_num = integer("session_num", required=True)
request_start_ns = integer("request_start_ns", required=True)
assert session_num is not None
assert request_start_ns is not None
input_metric = cls._metric(metrics, "input_sequence_length")
output_metric = cls._metric(metrics, "output_sequence_length")
if input_metric is None or output_metric is None:
raise ValueError("token count metrics are required")
input_tokens, output_tokens = round(input_metric[0]), round(output_metric[0])
if input_tokens < 0 or output_tokens < 0:
raise ValueError("token counts must be non-negative")
conversation_id = metadata.get("conversation_id")
turn_index = integer("turn_index")
source_request_id = (
f"{conversation_id}:{turn_index}"
if isinstance(conversation_id, str) and turn_index is not None
else str(session_num)
)
error = payload.get("error")
if error is not None and not isinstance(error, dict):
raise ValueError("error must be an object or null")
cancelled = metadata.get("was_cancelled", False)
if not isinstance(cancelled, bool):
raise ValueError("metadata.was_cancelled must be a boolean")
latency_ns = cls._duration_ns(cls._metric(metrics, "request_latency"))
ttft_ns = cls._duration_ns(cls._metric(metrics, "time_to_first_token"))
tpot_ns = (
round((latency_ns - ttft_ns) / (output_tokens - 1))
if latency_ns is not None
and ttft_ns is not None
and latency_ns >= ttft_ns
and output_tokens > 1
else None
)
error_type = _safe_error_category(error.get("type")) if isinstance(error, dict) else None
error_code = _safe_error_code(error.get("code")) if isinstance(error, dict) else None
outcome: ReportedInferenceRequestOutcome
if cancelled:
outcome = CancelledInferenceRequestOutcome(
error_type=error_type,
error_code=error_code,
)
elif error is not None:
outcome = FailedInferenceRequestOutcome(
error_type=error_type,
error_code=error_code,
)
else:
outcome = SucceededInferenceRequestOutcome()
return AIPerfRequestRow(
source_request_id=source_request_id,
provider_request_id=(
metadata.get("x_request_id")
if isinstance(metadata.get("x_request_id"), str)
else None
),
input_tokens=input_tokens,
output_tokens=output_tokens,
scheduled_ns=integer("credit_issued_ns"),
observed_started_ns=request_start_ns,
ttft_ns=ttft_ns,
latency_ns=latency_ns,
tpot_ns=tpot_ns,
mean_itl_ns=cls._duration_ns(cls._metric(metrics, "inter_token_latency")),
outcome=outcome,
line_index=line_index,
)
# ---------------------------------------------------------------------------
# AIPerf inputs.json correlation
# ---------------------------------------------------------------------------
#
# AIPerf's ``inputs.json`` is the complete input dataset with formatted payloads
# for each request (see ai-dynamo/aiperf ``working-with-profile-export-files``).
# Its structure is::
#
# {"data": [{"session_id": "<uuid>", "payloads": [<turn-0>, <turn-1>, ...]}]}
#
# Each ``profile_export.jsonl`` record carries ``metadata.conversation_id`` and
# ``metadata.turn_index`` that map to ``session_id`` and the ``payloads`` array
# index. The correlation index retains only ``session_id -> turn_count`` — never
# prompt text, tool definitions, or request bodies.
#
# Parsing uses low-level ``ijson.parse`` events so that no session dict or
# payload object is ever materialized. The event stream is processed in a single
# pass: ``session_id`` is captured from ``data.item.session_id`` string events,
# turn counts are derived by counting ``data.item.payloads.item`` start events,
# and all nested payload content events (prompts, tool definitions, etc.) are
# discarded without being built into Python objects. Peak memory is bounded by
# the fixed ijson chunk buffer plus the largest single string value that ijson
# accumulates, not by the total document or session size.
class AIPerfInputsIndex:
"""Bounded correlation index for AIPerf ``inputs.json``, retaining no payloads.
The index maps ``session_id`` to the number of turns (payloads) declared for
that session. The file is parsed via low-level ``ijson.parse`` events so no
session dict or payload object is ever materialized; only ``session_id``
strings and turn counts are retained.
"""
max_input_bytes = 256 * 1024 * 1024
max_sessions = 100_000
max_turns_per_session = 10_000
max_nesting_depth = 64
max_session_id_length = 256
stream_buffer_bytes = 65_536
def __init__(self, session_turn_counts: dict[str, int]) -> None:
self.session_turn_counts = dict(session_turn_counts)
@classmethod
def from_path(cls, path: Path) -> AIPerfInputsIndex:
"""Stream ``inputs.json`` via ``ijson.parse`` events and build a correlation index.
Processes the binary file as a stream of ``(prefix, event, value)``
tuples without materializing any session dict or payload object.
``session_id`` is captured from ``data.item.session_id`` string events;
turn counts are derived by counting ``data.item.payloads.item`` start
events. All nested payload content is discarded. Bounds: file size,
nesting depth, session ID length, session count, turns per session.
"""
try:
size = path.stat().st_size
except OSError as exc:
raise DomainError(
ErrorCode.ARTIFACT_PARSE_FAILED,
"The AIPerf inputs artifact is not accessible.",
) from exc
if size > cls.max_input_bytes:
raise DomainError(
ErrorCode.ARTIFACT_PARSE_FAILED,
f"The AIPerf inputs artifact exceeds the {cls.max_input_bytes}-byte limit.",
)
index: dict[str, int] = {}
try:
with path.open("rb") as stream:
saw_data_array = cls._stream_events(stream, index)
if not saw_data_array:
raise DomainError(
ErrorCode.ARTIFACT_PARSE_FAILED,
"The AIPerf inputs artifact must be an object with a data array.",
)
except (OSError, UnicodeDecodeError, IncompleteJSONError, JSONError) as exc:
raise DomainError(
ErrorCode.ARTIFACT_PARSE_FAILED,
"The AIPerf inputs artifact is not a valid JSON document.",
) from exc
return cls(index)
@classmethod
def _stream_events(cls, stream: Any, index: dict[str, int]) -> bool:
"""Process ``ijson.parse`` events in a single pass, populating ``index``.
Returns ``True`` if a top-level ``data`` array was seen. Raises
:class:`DomainError` on any structural violation or bound breach.
"""
parser = ijson.parse(stream, buf_size=cls.stream_buffer_bytes)
depth = 0
saw_data_array = False
in_session = False
current_session_id: str | None = None
saw_session_id = False
saw_payloads = False
in_payloads = False
current_turn_count = 0
for prefix, event, value in parser:
depth = cls._track_depth(event, depth)
saw_data_array = cls._track_top_level(prefix, event, saw_data_array)
cls._reject_non_object_data_item(prefix, event)
if prefix == "data.item" and event == "start_map":
cls._check_session_limit(index)
in_session = True
current_session_id = None
saw_session_id = False
saw_payloads = False
current_turn_count = 0
current_session_id, saw_session_id = cls._capture_session_id(
prefix, event, value, current_session_id, saw_session_id
)
saw_payloads, in_payloads = cls._track_payloads(
prefix, event, saw_payloads, in_payloads
)
current_turn_count = cls._count_payload_item(
prefix, event, in_payloads, current_turn_count, current_session_id
)
if prefix == "data.item" and event == "end_map" and in_session:
cls._store_session(
index,
current_session_id,
saw_session_id,
saw_payloads,
current_turn_count,
)
in_session = False
return saw_data_array
@classmethod
def _track_depth(cls, event: str, depth: int) -> int:
if event in ("start_map", "start_array"):
depth += 1
if depth > cls.max_nesting_depth:
raise DomainError(
ErrorCode.ARTIFACT_PARSE_FAILED,
f"The AIPerf inputs artifact exceeds the "
f"{cls.max_nesting_depth}-depth nesting limit.",
)
elif event in ("end_map", "end_array"):
depth -= 1
return depth
@classmethod
def _track_top_level(cls, prefix: str, event: str, saw_data_array: bool) -> bool:
if prefix == "data" and event == "start_array":
return True
return saw_data_array
@classmethod
def _reject_non_object_data_item(cls, prefix: str, event: str) -> None:
if prefix == "data.item" and event not in ("start_map", "end_map", "map_key"):
raise DomainError(
ErrorCode.ARTIFACT_PARSE_FAILED,
"Each AIPerf inputs data entry must be an object.",
)
@classmethod
def _check_session_limit(cls, index: dict[str, int]) -> None:
if len(index) >= cls.max_sessions:
raise DomainError(
ErrorCode.ARTIFACT_PARSE_FAILED,
f"The AIPerf inputs artifact exceeds the {cls.max_sessions}-session limit.",
)
@classmethod
def _capture_session_id(
cls,
prefix: str,
event: str,
value: Any,
current_session_id: str | None,
saw_session_id: bool,
) -> tuple[str | None, bool]:
if prefix != "data.item.session_id":
return current_session_id, saw_session_id
if saw_session_id:
raise DomainError(
ErrorCode.ARTIFACT_PARSE_FAILED,
"Each AIPerf inputs data entry must have exactly one session_id.",
)
if event != "string":
raise DomainError(
ErrorCode.ARTIFACT_PARSE_FAILED,
"Each AIPerf inputs data entry must have a string session_id.",
)
if not isinstance(value, str) or not value:
raise DomainError(
ErrorCode.ARTIFACT_PARSE_FAILED,
"Each AIPerf inputs data entry must have a non-empty session_id.",
)
if len(value) > cls.max_session_id_length:
raise DomainError(
ErrorCode.ARTIFACT_PARSE_FAILED,
f"Session_id length exceeds the {cls.max_session_id_length}-character limit.",
)
return value, True
@classmethod
def _track_payloads(
cls, prefix: str, event: str, saw_payloads: bool, in_payloads: bool
) -> tuple[bool, bool]:
if prefix == "data.item.payloads":
if event not in ("start_array", "end_array"):
raise DomainError(
ErrorCode.ARTIFACT_PARSE_FAILED,
"Each AIPerf inputs data entry must have a payloads array.",
)
if event == "start_array":
return True, True
return saw_payloads, False
return saw_payloads, in_payloads
@classmethod
def _count_payload_item(
cls,
prefix: str,
event: str,
in_payloads: bool,
current_turn_count: int,
current_session_id: str | None,
) -> int:
if not (
in_payloads
and prefix == "data.item.payloads.item"
and event not in ("end_map", "end_array", "map_key")
):
return current_turn_count
current_turn_count += 1
if current_turn_count > cls.max_turns_per_session:
raise DomainError(
ErrorCode.ARTIFACT_PARSE_FAILED,
f"Session {current_session_id!r} has more than {cls.max_turns_per_session} turns.",
)
return current_turn_count
@classmethod
def _store_session(
cls,
index: dict[str, int],
current_session_id: str | None,
saw_session_id: bool,
saw_payloads: bool,
current_turn_count: int,
) -> None:
if not saw_session_id or current_session_id is None:
raise DomainError(
ErrorCode.ARTIFACT_PARSE_FAILED,
"Each AIPerf inputs data entry must have a non-empty session_id.",
)
if not saw_payloads:
raise DomainError(
ErrorCode.ARTIFACT_PARSE_FAILED,
"Each AIPerf inputs data entry must have a payloads array.",
)
if current_session_id in index:
raise DomainError(
ErrorCode.ARTIFACT_PARSE_FAILED,
f"Duplicate session_id {current_session_id!r} in AIPerf inputs.",
)
index[current_session_id] = current_turn_count
def has_session(self, session_id: str) -> bool:
return session_id in self.session_turn_counts
def has_turn(self, session_id: str, turn_index: int) -> bool:
count = self.session_turn_counts.get(session_id)
return count is not None and 0 <= turn_index < count
@property
def session_count(self) -> int:
return len(self.session_turn_counts)
class AIPerfCorrelationSummary(ContractModel):
"""Typed summary of correlating ``profile_export`` records against ``inputs.json``."""
schema_version: Literal[1] = 1
inputs_session_count: int
matched_count: int
missing_session_count: int
turn_out_of_range_count: int
no_correlation_id_count: int
limitations: tuple[str, ...] = ()
# ---------------------------------------------------------------------------
# vLLM aggregate benchmark-result JSON normalization
# ---------------------------------------------------------------------------
#
def _percentile_label(percentile: int | float) -> str:
"""Return a canonical label for a percentile rank, preserving fractional precision.
``int()`` truncation made p99.1 and p99.9 both produce ``p99``, losing
the exact percentile identity in the metric name.
"""
if float(percentile).is_integer():
return str(int(percentile))
return str(float(percentile))
# vLLM's ``benchmark_serving.BenchmarkMetrics`` dataclass is serialized by the
# Mooncake replayer (and other vLLM benchmark scripts) as a JSON object whose
# percentile fields are lists of ``[percentile, value_ms]`` pairs. The parser
# normalizes the aggregate metrics into bounded, typed measurement rows without
# preserving raw prompt text, error strings, or request payloads.
_VllmPercentile = tuple[StrictInt | StrictFloat, StrictInt | StrictFloat]
class VllmAggregateMetrics(ContractModel):
"""The ``BenchmarkMetrics`` dataclass shape serialized by vLLM scripts."""
model_config = ConfigDict(extra="ignore")
completed: Annotated[int, Field(ge=0)]
total_input: Annotated[int, Field(ge=0)]
total_output: Annotated[int, Field(ge=0)]
request_throughput: Annotated[float, Field(ge=0)]
request_goodput: Annotated[float, Field(ge=0)] | None = None
output_throughput: Annotated[float, Field(ge=0)]
total_token_throughput: Annotated[float, Field(ge=0)]
mean_ttft_ms: float
median_ttft_ms: float
std_ttft_ms: float
percentiles_ttft_ms: tuple[_VllmPercentile, ...] = ()
mean_tpot_ms: float
median_tpot_ms: float
std_tpot_ms: float
percentiles_tpot_ms: tuple[_VllmPercentile, ...] = ()
mean_itl_ms: float
median_itl_ms: float
std_itl_ms: float
percentiles_itl_ms: tuple[_VllmPercentile, ...] = ()
mean_e2el_ms: float
median_e2el_ms: float
std_e2el_ms: float
percentiles_e2el_ms: tuple[_VllmPercentile, ...] = ()
@field_validator(
"request_throughput",
"request_goodput",
"output_throughput",
"total_token_throughput",
mode="before",
)
@classmethod
def finite_throughput(cls, value: Any) -> Any:
if value is None:
return value
if isinstance(value, bool) or not isinstance(value, int | float):
raise ValueError("throughput metrics must be JSON numbers")
if not math.isfinite(float(value)):
raise ValueError("throughput metrics must be finite")
return value
@field_validator(
"mean_ttft_ms",
"median_ttft_ms",
"std_ttft_ms",
"mean_tpot_ms",
"median_tpot_ms",
"std_tpot_ms",
"mean_itl_ms",
"median_itl_ms",
"std_itl_ms",
"mean_e2el_ms",
"median_e2el_ms",
"std_e2el_ms",
)
@classmethod
def finite_latency(cls, value: float) -> float:
if not math.isfinite(value):
raise ValueError("latency metrics must be finite")
return value
@model_validator(mode="after")
def non_negative_latency(self) -> VllmAggregateMetrics:
for name in (
"mean_ttft_ms",
"median_ttft_ms",
"mean_tpot_ms",
"median_tpot_ms",
"mean_itl_ms",
"median_itl_ms",
"mean_e2el_ms",
"median_e2el_ms",
"std_ttft_ms",
"std_tpot_ms",
"std_itl_ms",
"std_e2el_ms",
):
if getattr(self, name) < 0:
raise ValueError(f"{name} must be non-negative")
return self
@field_validator(
"percentiles_ttft_ms",
"percentiles_tpot_ms",
"percentiles_itl_ms",
"percentiles_e2el_ms",
)
@classmethod
def valid_percentiles(cls, values: tuple[_VllmPercentile, ...]) -> tuple[_VllmPercentile, ...]:
for percentile, latency_ms in values:
if not 0 <= float(percentile) <= 100 or not math.isfinite(float(percentile)):
raise ValueError("percentile ranks must be finite values from 0 through 100")
if latency_ms < 0 or not math.isfinite(float(latency_ms)):
raise ValueError("percentile latency values must be finite and non-negative")
return values
class VllmResultDocument(ContractModel):
"""The wrapper emitted by the Mooncake replayer around vLLM metrics.
The replayer stores ``{"metrics": <BenchmarkMetrics.asdict>, ...counts}``.
Only the bounded aggregate metrics are normalized; raw request payloads,
error text, and server endpoints are deliberately dropped.
"""
model_config = ConfigDict(extra="ignore")
metrics: VllmAggregateMetrics
successful_requests: Annotated[int, Field(ge=0)]
failed_requests: Annotated[int, Field(ge=0)]
total_requests: Annotated[int, Field(ge=0)]
actual_duration: Annotated[float, Field(ge=0)]
time_scale: Annotated[float, Field(gt=0)] = 1.0
@field_validator("actual_duration", "time_scale")
@classmethod
def finite_duration_and_scale(cls, value: float) -> float:
if not math.isfinite(value):
raise ValueError("duration and time_scale must be finite")
return value
@model_validator(mode="after")
def totals_match(self) -> VllmResultDocument:
if self.successful_requests + self.failed_requests != self.total_requests:
raise ValueError("successful plus failed requests must equal total requests")
if self.successful_requests != self.metrics.completed:
raise ValueError("successful_requests must equal metrics.completed")
return self
class VllmMeasurementRow(ContractModel):
"""One normalized measurement derived from a vLLM aggregate result."""
schema_version: Literal[1] = 1
measurement_id: str
name: str
value_float: float
unit: str
aggregation: str
dimensions: dict[str, str]
evidence_level: EvidenceLevel = EvidenceLevel.DERIVED
class VllmResultParser:
"""Validate a vLLM aggregate benchmark-result JSON document and normalize it.
The parser reads the document once, validates it against the bounded
:class:`VllmResultDocument` schema, and produces typed measurement rows.
Raw prompt text, error strings, and server endpoints are never preserved.
"""
max_document_bytes = 16 * 1024 * 1024