-
Notifications
You must be signed in to change notification settings - Fork 526
/
Copy path_inspector.py
1294 lines (1107 loc) · 49.5 KB
/
_inspector.py
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
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
# pyre-unsafe
import dataclasses
import logging
import sys
import warnings
from collections import defaultdict, OrderedDict
from dataclasses import dataclass
from functools import cached_property
from typing import (
Any,
Callable,
Dict,
IO,
List,
Mapping,
Optional,
Sequence,
Tuple,
TypeAlias,
TypedDict,
Union,
)
import executorch.devtools.etdump.schema_flatcc as flatcc
import numpy as np
import pandas as pd
from executorch.devtools.debug_format.et_schema import OperatorGraph, OperatorNode
from executorch.devtools.etdump.schema_flatcc import (
DebugEvent,
ETDumpFlatCC,
ProfileEvent,
)
from executorch.devtools.etrecord import ETRecord, parse_etrecord
from executorch.devtools.inspector._inspector_utils import (
calculate_time_scale_factor,
create_debug_handle_to_op_node_mapping,
display_or_print_df,
EDGE_DIALECT_GRAPH_KEY,
EXCLUDED_COLUMNS_WHEN_PRINTING,
EXCLUDED_EVENTS_WHEN_PRINTING,
find_populated_event,
FORWARD,
gen_etdump_object,
gen_graphs_from_etrecord,
inflate_runtime_output,
is_debug_output,
is_inference_output_equal,
ProgramOutput,
RESERVED_FRAMEWORK_EVENT_NAMES,
TimeScale,
verify_debug_data_equivalence,
)
from executorch.exir import ExportedProgram
log: logging.Logger = logging.getLogger(__name__)
# Signature of an InstructionEvent
@dataclass(frozen=True, order=True)
class InstructionEventSignature:
instruction_id: int
chain_index: int
delegate_id: Optional[int] = None
delegate_id_str: Optional[str] = None
# Aggregated Runtime Events for a single instruction
@dataclass
class InstructionEvent:
signature: InstructionEventSignature
profile_events: Optional[List[ProfileEvent]] = None
debug_events: Optional[List[DebugEvent]] = None
@staticmethod
def gen_from_events(run_events: List[flatcc.Event]) -> List["InstructionEvent"]:
"""
Given a list of events from a run in ETDump, collate the ProfileEvent
and DebugEvents by instruction id and return a list of InstructionEvents
constructed from collated events (ignoring run_output events)
"""
instruction_events: Dict[InstructionEventSignature, InstructionEvent] = (
OrderedDict()
)
for event in run_events:
# Find the event that was logged
populated_event: Union[DebugEvent, ProfileEvent] = find_populated_event(
event
)
# Get existing InstructionEvent or insert a new one
signature = InstructionEventSignature(
instruction_id=populated_event.instruction_id,
chain_index=populated_event.chain_index,
delegate_id=populated_event.delegate_debug_id_int,
delegate_id_str=populated_event.delegate_debug_id_str,
)
instruction_event = instruction_events.setdefault(
signature, InstructionEvent(signature=signature)
)
# Update InstructionEvent based on event type
if isinstance(populated_event, ProfileEvent):
if instruction_event.profile_events is None:
instruction_event.profile_events = []
instruction_event.profile_events.append(populated_event)
elif isinstance(populated_event, DebugEvent):
# Ignore run_output events
if not is_debug_output(populated_event.debug_entry):
if instruction_event.debug_events is None:
instruction_event.debug_events = []
instruction_event.debug_events.append(populated_event)
return list(instruction_events.values())
# Signature of a ProfileEvent
@dataclass(frozen=True, order=True)
class ProfileEventSignature:
name: str
instruction_id: Optional[int]
delegate_id: Optional[int] = None
delegate_id_str: Optional[str] = None
@staticmethod
def _gen_from_event(event: ProfileEvent) -> "ProfileEventSignature":
"""
Given a ProfileEvent, extract the fields into a signature
ProfileEvents from ETDump default to "" and -1 when the field is not populated
The Signature will convert these back to the intended None value
"""
return ProfileEventSignature(
event.name or "",
event.instruction_id if event.instruction_id != -1 else None,
event.delegate_debug_id_int if event.delegate_debug_id_int != -1 else None,
event.delegate_debug_id_str if event.delegate_debug_id_str != "" else None,
)
# Signature of a DebugEvent
@dataclass(frozen=True, order=True)
class DebugEventSignature:
name: str = ""
instruction_id: Optional[int] = -1
delegate_id: Optional[int] = None
delegate_id_str: Optional[str] = None
@staticmethod
def _gen_from_event(event: DebugEvent) -> "DebugEventSignature":
"""
Given a DebugEvent, extract the fields into a signature
DebugEvents from ETDump default to "" and -1 when the field is not populated
The Signature will convert these back to the intended None value
"""
return DebugEventSignature(
event.name or "",
event.instruction_id if event.instruction_id != -1 else None,
event.delegate_debug_id_int if event.delegate_debug_id_int != -1 else None,
event.delegate_debug_id_str if event.delegate_debug_id_str != "" else None,
)
# Signature of an Event inside of a Run
@dataclass(frozen=True, order=True)
class EventSignature:
"""
Note that (profile_event_signature, debug_event_signature) are sufficient
signature identifiers.
instruction_id is extracted from the signatures (equivalent in both) and
surfaced for convenience
"""
instruction_id: int
profile_event_signature: Optional[ProfileEventSignature] = None
debug_event_signature: Optional[DebugEventSignature] = None
@staticmethod
def gen_from_instruction_event(
instruction_event: InstructionEvent,
) -> List[Tuple["EventSignature", InstructionEvent]]:
"""
Construct EventSignatures from the given InstructionEvent
and return tuples of (1) EventSignature and (2) related subset
InstructionEvent
"""
# Generate the DebugEventSignature
debug_events = instruction_event.debug_events
debug_signature = (
DebugEventSignature._gen_from_event(debug_events[0])
if debug_events is not None and len(debug_events) > 0
else None
)
# If no ProfileEvents, return a singleton EventSignature
if (profile_events := instruction_event.profile_events) is None:
return [
(
EventSignature(
instruction_id=instruction_event.signature.instruction_id,
debug_event_signature=debug_signature,
),
instruction_event,
)
]
# Generate the ProfileEventSignature
return [
(
EventSignature(
instruction_id=instruction_event.signature.instruction_id,
profile_event_signature=ProfileEventSignature._gen_from_event(
profile_event
),
debug_event_signature=debug_signature,
),
dataclasses.replace(instruction_event, profile_events=[profile_event]),
)
for profile_event in profile_events
]
# Signature of a Run
@dataclass(frozen=True, order=True)
class RunSignature:
"""
Args:
name: Name of the run
events: List of EventSignatures that correspond to the run
bundled_input_index: Index of the bundled input used to generate the debug output
"""
name: str
events: Optional[Tuple[EventSignature]] = None
bundled_input_index: Optional[int] = None
# Typing for mapping Event.delegate_debug_identifiers to debug_handle(s)
DelegateIdentifierDebugHandleMap: TypeAlias = Union[
Mapping[int, Tuple[int, ...]], Mapping[str, Tuple[int, ...]]
]
# Typing for Dict containig delegate metadata
DelegateMetadata = TypedDict(
"DelegateMetadata",
{"name": str, "delegate_map": DelegateIdentifierDebugHandleMap},
)
@dataclass
class PerfData:
def __init__(self, raw: List[float]):
self.raw: List[float] = raw
@property
def p10(self) -> float:
return np.percentile(self.raw, 10)
@property
def p50(self) -> float:
return np.percentile(self.raw, 50)
@property
def p90(self) -> float:
return np.percentile(self.raw, 90)
@property
def avg(self) -> float:
return np.mean(self.raw)
@property
def min(self) -> float:
return min(self.raw)
@property
def max(self) -> float:
return max(self.raw)
@dataclass
class Event:
"""
An Event corresponds to an operator instance with perf data retrieved from the runtime and other metadata from `ETRecord`.
Args:
name: Name of the profiling `Event`, empty if no profiling event.
perf_data: Performance data associated with the event retrived from the runtime (available attributes: p10, p50, p90, avg, min and max).
op_type: List of op types corresponding to the event.
delegate_debug_identifier: Supplemental identifier used in combination with instruction id.
debug_handles: Debug handles in the model graph to which this event is correlated.
stack_trace: A dictionary mapping the name of each associated op to its stack trace.
module_hierarchy: A dictionary mapping the name of each associated op to its module hierarchy.
is_delegated_op: Whether or not the event was delegated.
delegate_backend_name: Name of the backend this event was delegated to.
_delegate_debug_metadatas: A list of raw delegate debug metadata in string, one for each profile event.
Available parsed (if parser provided) as Event.delegate_debug_metadatas
Available as Event.raw_delegate_debug_metadatas
debug_data: A list containing intermediate data collected.
_instruction_id: Instruction Identifier for Symbolication
_delegate_metadata_parser: Optional Parser for _delegate_debug_metadatas
"""
name: str
perf_data: Optional[PerfData] = None
op_types: List[str] = dataclasses.field(default_factory=list)
delegate_debug_identifier: Optional[Union[int, str]] = None
debug_handles: Optional[Union[int, Sequence[int]]] = None
stack_traces: Dict[str, str] = dataclasses.field(default_factory=dict)
module_hierarchy: Dict[str, Dict] = dataclasses.field(default_factory=dict)
is_delegated_op: Optional[bool] = None
delegate_backend_name: Optional[str] = None
_delegate_debug_metadatas: List[str] = dataclasses.field(default_factory=list)
debug_data: ProgramOutput = dataclasses.field(default_factory=list)
_instruction_id: Optional[int] = None
_delegate_metadata_parser: Optional[Callable[[List[str]], Dict[str, Any]]] = None
_delegate_time_scale_converter: Optional[
Callable[[Union[int, str], Union[int, float]], Union[int, float]]
] = None
_start_time: Optional[List[Union[int, float]]] = None
@cached_property
def delegate_debug_metadatas(self) -> Union[List[str], Dict[str, Any]]:
"""
Returns the parsed _delegate_debug_metadatas if a parser is available
Otherwise returns the raw _delegate_debug_metadatas
"""
if not self.is_delegated_op or self._delegate_metadata_parser is None:
return self._delegate_debug_metadatas
return self._delegate_metadata_parser(self._delegate_debug_metadatas)
@property
def raw_delegate_debug_metadatas(self) -> List[str]:
"""
Return the raw unparsed _delegate_debug_metadatas
"""
return self._delegate_debug_metadatas
@property
def start_time(self) -> Optional[List[Union[int, float]]]:
"""
Returns the start time of the event.
"""
return self._start_time
def to_dataframe(self, _units="") -> pd.DataFrame:
"""
Convert the Event into a pandas DataFrame
Args:
None
Returns:
A pandas DataFrame with the Event data
"""
event_dict = self.asdict(_units=_units)
return pd.DataFrame(event_dict)
# Override the default implementation of dataclass.asdict to handle null perf data
def asdict(self, _units="") -> dict:
"""
Convert the Event into a dict
Args:
None
Returns:
A dict with the Event data
"""
def truncated_list(long_list: List[str]) -> str:
return f"['{long_list[0]}', '{long_list[1]}' ... '{long_list[-1]}'] ({len(long_list)} total)"
return {
"event_name": self.name,
"raw": [self.perf_data.raw if self.perf_data else None],
"p10" + _units: self.perf_data.p10 if self.perf_data else None,
"p50" + _units: self.perf_data.p50 if self.perf_data else None,
"p90" + _units: self.perf_data.p90 if self.perf_data else None,
"avg" + _units: self.perf_data.avg if self.perf_data else None,
"min" + _units: self.perf_data.min if self.perf_data else None,
"max" + _units: self.perf_data.max if self.perf_data else None,
"op_types": [
(
self.op_types
if len(self.op_types) < 5
else truncated_list(self.op_types)
)
],
"delegate_debug_identifier": self.delegate_debug_identifier,
"stack_traces": [self.stack_traces],
"module_hierarchy": [self.module_hierarchy],
"is_delegated_op": self.is_delegated_op,
"delegate_backend_name": self.delegate_backend_name,
"debug_data": [self.debug_data],
"start_time": [self._start_time],
}
@staticmethod
def _gen_from_inference_events(
signature: EventSignature,
events: List[InstructionEvent],
scale_factor: float = 1.0,
output_buffer: Optional[bytes] = None,
delegate_metadata_parser: Optional[
Callable[[List[str]], Dict[str, Any]]
] = None,
delegate_time_scale_converter: Optional[
Callable[[Union[int, str], Union[int, float]], Union[int, float]]
] = None,
) -> "Event":
"""
Given an EventSignature and a list of Events with that signature,
return an Event object matching the EventSignature, with perf_data
populated from the list of ProfileEvents and debug_data populated from
the list of DebugEvents.
An optional inverse scale factor can be provided to adjust the event timestamps
An optional buffer can be provided to inflate etdump references
An optional delegate_metadata_parser can be provided to parse the delegate metadata
"""
profile_event_signature = signature.profile_event_signature
debug_event_signature = signature.debug_event_signature
# Event is gradually populated in this function
ret_event: Event = Event(
name="",
_instruction_id=signature.instruction_id,
_delegate_metadata_parser=delegate_metadata_parser,
_delegate_time_scale_converter=delegate_time_scale_converter,
)
# Populate fields from profile events
Event._populate_profiling_related_fields(
ret_event, profile_event_signature, events, scale_factor
)
# Populate fields from debug events
Event._populate_debugging_related_fields(
ret_event, debug_event_signature, events, output_buffer
)
return ret_event
@staticmethod
def _calculate_elapsed_time(start_time, end_time):
# We're assuming if there's a wraparound in the time values, then
# the time representation of that platform only contains 32 bits.
# This should be fine for now, but ideally we should source the max
# time value from the platform using etdump.
max_uint32 = 2**32 - 1
if start_time > end_time:
if (start_time > max_uint32) or (end_time > max_uint32):
raise ValueError(
f"Expected start_time ({start_time}) and end_time ({end_time}) to be less than {max_uint32} for cases where there is wrap-around of time values."
)
# Handle wraparound
elapsed_time = (max_uint32 - start_time) + end_time
else:
# Normal case
elapsed_time = end_time - start_time
return elapsed_time
@staticmethod
def _populate_event_signature_fields(
ret_event: "Event",
event_signature: Optional[Union[ProfileEventSignature, DebugEventSignature]],
) -> None:
"""
Given a partially constructed Event, populate the fields related to
the profile event signature or debug event signature
Fields Updated:
name
delegate_debug_identifier
is_delegated_op
"""
# TODO: T201347372 Push the None check to ealier in the stack.
if event_signature is not None:
if event_signature.delegate_id is not None: # 0 is a valid value
delegate_debug_identifier = event_signature.delegate_id
else:
delegate_debug_identifier = event_signature.delegate_id_str or None
# Use the delegate identifier as the event name if delegated
is_delegated_op = delegate_debug_identifier is not None
name = (
event_signature.name
if not is_delegated_op
else str(delegate_debug_identifier)
)
# Update fields
# This is for older version of etdump that doesn't have the name field for debug events, we don't update the name field
if name:
ret_event.name = name
ret_event.delegate_debug_identifier = delegate_debug_identifier
ret_event.is_delegated_op = is_delegated_op
@staticmethod
def _populate_profiling_related_fields(
ret_event: "Event",
profile_event_signature: Optional[ProfileEventSignature],
events: List[InstructionEvent],
scale_factor: float,
) -> None:
"""
Given a partially constructed Event, populate the fields related to
the profile events
Fields Updated:
name
delegate_debug_identifier
is_delegated_op
perf_data
delegate_debug_metadatas
"""
# Fill out fields from profile event signature
Event._populate_event_signature_fields(ret_event, profile_event_signature)
# Fill out fields from profile event
data = []
stime = []
delegate_debug_metadatas = []
for event in events:
if (profile_events := event.profile_events) is not None:
if len(profile_events) != 1:
raise ValueError(
f"Expected exactly one profile event per InstructionEvent when generating Inspector Event, but got {len(profile_events)}"
)
profile_event = profile_events[0]
# Scale factor should only be applied to non-delegated ops
if (
ret_event.is_delegated_op
and (convert_time_scale := ret_event._delegate_time_scale_converter)
is not None
):
scaled_time = Event._calculate_elapsed_time(
convert_time_scale(ret_event.name, profile_event.start_time),
convert_time_scale(ret_event.name, profile_event.end_time),
)
# If it's not a delegated op then we can just use the raw time values
# and then scale them according to the scale factor that was passed in.
elif not ret_event.is_delegated_op:
scaled_time = (
float(
Event._calculate_elapsed_time(
profile_event.start_time, profile_event.end_time
)
)
/ scale_factor
)
# If there was no scale factor passed in just take a difference of the
# end and start times.
else:
scaled_time = float(
Event._calculate_elapsed_time(
profile_event.start_time, profile_event.end_time
)
)
data.append(scaled_time)
stime.append(profile_event.start_time)
delegate_debug_metadatas.append(
profile_event.delegate_debug_metadata
if profile_event.delegate_debug_metadata
else ""
)
# Update fields
if len(data) > 0:
ret_event.perf_data = PerfData(data)
if any(delegate_debug_metadatas):
ret_event._delegate_debug_metadatas = delegate_debug_metadatas
# add _start_time to the event
if len(stime) > 0:
ret_event._start_time = stime
@staticmethod
def _populate_debugging_related_fields(
ret_event: "Event",
debug_event_signature: Optional[DebugEventSignature],
events: List[InstructionEvent],
output_buffer: Optional[bytes] = None,
) -> None:
"""
Given a partially constructed Event, populate the fields related to
the debug events
Fields Updated:
name
delegate_debug_identifier
is_delegated_op
debug_data
"""
# Fill out fields from debug event signature
Event._populate_event_signature_fields(ret_event, debug_event_signature)
debug_data: List[flatcc.Value] = []
for event in events:
if (debug_events := event.debug_events) is None:
continue
# Populate on the first iteration only, then verify equivalence for others
if len(debug_data) == 0:
debug_data = [debug_event.debug_entry for debug_event in debug_events]
else:
for debug_event, value in zip(debug_events, debug_data):
v1 = inflate_runtime_output(debug_event.debug_entry, output_buffer)
v2 = inflate_runtime_output(value, output_buffer)
assert is_inference_output_equal(
v1, v2
), """Corresponding debug events in multiple iterations of the model
must have the same debug entry values. This is not the case for the
intermediate data present in this ETDump and indicates potential issues
with the model/runtime."""
ret_event.debug_data = [
inflate_runtime_output(debug_value, output_buffer)
for debug_value in debug_data
]
def _associate_with_op_graph_nodes(
self,
debug_handle_to_op_node_map: Dict[int, OperatorNode],
) -> None:
"""
Helper function to populate the stack_traces, module_hierarchy and op_types attributes
based on the debug handles of this event
"""
# Framework events aren't logically associated with any nodes
if self.name in RESERVED_FRAMEWORK_EVENT_NAMES:
return
if (debug_handles := self.debug_handles) is None:
return
if isinstance(debug_handles, int):
debug_handles = [debug_handles]
for handle in debug_handles:
node = debug_handle_to_op_node_map.get(handle)
# Attach node metadata including stack traces, module hierarchy and op_types to this event
if node is not None and (metadata := node.metadata) is not None:
self.stack_traces[node.name] = metadata.get("stack_trace")
self.module_hierarchy[node.name] = metadata.get("nn_module_stack")
if node.op:
# TODO: consider having this as a dict from node.name -> node.op
self.op_types += [node.op]
@dataclass
class EventBlock:
r"""
An `EventBlock` contains a collection of events associated with a particular profiling/debugging block retrieved from the runtime.
Each `EventBlock` represents a pattern of execution. For example, model initiation and loading lives in a single `EventBlock`.
If there's a control flow, each branch will be represented by a separate `EventBlock`.
Args:
name: Name of the profiling/debugging block.
events: List of `Event`\ s associated with the profiling/debugging block.
bundled_input_idx: Index of the Bundled Input that this EventBlock corresponds to.
run_output: Run output extracted from the encapsulated Events
"""
name: str
events: List[Event] = dataclasses.field(default_factory=list)
source_time_scale: TimeScale = TimeScale.NS
target_time_scale: TimeScale = TimeScale.MS
bundled_input_index: Optional[int] = None
run_output: Optional[ProgramOutput] = None
reference_output: Optional[ProgramOutput] = None
def to_dataframe(
self, include_units: bool = False, include_delegate_debug_data: bool = False
) -> pd.DataFrame:
"""
Converts the EventBlock into a DataFrame with each row being an event instance
Note: Rows that have an event_name = OPERATOR_CALL correspond to the perf of the
previous operator + framework tax of making said operator call.
Args:
include_units: Whether headers should include units (default false)
include_delegate_debug_data: Whether to show the delegate debug data
Returns:
A pandas DataFrame containing the data of each Event instance in this EventBlock.
"""
units = " (" + self.target_time_scale.value + ")" if include_units else ""
df = pd.concat([e.to_dataframe(units) for e in self.events], ignore_index=True)
df.insert(
0,
"event_block_name",
np.asarray([self.name for _ in range(len(self.events))]),
allow_duplicates=True,
)
# Add Delegate Debug Metadata columns
if include_delegate_debug_data:
delegate_data = []
for event in self.events:
if (metadata := event.delegate_debug_metadatas) is not None and len(
metadata
) > 0:
if isinstance(metadata, list):
delegate_data.append(
pd.Series([metadata], index=["delegate_debug_metadata"])
)
elif isinstance(metadata, dict):
delegate_data.append(pd.Series(metadata))
else:
raise ValueError(
f"Unexpected type for delegate_debug_metadata: {type(metadata)}"
)
else:
delegate_data.append(pd.Series())
if any(not data.empty for data in delegate_data):
df = pd.concat([df, pd.DataFrame(delegate_data)], axis=1)
return df
@staticmethod
def _gen_from_etdump(
etdump: ETDumpFlatCC,
source_time_scale: TimeScale = TimeScale.NS,
target_time_scale: TimeScale = TimeScale.MS,
output_buffer: Optional[bytes] = None,
delegate_metadata_parser: Optional[
Callable[[List[str]], Dict[str, Any]]
] = None,
delegate_time_scale_converter: Optional[
Callable[[Union[int, str], Union[int, float]], Union[int, float]]
] = None,
) -> List["EventBlock"]:
"""
Given an etdump, generate a list of EventBlocks corresponding to the
contents.
An optional (inverse) scale factor can be provided to adjust the
etdump timestamps associated with each EventBlocks
An optional buffer to inflate etdump references
An optional delegate metadata parser function to parse delegate profiling metadata
"""
# Map each RunSignatures to instances of its constituent events.
# The value of the map is a GroupedRunInstance which contains:
# (1) a map from each EventSignature to InstructionEvents with the signature
# (2) the run output for this RunSignature
@dataclass
class GroupedRunInstances:
events: OrderedDict[EventSignature, List[InstructionEvent]]
run_output: ProgramOutput
run_groups: Mapping[RunSignature, GroupedRunInstances] = defaultdict(
lambda: GroupedRunInstances(OrderedDict(), [])
)
# Collect all the run data
for run in etdump.run_data:
if (run_events := run.events) is None:
continue
# Collate the run_events into InstructionEvents
instruction_events: List[InstructionEvent] = (
InstructionEvent.gen_from_events(run_events)
)
# Map EventSignatures to the InstructionEvents
event_signatures: Dict[EventSignature, InstructionEvent] = OrderedDict()
for instruction_event in instruction_events:
if (
instruction_event.debug_events is None
and instruction_event.profile_events is None
):
# Currently corresponds to run output
continue
generated_event_signatures: List[
Tuple[EventSignature, InstructionEvent]
] = EventSignature.gen_from_instruction_event(instruction_event)
for (
event_signature,
filtered_instruction_event,
) in generated_event_signatures:
event_signatures[event_signature] = filtered_instruction_event
# Create a RunSignature from the EventSignatures
run_signature = RunSignature(
name=run.name,
events=tuple(event_signatures.keys()),
bundled_input_index=run.bundled_input_index,
)
# Update the Run Groups, indexed on the RunSignature
run_signature_events: OrderedDict[
EventSignature, List[InstructionEvent]
] = run_groups[run_signature].events
for event_signature, event in event_signatures.items():
run_signature_events.setdefault(event_signature, []).append(event)
# Populate (or Verify if already populated) Run Outputs
run_outputs: ProgramOutput = EventBlock._collect_run_outputs(
run_events, output_buffer
)
if len(existing_run_outputs := run_groups[run_signature].run_output) == 0:
existing_run_outputs.extend(run_outputs)
else:
verify_debug_data_equivalence(existing_run_outputs, run_outputs)
# Construct the EventBlocks
event_blocks = []
scale_factor = calculate_time_scale_factor(source_time_scale, target_time_scale)
for run_signature, grouped_run_instance in run_groups.items():
run_group: OrderedDict[EventSignature, List[InstructionEvent]] = (
grouped_run_instance.events
)
run_outputs: ProgramOutput = grouped_run_instance.run_output
# Construct the Events
events: List[Event] = [
Event._gen_from_inference_events(
signature,
instruction_events,
scale_factor,
output_buffer,
delegate_metadata_parser,
delegate_time_scale_converter,
)
for signature, instruction_events in run_group.items()
]
# Add the EventBlock to the return list
event_blocks.append(
EventBlock(
name=run_signature.name,
events=events,
source_time_scale=source_time_scale,
target_time_scale=target_time_scale,
bundled_input_index=run_signature.bundled_input_index,
run_output=run_outputs,
)
)
return event_blocks
@staticmethod
def _collect_run_outputs(
events: List[flatcc.Event], output_buffer: Optional[bytes] = None
) -> ProgramOutput:
"""
Given a list of events, search the events for ProgramOutputs (aka lists of InferenceOutputs) marked
as run outputs
"""
output_events = []
for event in events:
if event.debug_event is None:
continue
if event.debug_event.debug_entry is None:
raise RuntimeError(
"Debug entry inside debug event should not be empty!"
)
if is_debug_output(event.debug_event.debug_entry):
output_events += [event]
return [
inflate_runtime_output(debug_event.debug_entry, output_buffer)
for output_event in output_events
if (debug_event := output_event.debug_event) is not None
]
# TODO: Considering changing ETRecord deserialization logic to cast the ints in string format to actual ints
def _gen_resolve_debug_handles(
self,
handle_map: Dict[str, List[int]],
delegate_map: Optional[Dict[str, DelegateMetadata]] = None,
):
"""
Given mappings from instruction id to debug handles, populate the
debug_handles field of all underlying events
If the event is delegated, index with the instruction_id and delegate_debug_identifier
to obtain the debug_handle via the delegate map
"""
for event in self.events:
# Check if instruction_id is present in the event
if event._instruction_id is None:
continue
# Check for the instruction_id in handle map
if (instruction_id := str(event._instruction_id)) not in handle_map:
continue
# For non-delegated event, handles are found in handle_map
if (delegate_debug_id := event.delegate_debug_identifier) is None:
event.debug_handles = handle_map[instruction_id]
# DELEGATE_CALL is a special non-delegated event and benefits from having the name populated
if (
event.name == "DELEGATE_CALL"
and delegate_map is not None
and (delegate_metadata := delegate_map.get(instruction_id))
is not None
):
event.delegate_backend_name = delegate_metadata.get("name", "")
continue
# Check that the delegated event has a corresponding mapping
if (
delegate_map is None
or (delegate_metadata := delegate_map.get(instruction_id)) is None
):
event.debug_handles = handle_map[instruction_id]
log.warning(
f" No delegate mapping found for delegate with instruction id {event._instruction_id}"
)
continue
# For delegated events, handles are found via delegateMetadata
event.delegate_backend_name = delegate_metadata.get("name", "")
delegate_metadata_delegate_map = delegate_metadata.get("delegate_map") or {}
# delegate_debug_id can be either int based or string based, therefore we need to check both
debug_handles = delegate_metadata_delegate_map.get(
delegate_debug_id # pyre-ignore
)
if debug_handles is not None:
event.debug_handles = debug_handles
else:
event.debug_handles = delegate_metadata_delegate_map.get(
str(delegate_debug_id) # pyre-ignore
)
for key, value in delegate_metadata_delegate_map.items():
if key in str(delegate_debug_id):
event.debug_handles = value
class Inspector:
"""
APIs for examining model architecture and performance stats.
Public Attributes:
event_blocks: List["EventBlocks"]. Structured data from ETDump (correlated with ETRecord if provided).
Private Attributes:
_etrecord: Optional[ETRecord]. File under etrecord_path deserialized into an object.
"""
def __init__(
self,
etdump_path: Optional[str] = None,
etdump_data: Optional[bytes] = None,
etrecord: Optional[Union[ETRecord, str]] = None,
source_time_scale: TimeScale = TimeScale.NS,
target_time_scale: TimeScale = TimeScale.MS,
debug_buffer_path: Optional[str] = None,
delegate_metadata_parser: Optional[
Callable[[List[str]], Dict[str, Any]]
] = None,
delegate_time_scale_converter: Optional[
Callable[[Union[int, str], Union[int, float]], Union[int, float]]
] = None,
enable_module_hierarchy: bool = False,
) -> None:
r"""
Initialize an `Inspector` instance with the underlying `EventBlock`\ s populated with data from the provided ETDump path or binary,
and optional ETRecord path.