-
Notifications
You must be signed in to change notification settings - Fork 490
Expand file tree
/
Copy pathperfetto.py
More file actions
executable file
·1296 lines (1137 loc) · 43.4 KB
/
perfetto.py
File metadata and controls
executable file
·1296 lines (1137 loc) · 43.4 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
# Copyright © 2019-2023
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
vortex_perfetto.py
Convert Vortex GPU RTL or SimX log traces into a Perfetto-compatible trace
(Chrome Trace JSON).
Design goals (per Vortex project requirements)
- One unified output schema regardless of log type (-t/--type).
- Two separate parsers (RTL vs SimX) that emit the same intermediate events.
- Streaming JSON writer (low memory) with optional gzip compression.
- Optional value capture controlled by a single type-agnostic switch:
--values {none,dest,all}
By default, only destination values are captured, and dest_value is attached
ONLY to the commit stage marker.
Usage examples
# SimX (default), compressed:
python3 vortex_perfetto.py run_simx.log -c -o vortex.perfetto.json.gz
# RTL sim:
python3 vortex_perfetto.py run.log -t rtlsim -c -o vortex.perfetto.json.gz
# Limit export to a cycle window:
python3 vortex_perfetto.py run.log -t rtlsim --cycle-min 10000 --cycle-max 20000 -c -o win.json.gz
Open in Perfetto UI
- Web UI: https://ui.perfetto.dev (load the .json or .json.gz)
- VS Code: install a Perfetto trace viewer extension and open the .json/.json.gz.
Notes
- Cache payloads are intentionally NOT captured (too costly). Only hit/miss/fill/writeback
and lightweight req/rsp events are recorded when present.
- RTL tmask bit ordering is normalized to match SimX convention (bit0 == thread0).
"""
from __future__ import annotations
import argparse
import gzip
import io
import json
import re
import sys
from itertools import chain
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, Iterable, Iterator, List, Optional, Tuple
# -----------------------------
# Intermediate Representation
# -----------------------------
STAGES_CANON = {"schedule", "fetch", "decode", "issue", "dispatch", "operands", "execute", "commit"}
# Canonical pipeline order, shared by SimX and RTL. Emitted as a 'stage_idx' arg
# so stage markers can be aligned numerically across simulators even though each
# sim observes a different subset (SimX has issue/operands; RTL has fetch).
STAGE_INDEX = {
"schedule": 0, "fetch": 1, "decode": 2, "issue": 3,
"operands": 4, "dispatch": 5, "execute": 6, "commit": 7,
}
@dataclass
class InstructionStageEvent:
ts: int
path: str
stage: str
uuid: int
wid: Optional[int] = None
pc: Optional[str] = None
ex: Optional[str] = None
op: Optional[str] = None
wb: Optional[int] = None
tmask: Optional[str] = None
sop: int = 1
eop: int = 1
# Sub-phase within a stage when the stage is observed more than once per
# instruction (RTL fetch is logged as both 'req' and 'rsp').
phase: Optional[str] = None
parent_uuid: Optional[int] = None
# Canonical reg names (x/f/v) when known
rd: Optional[str] = None
rs1: Optional[str] = None
rs2: Optional[str] = None
rs3: Optional[str] = None
# Values (emitted by Perfetto emitter according to --values)
src_values: Optional[List[Dict[str, str]]] = None # [{"reg": "...", "value": "..."}]
dest_value: Optional[Dict[str, str]] = None # {"reg": "...", "value": "..."} (commit only)
@dataclass
class WarpStateEvent:
ts: int
path: str
wid: int
active: Optional[int] = None
stalled: Optional[int] = None
tmask: Optional[str] = None
@dataclass
class CacheEvent:
ts: int
path: str
level: str # icache/dcache/l2/l3/mem/unknown
kind: str # hit/miss/fill/writeback/req/rsp/replay/mshr/...
uuid: Optional[int] = None
wid: Optional[int] = None
pc: Optional[str] = None
tmask: Optional[str] = None
addr: Optional[str] = None
tag: Optional[str] = None
@dataclass
class RawInstantEvent:
ts: int
path: str
name: str
uuid: Optional[int] = None
args: Dict[str, Any] = field(default_factory=dict)
# -----------------------------
# Shared parsing utilities
# -----------------------------
CONFIGS_RE = re.compile(r"\bCONFIGS:\s*(.*)$")
VXDRV_START_RE = re.compile(r"^\s*\[VXDRV\]\s+START:")
# Simulator-reported instruction count, e.g. "PERF: instrs=1504, cycles=3802, ...".
PERF_INSTRS_RE = re.compile(r"\bPERF:\s*instrs=(\d+)")
PARENT_HASH_RE = re.compile(r"\bparent=#(\d+)\b")
UUID_SUFFIX_RE = re.compile(r"\(#\s*(\d+)\s*\)\s*$")
# RTL "tick:" prefix
RTL_TICK_RE = re.compile(r"^\s*(\d+)\s*:\s*(.*)$")
# SimX TRACE/DEBUG prefixes
SIMX_TRACE_RE = re.compile(r"^\s*TRACE\s+(?P<cycle>\d+)\s*:\s*(?P<body>.*)$")
SIMX_DEBUG_RE = re.compile(r"^\s*DEBUG\s+(?P<body>.*)$")
# body format: "<path> <action>: <args...>"
BODY_ACTION_ARGS_RE = re.compile(r"^(?P<path>\S+)\s+(?P<action>[^:]+)\s*:\s*(?P<args>.*)$")
BODY_ACTION_ONLY_RE = re.compile(r"^(?P<path>\S+)\s+(?P<action>.*)$")
REG_NAME_RE = re.compile(r"^[xfv]\d+$", re.IGNORECASE)
def parse_configs_line(line: str) -> Optional[Dict[str, str]]:
m = CONFIGS_RE.search(line)
if not m:
return None
s = m.group(1).strip()
parts = [p.strip() for p in s.split(",") if p.strip()]
out: Dict[str, str] = {}
for p in parts:
if "=" in p:
k, v = p.split("=", 1)
out[k.strip()] = v.strip()
return out
def split_top_level_commas(s: str) -> List[str]:
"""
Split a string by commas, but ignore commas inside {...} or (...) or [...]
(needed for register vectors and payload-like fields).
"""
out: List[str] = []
cur: List[str] = []
depth_curly = 0
depth_paren = 0
depth_brack = 0
i = 0
while i < len(s):
c = s[i]
if c == "{":
depth_curly += 1
elif c == "}":
depth_curly = max(0, depth_curly - 1)
elif c == "(":
depth_paren += 1
elif c == ")":
depth_paren = max(0, depth_paren - 1)
elif c == "[":
depth_brack += 1
elif c == "]":
depth_brack = max(0, depth_brack - 1)
if c == "," and depth_curly == 0 and depth_paren == 0 and depth_brack == 0:
tok = "".join(cur).strip()
if tok:
out.append(tok)
cur = []
else:
cur.append(c)
i += 1
tok = "".join(cur).strip()
if tok:
out.append(tok)
return out
def parse_kv_brace_aware(args_str: str) -> Dict[str, str]:
"""
Parse "k=v, k2=v2, ..." with comma separation at top level only.
Values may contain braces with commas.
"""
out: Dict[str, str] = {}
for tok in split_top_level_commas(args_str):
if "=" not in tok:
continue
k, v = tok.split("=", 1)
out[k.strip()] = v.strip()
return out
def safe_int(x: Optional[str]) -> Optional[int]:
if x is None:
return None
try:
return int(x, 0)
except Exception:
try:
return int(x)
except Exception:
return None
def parse_transition(v: str) -> str:
v = v.strip()
if "->" in v:
return v.split("->", 1)[1].strip()
return v
def parse_state_value(v: Optional[str]) -> Optional[int]:
"""Parse a warp-state active/stalled field to 0/1.
SimX prints booleans (active=true/false); RTL prints ints or transitions
(stalled=0->1). Both reduce to the post-transition 0/1 here.
"""
if v is None:
return None
v = parse_transition(v).strip().lower()
if v == "true":
return 1
if v == "false":
return 0
return safe_int(v)
def normalize_tmask(bitstr: str, num_threads: Optional[int], log_type: str) -> str:
bitstr = bitstr.strip()
if num_threads is not None and len(bitstr) < num_threads and all(c in "01" for c in bitstr):
bitstr = bitstr.rjust(num_threads, "0")
# RTL uses reversed bit ordering vs SimX
if log_type == "rtlsim" and all(c in "01" for c in bitstr):
bitstr = bitstr[::-1]
return bitstr
def decode_rtl_reg_index(reg_index: str) -> Optional[str]:
"""
Decode RTL numeric register encoding:
rtype = ireg // 32
rvalue = ireg % 32
rtype == 0 -> x<rvalue>
rtype == 1 -> f<rvalue>
rtype == 2 -> v<rvalue>
"""
try:
ireg = int(reg_index, 10)
except Exception:
return None
rtype = ireg // 32
rvalue = ireg % 32
if rtype == 2:
return f"v{rvalue}"
if rtype == 1:
return f"f{rvalue}"
return f"x{rvalue}"
def infer_cache_level(path: str) -> str:
p = path.lower()
if "icache" in p:
return "icache"
if "dcache" in p:
return "dcache"
if "l2cache" in p:
return "l2"
if "l3cache" in p:
return "l3"
if p.startswith("mem") or "dram" in p or p.endswith("-mem") or "-mem" in p:
return "mem"
return "unknown"
# Level tokens that may appear inside a cache action name (used to recover the
# level when the module path alone is ambiguous, e.g. SimX 'icache-req' logged
# at the core path).
_KIND_LEVEL_TOKENS = (
("icache", "icache"), ("dcache", "dcache"),
("l2cache", "l2"), ("l3cache", "l3"), ("l2", "l2"), ("l3", "l3"),
)
def canonicalize_cache(level: str, kind: str) -> Tuple[str, str, str]:
"""Map a sim-specific cache action onto a canonical (level, class, op).
SimX and RTL name the same cache activity differently (e.g. SimX 'core-req'
vs RTL 'core-rd-req'/'core-wr-req'/'core-rd-req[0]'). This collapses both onto
a shared class vocabulary so cross-simulator traces are comparable, while the
read/write detail is preserved separately in 'op' and the original string in
'raw_kind' (set by the caller).
Returns (level, klass, op):
level: icache|dcache|l2|l3|mem|unknown (recovered from the kind if needed)
klass: core-req|core-rsp|mem-req|mem-rsp|fill|writeback|hit|miss|
mshr|replay|flush|alloc|<fallback>
op: rd|wr|"" (empty when the name does not encode a direction)
"""
raw = kind.strip().lower()
k = re.sub(r"\[\d+\]", "", raw) # drop per-port index suffix, e.g. [0]
k = k.replace(" ", "-").strip("-") # DRAM "Rd Req" -> "rd-req"
lvl = level
if lvl == "unknown":
for tok, name in _KIND_LEVEL_TOKENS:
if tok in k:
lvl = name
break
op = "rd" if ("rd" in k or "read" in k) else ("wr" if ("wr" in k or "write" in k) else "")
if "hit" in k:
klass = "hit"
elif "miss" in k:
klass = "miss"
elif "fill" in k:
klass = "fill"
elif "flush" in k:
klass = "flush"
elif "writeback" in k or "writethrough" in k or k == "wb":
klass = "writeback"
elif "mshr" in k:
klass = "mshr"
elif "replay" in k:
klass = "replay"
elif "allocate" in k or "release" in k:
klass = "alloc"
else:
phase = "rsp" if "rsp" in k else ("req" if "req" in k else "")
if "core" in k:
port = "core"
elif "mem" in k or "out" in k:
port = "mem"
elif ("icache" in k or "dcache" in k):
port = "core" # core issuing a fetch/load to the cache
elif phase:
port = "mem" # bare DRAM "rd-req"/"rd-rsp" with no port token
else:
port = ""
if port and phase:
klass = f"{port}-{phase}"
elif phase:
klass = phase
else:
klass = k or "other"
return lvl, klass, op
def is_cache_event(path: str, action: str) -> bool:
a = action.strip().lower()
if a == "init":
return False
cachey = any(k in a for k in ("hit", "miss", "fill", "writeback", "wb", "mshr", "replay", "req", "rsp"))
pathy = any(k in path.lower() for k in ("icache", "dcache", "l2cache", "l3cache", "mem", "dram"))
a_cachey = any(k in a for k in ("icache", "dcache", "l2cache", "l3cache", "mem"))
return (cachey and pathy) or a_cachey
def extract_body_fields(body: str) -> Tuple[str, str, str]:
m = BODY_ACTION_ARGS_RE.match(body)
if m:
return m.group("path"), m.group("action").strip(), m.group("args").strip()
m2 = BODY_ACTION_ONLY_RE.match(body)
if m2:
return m2.group("path"), m2.group("action").strip(), ""
return "", "", body.strip()
def strip_payload_heavy_fields(args_str: str) -> str:
"""
Drop payload-heavy fields to keep JSON small.
"""
args_str = re.sub(r"\bdata=\{.*\}", "data={...}", args_str)
args_str = re.sub(r"\ba_row=\{.*\}", "a_row={...}", args_str)
args_str = re.sub(r"\bb_col=\{.*\}", "b_col={...}", args_str)
return args_str
# -----------------------------
# Parser base and parsers
# -----------------------------
class ParserBase:
def __init__(self, *, values_mode: str, cycle_min: Optional[int], cycle_max: Optional[int]):
self.values_mode = values_mode # none|dest|all
self.cycle_min = cycle_min
self.cycle_max = cycle_max
self.num_threads: Optional[int] = None
# Instruction count reported by the simulator's "PERF: instrs=" line, used
# for a parsed-vs-emitted reconciliation self-check.
self.perf_instrs: Optional[int] = None
def _keep(self, ts: int) -> bool:
if self.cycle_min is not None and ts < self.cycle_min:
return False
if self.cycle_max is not None and ts > self.cycle_max:
return False
return True
def parse_lines(self, lines: Iterable[str]) -> Iterator[Any]:
raise NotImplementedError
@dataclass
class InstrRecord:
rd: Optional[str] = None
rs1: Optional[str] = None
rs2: Optional[str] = None
rs3: Optional[str] = None
parent_uuid: Optional[int] = None
src_values: List[Dict[str, str]] = field(default_factory=list)
dest_value: Optional[Dict[str, str]] = None
op: Optional[str] = None
class RtlParser(ParserBase):
def __init__(self, *, values_mode: str, cycle_min: Optional[int], cycle_max: Optional[int], wait_for_vxdrv_start: bool = True):
super().__init__(values_mode=values_mode, cycle_min=cycle_min, cycle_max=cycle_max)
self.wait_for_vxdrv_start = wait_for_vxdrv_start
self._started = not wait_for_vxdrv_start
self._instr: Dict[int, InstrRecord] = {}
def parse_lines(self, lines: Iterable[str]) -> Iterator[Any]:
for line in lines:
line = line.rstrip("\n")
if not line:
continue
if self.perf_instrs is None and "PERF:" in line:
mp = PERF_INSTRS_RE.search(line)
if mp:
self.perf_instrs = int(mp.group(1))
cfg = parse_configs_line(line)
if cfg is not None:
if "num_threads" in cfg:
self.num_threads = safe_int(cfg["num_threads"])
continue
if self.wait_for_vxdrv_start and not self._started:
if VXDRV_START_RE.match(line):
self._started = True
continue
if line.lstrip().startswith("[VXDRV]"):
continue
m_tick = RTL_TICK_RE.match(line)
if not m_tick:
continue
ts = int(m_tick.group(1))
if not self._keep(ts):
continue
body = m_tick.group(2).strip()
uuid: Optional[int] = None
m_uuid = UUID_SUFFIX_RE.search(body)
if m_uuid:
uuid = int(m_uuid.group(1))
body = UUID_SUFFIX_RE.sub("", body).rstrip()
path, action, args_str = extract_body_fields(body)
if not path or not action:
continue
if action.strip() == "warp-state":
kv = parse_kv_brace_aware(args_str)
wid = safe_int(kv.get("wid"))
if wid is None:
continue
active = kv.get("active")
stalled = kv.get("stalled")
tmask = kv.get("tmask")
if active is not None:
active = parse_transition(active)
if stalled is not None:
stalled = parse_transition(stalled)
if tmask is not None:
tmask = normalize_tmask(parse_transition(tmask), self.num_threads, "rtlsim")
yield WarpStateEvent(
ts=ts,
path=path,
wid=wid,
active=safe_int(active) if active is not None else None,
stalled=safe_int(stalled) if stalled is not None else None,
tmask=tmask
)
continue
if is_cache_event(path, action):
args_clean = strip_payload_heavy_fields(args_str)
kv = parse_kv_brace_aware(args_clean)
tmask = kv.get("tmask")
if tmask is not None:
tmask = normalize_tmask(tmask, self.num_threads, "rtlsim")
yield CacheEvent(
ts=ts,
path=path,
level=infer_cache_level(path),
kind=action.strip(),
uuid=uuid,
wid=safe_int(kv.get("wid")),
pc=kv.get("PC") or kv.get("pc"),
tmask=tmask,
addr=kv.get("addr"),
tag=kv.get("tag"),
)
continue
if uuid is None:
continue
kv = parse_kv_brace_aware(args_str)
wid = safe_int(kv.get("wid"))
pc = kv.get("PC") or kv.get("pc")
ex = kv.get("ex")
op = kv.get("op")
tmask = kv.get("tmask")
if tmask is not None:
if self.num_threads is None and all(c in "01" for c in tmask.strip()):
self.num_threads = len(tmask.strip())
tmask = normalize_tmask(tmask, self.num_threads, "rtlsim")
parent_uuid = None
mp = PARENT_HASH_RE.search(args_str)
if mp:
parent_uuid = int(mp.group(1))
rd = decode_rtl_reg_index(kv["rd"]) if "rd" in kv else None
rs1 = decode_rtl_reg_index(kv["rs1"]) if "rs1" in kv else None
rs2 = decode_rtl_reg_index(kv["rs2"]) if "rs2" in kv else None
rs3 = decode_rtl_reg_index(kv["rs3"]) if "rs3" in kv else None
rec = self._instr.get(uuid)
if rec is None:
rec = InstrRecord()
self._instr[uuid] = rec
if parent_uuid is not None:
rec.parent_uuid = parent_uuid
if op is not None:
rec.op = op
if rd is not None:
rec.rd = rd
if rs1 is not None:
rec.rs1 = rs1
if rs2 is not None:
rec.rs2 = rs2
if rs3 is not None:
rec.rs3 = rs3
if self.values_mode == "all":
for k_src, reg_name in (("rs1_data", rec.rs1), ("rs2_data", rec.rs2), ("rs3_data", rec.rs3)):
if k_src in kv and reg_name is not None:
rec.src_values.append({"reg": reg_name, "value": kv[k_src]})
if self.values_mode in ("dest", "all") and action.strip() == "commit":
if "data" in kv and rec.rd is not None:
rec.dest_value = {"reg": rec.rd, "value": kv["data"]}
stage = self._map_stage(path, action)
if stage is None:
yield RawInstantEvent(ts=ts, path=path, name=action.strip(), uuid=uuid, args={"raw": args_str})
continue
sop = safe_int(kv.get("sop")) or 1
eop = safe_int(kv.get("eop")) or 1
# RTL logs fetch as two events (req/rsp); tag the phase so the doubled
# fetch markers are distinguishable rather than looking like duplicates.
phase = action.strip() if (stage == "fetch" and action.strip() in ("req", "rsp")) else None
yield InstructionStageEvent(
ts=ts,
path=path,
stage=stage,
uuid=uuid,
wid=wid,
pc=pc,
ex=ex,
op=rec.op or op,
wb=safe_int(kv.get("wb")),
tmask=tmask,
sop=sop,
eop=eop,
phase=phase,
parent_uuid=rec.parent_uuid,
rd=rec.rd,
rs1=rec.rs1,
rs2=rec.rs2,
rs3=rec.rs3,
src_values=rec.src_values if rec.src_values else None,
dest_value=rec.dest_value if rec.dest_value else None,
)
if stage == "commit":
self._instr.pop(uuid, None)
def _map_stage(self, path: str, action: str) -> Optional[str]:
a = action.strip()
p = path
if p.endswith("-scheduler") and a == "dispatch":
return "schedule"
if "-fetch" in p and a in ("req", "rsp", "fetch"):
return "fetch"
if p.endswith("-decode") and a == "decode":
return "decode"
if "issue" in p and a in ("issue", "decode"):
return "issue"
if p.endswith("-dispatcher") and a == "dispatch":
return "dispatch"
if "-execute" in p or "-issue" in p:
return "execute"
if p.endswith("-commit") and a == "commit":
return "commit"
if a == "commit":
return "commit"
return None
class SimxParser(ParserBase):
def __init__(self, *, values_mode: str, cycle_min: Optional[int], cycle_max: Optional[int], wait_for_vxdrv_start: bool = True):
super().__init__(values_mode=values_mode, cycle_min=cycle_min, cycle_max=cycle_max)
self.wait_for_vxdrv_start = wait_for_vxdrv_start
self._started = not wait_for_vxdrv_start
self._instr: Dict[int, InstrRecord] = {}
self._open_debug_uuid: Optional[int] = None
def parse_lines(self, lines: Iterable[str]) -> Iterator[Any]:
for line in lines:
line = line.rstrip("\n")
if not line:
continue
if self.perf_instrs is None and "PERF:" in line:
mp = PERF_INSTRS_RE.search(line)
if mp:
self.perf_instrs = int(mp.group(1))
cfg = parse_configs_line(line)
if cfg is not None:
if "num_threads" in cfg:
self.num_threads = safe_int(cfg["num_threads"])
continue
if self.wait_for_vxdrv_start and not self._started:
if VXDRV_START_RE.match(line):
self._started = True
continue
m_trace = SIMX_TRACE_RE.match(line)
if m_trace:
ts = int(m_trace.group("cycle"))
if not self._keep(ts):
continue
body = m_trace.group("body").strip()
uuid: Optional[int] = None
m_uuid = UUID_SUFFIX_RE.search(body)
if m_uuid:
uuid = int(m_uuid.group(1))
body = UUID_SUFFIX_RE.sub("", body).rstrip()
path, action, args_str = extract_body_fields(body)
if not path or not action:
continue
if is_cache_event(path, action):
args_clean = strip_payload_heavy_fields(args_str)
kv = parse_kv_brace_aware(args_clean)
tmask = kv.get("tmask")
if tmask is not None:
if self.num_threads is None and all(c in "01" for c in tmask.strip()):
self.num_threads = len(tmask.strip())
tmask = normalize_tmask(tmask, self.num_threads, "simx")
yield CacheEvent(
ts=ts,
path=path,
level=infer_cache_level(path),
kind=action.strip(),
uuid=uuid,
wid=safe_int(kv.get("wid")),
pc=kv.get("PC") or kv.get("pc"),
tmask=tmask,
addr=kv.get("addr"),
tag=kv.get("tag"),
)
continue
if action.strip() == "warp-state":
# SimX emits warp-state lines without a (#uuid) suffix; surface them
# as per-warp counters (active/stalled/active_threads), matching RTL.
kv = parse_kv_brace_aware(args_str)
wid = safe_int(kv.get("wid"))
if wid is None:
continue
tmask = kv.get("tmask")
if tmask is not None:
if self.num_threads is None and all(c in "01" for c in tmask.strip()):
self.num_threads = len(tmask.strip())
tmask = normalize_tmask(tmask, self.num_threads, "simx")
yield WarpStateEvent(
ts=ts,
path=path,
wid=wid,
active=parse_state_value(kv.get("active")),
stalled=parse_state_value(kv.get("stalled")),
tmask=tmask,
)
continue
if uuid is None:
continue
kv = parse_kv_brace_aware(args_str)
wid = safe_int(kv.get("wid"))
pc = kv.get("PC") or kv.get("pc")
ex = kv.get("ex")
op = kv.get("op")
tmask = kv.get("tmask")
if tmask is not None:
if self.num_threads is None and all(c in "01" for c in tmask.strip()):
self.num_threads = len(tmask.strip())
tmask = normalize_tmask(tmask, self.num_threads, "simx")
sop = safe_int(kv.get("sop")) or 1
eop = safe_int(kv.get("eop")) or 1
parent_uuid = None
mp = PARENT_HASH_RE.search(args_str)
if mp:
parent_uuid = int(mp.group(1))
rec = self._instr.get(uuid)
if rec is None:
rec = InstrRecord()
self._instr[uuid] = rec
if parent_uuid is not None:
rec.parent_uuid = parent_uuid
if op is not None:
rec.op = op
stage = self._map_stage(path, action)
if stage is None:
yield RawInstantEvent(ts=ts, path=path, name=action.strip(), uuid=uuid, args={"raw": args_str})
continue
yield InstructionStageEvent(
ts=ts,
path=path,
stage=stage,
uuid=uuid,
wid=wid,
pc=pc,
ex=ex,
op=rec.op or op,
wb=safe_int(kv.get("wb")),
tmask=tmask,
sop=sop,
eop=eop,
parent_uuid=rec.parent_uuid,
rd=rec.rd,
rs1=rec.rs1,
rs2=rec.rs2,
rs3=rec.rs3,
src_values=rec.src_values if rec.src_values else None,
dest_value=rec.dest_value if rec.dest_value else None,
)
if stage == "commit":
self._instr.pop(uuid, None)
continue
m_dbg = SIMX_DEBUG_RE.match(line)
if m_dbg:
body = m_dbg.group("body").strip()
uuid: Optional[int] = None
m_uuid = UUID_SUFFIX_RE.search(body)
if m_uuid:
uuid = int(m_uuid.group(1))
body = UUID_SUFFIX_RE.sub("", body).rstrip()
else:
uuid = self._open_debug_uuid
if uuid is None:
continue
self._parse_debug(body, uuid)
continue
def _map_stage(self, path: str, action: str) -> Optional[str]:
a = action.strip().lower()
if a in STAGES_CANON:
return a
return None
def _parse_debug(self, body: str, uuid: int) -> None:
rec = self._instr.get(uuid)
if rec is None:
rec = InstrRecord()
self._instr[uuid] = rec
if body.startswith("Instr:"):
self._open_debug_uuid = uuid
s = body[len("Instr:"):].strip()
mp = PARENT_HASH_RE.search(s)
if mp:
rec.parent_uuid = int(mp.group(1))
mt = re.search(r"\btmask=([01]+)\b", s)
if mt and self.num_threads is None:
self.num_threads = len(mt.group(1))
key_match = re.search(r"\b(cid|wid|tmask|PC|parent)=\b", s)
asm_part = s[:key_match.start()].strip() if key_match else s.strip()
if asm_part:
parts = asm_part.split(None, 1)
mnemonic = parts[0]
rec.op = mnemonic
operands = parts[1] if len(parts) > 1 else ""
ops = [o.strip() for o in operands.split(",") if o.strip()]
reg_ops = [o for o in ops if REG_NAME_RE.match(o)]
if len(reg_ops) >= 1:
rec.rd = reg_ops[0]
if len(reg_ops) >= 2:
rec.rs1 = reg_ops[1]
if len(reg_ops) >= 3:
rec.rs2 = reg_ops[2]
if len(reg_ops) >= 4:
rec.rs3 = reg_ops[3]
return
if body.startswith("Src") and "Reg:" in body:
if self.values_mode != "all":
return
_, rhs = body.split("Reg:", 1)
rhs = rhs.strip()
if "=" not in rhs:
return
reg, val = rhs.split("=", 1)
rec.src_values.append({"reg": reg.strip(), "value": val.strip()})
return
if body.startswith("Dest Reg:"):
if self.values_mode not in ("dest", "all"):
return
rhs = body[len("Dest Reg:"):].strip()
if "=" not in rhs:
return
reg, val = rhs.split("=", 1)
reg = reg.strip()
val = val.strip()
rec.dest_value = {"reg": reg, "value": val}
rec.rd = rec.rd or reg
return
# -----------------------------
# Perfetto / Chrome Trace writer
# -----------------------------
class TraceWriter:
def __init__(self, out_f: io.TextIOBase):
self.out_f = out_f
self.first = True
self.out_f.write("[")
def emit(self, evt: Dict[str, Any]) -> None:
s = json.dumps(evt, separators=(",", ":"), ensure_ascii=False)
if self.first:
self.first = False
self.out_f.write(s)
else:
self.out_f.write("," + s)
def close(self) -> None:
self.out_f.write("]\n")
self.out_f.flush()
@dataclass
class TrackAllocator:
pid: int
writer: TraceWriter
_next_tid: int = 100
_tid_by_key: Dict[str, int] = field(default_factory=dict)
_named: set = field(default_factory=set)
def tid(self, key: str, name: str) -> int:
if key in self._tid_by_key:
return self._tid_by_key[key]
tid = self._next_tid
self._next_tid += 1
self._tid_by_key[key] = tid
self._emit_thread_name(tid, name)
return tid
def _emit_thread_name(self, tid: int, name: str) -> None:
if tid in self._named:
return
self._named.add(tid)
self.writer.emit({
"ph": "M",
"pid": self.pid,
"tid": tid,
"name": "thread_name",
"args": {"name": name}
})
def extract_hierarchy(path: str) -> Tuple[Optional[str], Optional[str], Optional[str]]:
mc = re.search(r"(cluster\d+)", path)
ms = re.search(r"(socket\d+)", path)
mcore = re.search(r"(core\d+)", path)
return (mc.group(1) if mc else None,
ms.group(1) if ms else None,
mcore.group(1) if mcore else None)
def track_name_for(path: str, wid: Optional[int], kind: str,
mem_level: Optional[str] = None) -> Tuple[str, str]:
cluster, socket, core = extract_hierarchy(path)
base = "-".join([x for x in (cluster, socket, core) if x]) or "global"
if kind == "warp" and wid is not None:
return f"{base}/warp{wid}", f"{base}: warp{wid}"
if kind == "warpstate" and wid is not None:
return f"{base}/warp{wid}/state", f"{base}: warp{wid} state"
if kind == "mem":
lvl = mem_level or infer_cache_level(path)
return f"{base}/{lvl}", f"{base}: {lvl}"
return f"{base}/{path}", path
@dataclass
class EmitterConfig:
values_mode: str
parent_flow: bool
freq_mhz: Optional[float] = None
cycle_ns: Optional[float] = None
def ts_to_us(ts: int, cfg: EmitterConfig) -> float:
if cfg.cycle_ns is not None:
return (cfg.cycle_ns * ts) / 1000.0
if cfg.freq_mhz is not None and cfg.freq_mhz > 0:
return ts / cfg.freq_mhz
return float(ts)
class PerfettoEmitter:
def __init__(self, writer: TraceWriter, cfg: EmitterConfig):
self.writer = writer
self.cfg = cfg
self.pid = 1
self.tracks = TrackAllocator(pid=self.pid, writer=writer)
self._open_inst: Dict[int, Tuple[float, int]] = {}
self._last_ts_us: float = 0.0
# Reconciliation counters (instruction async slices).
self.slices_begun = 0
self.slices_committed = 0
self.slices_incomplete = 0
self.writer.emit({"ph": "M", "pid": self.pid, "name": "process_name", "args": {"name": "Vortex GPU 1"}})
self.writer.emit({"ph": "M", "pid": self.pid, "name": "process_sort_index", "args": {"sort_index": 1}})
def finalize(self) -> None:
end_ts = self._last_ts_us
for uuid, (beg, tid) in list(self._open_inst.items()):
self._emit_async_end(end_ts, tid, "inst", "vortex.inst", uuid, {"uuid": uuid, "incomplete": 1})
self._open_inst.pop(uuid, None)
self.slices_incomplete += 1
def emit_event(self, ev: Any) -> None:
if isinstance(ev, InstructionStageEvent):
self._emit_instruction_stage(ev)
return
if isinstance(ev, WarpStateEvent):
self._emit_warp_state(ev)
return
if isinstance(ev, CacheEvent):
self._emit_cache(ev)
return
if isinstance(ev, RawInstantEvent):
self._emit_raw(ev)
return