Uh oh!
There was an error while loading. Please reload this page.
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
Latest commit
361 lines (276 loc) · 11.1 KB
/
Copy pathvisualize.py
File metadata and controls
361 lines (276 loc) · 11.1 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
# Copyright 2025-2026 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.
importargparse
importgzip
importio
importjson
importxml.etree.ElementTreeasET# nosec B405
frompathlibimportPath
fromtypingimportAny, Callable, Dict, Iterable, NamedTuple, Union
importpandasaspd
fromexecutorch.devtools.visualization.visualization_utilsimport (
visualize_model_explorer,
)
frommodel_explorerimport ( # type: ignore[import]
configasmodel_explorer_config,
node_data_builderasndb,
)
frommodel_explorer.configimportModelSource# type: ignore[import]
COMPILER_OP_ID="scheduled_id"
classTables(NamedTuple):
queue: pd.DataFrame
group: pd.DataFrame
perf: pd.DataFrame
source: pd.DataFrame
defparse_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) # nosec B314
exceptET.ParseErrorase:
raiseValueError(f"Failed to parse XML tables file {tables_path}: {e}")
tables: Dict[str, pd.DataFrame] = {}
fortableintree.getroot().findall("table"):
name=table.attrib.get("name")
ifnameinrequired_tables:
text=table.textor""
tables[name] =pd.read_csv(io.StringIO(text))
missing=required_tables-tables.keys()
ifmissing:
raiseValueError(f"Missing required tables in XML: {missing}")
returnTables(**tables)
defget_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:
withgzip.open(trace_file_path, "rt", encoding="utf-8") asfile:
data=json.load(file)
except (OSError, json.JSONDecodeError) ase:
raiseValueError(f"Failed to read or parse trace file {trace_file_path}: {e}")
if"traceEvents"notindata:
raiseKeyError(f"'traceEvents' key not found in {trace_file_path}")
returndata["traceEvents"]
defget_subops(df_group: pd.DataFrame) ->set:
returnset(df_group[df_group["id"] !=df_group["group_id"]]["id"])
deftransform_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
defis_end_of_command(qread_offset: int, end_idx: int) ->bool:
ifend_idx>=queue_df_len:
returnqread_offset>offsets[cmd_index]
returnqread_offset==offsets[end_idx]
foreventin (eforeinobjectsife.get("tid") =="qread"):
ifcmd_index>=queue_df_len:
break
qread_offset=4*int(event["args"]["qread"])
while (cmd_index+chain_len<=queue_df_len-1) andqueue_df.iloc[
cmd_index+chain_len
]["scheduled_id"] insub_ops:
chain_len+=1
end_idx=cmd_index+chain_len
ifis_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=end_idx
chain_len=1
Agg=Union[str, Callable[[pd.Series], Any]]
deflist_unique(s: pd.Series) ->list[Any]:
returnsorted(set(s.dropna()))
defbuild_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"forcintables.queue.columnsifcnotinexcluded
}
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"forcolinopt_df.columnsifcolnotinexclude_columns
}
src_col_funcs[COMPILER_OP_ID] =list_unique
perf_df=opt_df.groupby("source_id").agg(src_col_funcs).reset_index()
returnperf_df, cmd_to_op_df
defcheck_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()
foropt_idsinsrc_df[COMPILER_OP_ID].dropna():
iftype(opt_ids) islist:
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))
]
ifnotunmapped_operators.empty:
print("Warning: There are unmapped operators in the performance data.")
print(unmapped_operators)
returnNone
defbuild_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.
"""
returnpd.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",
)
defget_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] = {}
forsrc, durinzip(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"),
]
returnndb.ModelNodeData(
graphsData={
"main": ndb.GraphNodeData(results=duration_results, gradient=gradient)
}
)
defbuild_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)
returnget_model_node_data(src_df)
defvalidate_file_exists(file_path: Path) ->None:
ifnotfile_path.exists():
raiseFileNotFoundError(f"{file_path} not found")
defvalidate_perf_mode_args(trace: str, tables: str) ->None:
ifnot (traceandtables):
raiseValueError(
"Both --trace and --tables must be provided for perf mode, or neither for default mode"
)
defset_pte_model_explorer_config(model_file, tosa_files, config):
frompte_adapter_model_explorer.mainimportPTEAdapter# type: ignore[import]
pte_adapter=PTEAdapter()
settings= {"delegate_file_paths": [str(path) forpathintosa_files]}
me_graphs=pte_adapter.convert(model_path=str(model_file), settings=settings)
# Convert the given model to model explorer graphs.
graphs_index=len(config.graphs_list)
config.graphs_list.append(me_graphs)
# Construct model source.
#
# The model source has a special format, in the form of:
# graphs://{name}/{graphs_index}
model_name=model_file.stem
model_source: ModelSource= {"url": f"graphs://{model_name}/{graphs_index}"}
config.model_sources.append(model_source)
defset_tosa_model_explorer_config(model_file, config):
config.add_model_from_path(str(model_file))
defmain() ->None:
parser=argparse.ArgumentParser(
description="Visualize a model using model explorer."
)
parser.add_argument(
"--model_dir", required=True, type=str, help="Path to the model directory"
)
parser.add_argument(
"--pte",
action="store_true",
help="Visualize PTE flatbuffer model and delegates. Cannot be used with --tosa",
)
parser.add_argument(
"--tosa",
action="store_true",
help="Visualize TOSA flatbuffer model. Cannot be used with --pte",
)
parser.add_argument(
"--trace",
required=False,
help="(perf mode) PMU trace JSON.gz file with performance data. Can only be used together with --tosa",
)
parser.add_argument(
"--tables",
required=False,
help="(perf mode) Vela debug database tables XML file",
)
args=parser.parse_args()
ifargs.pteandargs.tosa:
raiseValueError("Cannot use both --pte and --tosa options together")
model_dir=Path(args.model_dir).resolve()
tosa_files=list(model_dir.glob("*TOSA*.tosa"))
model_files=None
ifargs.pte:
model_files=list(model_dir.glob("*.pte"))
elifargs.tosa:
model_files=tosa_files
ifnotmodel_files:
raiseFileNotFoundError(
f"No model files found in {model_dir} for the specified format."
)
model_file=model_files[0]
validate_file_exists(model_file)
config=model_explorer_config()
extensions= []
ifargs.pte:
set_pte_model_explorer_config(model_file, tosa_files, config)
elifargs.tosa:
set_tosa_model_explorer_config(model_file, config)
extensions.append("tosa_adapter_model_explorer")
ifargs.traceorargs.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=extensions)
if__name__=="__main__":
main()