forked from pytorch/executorch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisualize.py
More file actions
293 lines (226 loc) · 9.11 KB
/
visualize.py
File metadata and controls
293 lines (226 loc) · 9.11 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
# Copyright 2025 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import gzip
import io
import json
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, NamedTuple, Union
import pandas as pd
from executorch.devtools.visualization.visualization_utils import (
visualize_model_explorer,
)
from model_explorer import config as model_explorer_config, node_data_builder as ndb
COMPILER_OP_ID = "scheduled_id"
class Tables(NamedTuple):
queue: pd.DataFrame
group: pd.DataFrame
perf: pd.DataFrame
source: pd.DataFrame
def parse_tables(tables_path: Path) -> Tables:
"""
Parse the XML debug tables file and extract required tables as pandas DataFrames.
"""
required_tables = {"queue", "group", "perf", "source"}
try:
tree = ET.parse(tables_path)
except ET.ParseError as e:
raise ValueError(f"Failed to parse XML tables file {tables_path}: {e}")
tables: Dict[str, pd.DataFrame] = {}
for table in tree.getroot().findall("table"):
name = table.attrib.get("name")
if name in required_tables:
text = table.text or ""
tables[name] = pd.read_csv(io.StringIO(text))
missing = required_tables - tables.keys()
if missing:
raise ValueError(f"Missing required tables in XML: {missing}")
return Tables(**tables)
def get_trace_file_objects(trace_file_path: Path) -> list[Dict[str, Any]]:
"""
Load and return the 'traceEvents' list from a gzip-compressed JSON trace file.
"""
try:
with gzip.open(trace_file_path, "rt", encoding="utf-8") as file:
data = json.load(file)
except (OSError, json.JSONDecodeError) as e:
raise ValueError(f"Failed to read or parse trace file {trace_file_path}: {e}")
if "traceEvents" not in data:
raise KeyError(f"'traceEvents' key not found in {trace_file_path}")
return data["traceEvents"]
def get_subops(df_group: pd.DataFrame) -> set:
return set(df_group[df_group["id"] != df_group["group_id"]]["id"])
def transform_events(
objects: Iterable[Dict[str, Any]], queue_df: pd.DataFrame, sub_ops: set
) -> None:
"""
Annotate the 'queue' table in-place with duration based on trace events.
"""
queue_df_len = len(queue_df)
offsets = queue_df["offset"].astype(int)
start_ts, cmd_index, chain_len = 0, 0, 1
def is_end_of_command(qread_offset: int, end_idx: int) -> bool:
if end_idx >= queue_df_len:
return qread_offset > offsets[cmd_index]
return qread_offset == offsets[end_idx]
for event in (e for e in objects if e.get("tid") == "qread"):
if cmd_index >= queue_df_len:
break
qread_offset = 4 * int(event["args"]["qread"])
end_idx = cmd_index + chain_len
if is_end_of_command(qread_offset, end_idx):
end_ts = int(event["ts"]) - 1
queue_df.loc[cmd_index, ["duration"]] = [
end_ts - start_ts,
]
start_ts = end_ts
cmd_index += chain_len
chain_len = 1
while (cmd_index + chain_len <= queue_df_len - 1) and queue_df.iloc[
cmd_index + chain_len
]["scheduled_id"] in sub_ops:
chain_len += 1
Agg = Union[str, Callable[[pd.Series], Any]]
def list_unique(s: pd.Series) -> list[Any]:
return sorted(set(s.dropna()))
def build_perf_df(tables: Tables) -> tuple[pd.DataFrame, pd.DataFrame]:
"""
Build a performance DataFrame summarizing queue metrics grouped by source_id.
Returns a tuple of (perf_df, cmd_to_op_df) where cmd_to_op_df is needed for unmapped op tracking.
"""
tables.queue["cmd_id"] = tables.queue.index
excluded = {"optimised_id", "scheduled_id", "offset"}
col_funcs: Dict[str, Agg] = {
c: "sum" for c in tables.queue.columns if c not in excluded
}
col_funcs.update({"cmdstream_id": list_unique, "cmd_id": list_unique})
cmd_to_op_df = tables.queue.groupby(COMPILER_OP_ID).agg(col_funcs).reset_index()
opt_df = (
pd.merge(tables.perf[["id", "source_id"]], tables.group, on="id", how="left")
.rename(columns={"id": COMPILER_OP_ID})
.merge(cmd_to_op_df, on=COMPILER_OP_ID, how="inner")
)
exclude_columns = ["source_id"]
src_col_funcs: Dict[str, Agg] = {
col: "sum" for col in opt_df.columns if col not in exclude_columns
}
src_col_funcs[COMPILER_OP_ID] = list_unique
perf_df = opt_df.groupby("source_id").agg(src_col_funcs).reset_index()
return perf_df, cmd_to_op_df
def check_unmapped_ops(
tables: Tables, src_df: pd.DataFrame, cmd_to_op_df: pd.DataFrame
) -> None:
"""
Identify operators in the performance data that are not mapped to any source operation.
"""
opt_ids_in_src_table = set()
for opt_ids in src_df[COMPILER_OP_ID].dropna():
if type(opt_ids) is list:
opt_ids_in_src_table.update(opt_ids)
opt_df = pd.merge(
tables.perf[["id", "source_id"]], tables.group, on="id", how="left"
)
opt_df = opt_df.rename(columns={"id": COMPILER_OP_ID})
opt_df = pd.merge(opt_df, cmd_to_op_df, on=COMPILER_OP_ID, how="inner")
unmapped_operators = opt_df[
~opt_df[COMPILER_OP_ID].isin(list(opt_ids_in_src_table))
]
if not unmapped_operators.empty:
print("Warning: There are unmapped operators in the performance data.")
print(unmapped_operators)
return None
def build_src_df(tables: Tables, perf_df: pd.DataFrame) -> pd.DataFrame:
"""
Merge source table with performance metrics and total NPU cycles.
Returns a tuple of (src_df, cmd_to_op_df) where df_cmd_to_op is needed for unmapped op tracking.
"""
return pd.merge(
tables.source.rename(columns={"id": "source_id"})[["ext_key", "source_id"]],
perf_df,
on="source_id",
how="left",
).merge(
tables.perf[["source_id", "npu_cycles"]]
.groupby("source_id")
.sum(numeric_only=True)
.reset_index(),
on="source_id",
how="left",
)
def get_model_node_data(df: pd.DataFrame) -> ndb.ModelNodeData:
"""
Convert source-level metrics into ModelExplorer node data for duration.
"""
durations = df["duration"].fillna(0).astype(int)
duration_results: Dict[str, ndb.NodeDataResult] = {}
for src, dur in zip(df["ext_key"], durations):
node_id = f"main/op{int(src)}"
duration_results[node_id] = ndb.NodeDataResult(value=int(dur))
gradient = [
ndb.GradientItem(stop=0.0, bgColor="#ffffff"),
ndb.GradientItem(stop=0.1, bgColor="#33FF00"),
ndb.GradientItem(stop=0.2, bgColor="#66FF00"),
ndb.GradientItem(stop=0.5, bgColor="#FFFF00"),
ndb.GradientItem(stop=0.7, bgColor="#FF6600"),
ndb.GradientItem(stop=1.0, bgColor="#FF0000"),
]
return ndb.ModelNodeData(
graphsData={
"main": ndb.GraphNodeData(results=duration_results, gradient=gradient)
}
)
def build_overlay_data(trace_path: Path, tables_path: Path) -> ndb.ModelNodeData:
"""
Build ModelExplorer node data from trace and tables files.
"""
tables = parse_tables(tables_path)
events = get_trace_file_objects(trace_path)
transform_events(events, tables.queue, get_subops(tables.group))
perf_df, cmd_to_op_df = build_perf_df(tables)
src_df = build_src_df(tables, perf_df)
check_unmapped_ops(tables, src_df, cmd_to_op_df)
return get_model_node_data(src_df)
def validate_file_exists(file_path: Path) -> None:
if not file_path.exists():
raise FileNotFoundError(f"{file_path} not found")
def validate_perf_mode_args(trace: str, tables: str) -> None:
if not (trace and tables):
raise ValueError(
"Both --trace and --tables must be provided for perf mode, or neither for default mode"
)
def main() -> None:
parser = argparse.ArgumentParser(
description="Visualize a model using model explorer."
)
parser.add_argument(
"--model_path", required=True, type=str, help="Path to the model file"
)
parser.add_argument(
"--trace",
required=False,
help="(perf mode) PMU trace JSON.gz file with performance data",
)
parser.add_argument(
"--tables",
required=False,
help="(perf mode) Vela debug database tables XML file",
)
args = parser.parse_args()
model_file = Path(args.model_path).resolve()
validate_file_exists(model_file)
config = model_explorer_config().add_model_from_path(str(model_file))
if args.trace or args.tables:
validate_perf_mode_args(args.trace, args.tables)
trace_file = Path(args.trace).resolve()
tables_file = Path(args.tables).resolve()
validate_file_exists(trace_file)
validate_file_exists(tables_file)
config.add_node_data(
"Duration (Cycles)", build_overlay_data(trace_file, tables_file)
)
visualize_model_explorer(config=config, extensions=["tosa_adapter_model_explorer"])
if __name__ == "__main__":
main()