-
Notifications
You must be signed in to change notification settings - Fork 524
/
Copy pathgen_oplist.py
354 lines (318 loc) · 11.4 KB
/
gen_oplist.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
# 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.
import argparse
import json
import os
import sys
from enum import IntEnum
from typing import Any, Dict, List, Optional, Set
import yaml
from torchgen.executorch.parse import strip_et_fields
from torchgen.gen import LineLoader, parse_native_yaml_struct
from torchgen.selective_build.operator import SelectiveBuildOperator
from torchgen.selective_build.selector import merge_et_kernel_metadata
# Output YAML file format:
# ------------------------
#
# <BEGIN FILE CONTENTS>
# include_all_non_op_selectives: False
# include_all_operators: False
# debug_info:
# - model1@v100
# - model2@v50
# operators:
# aten::add:
# is_root_operator: Yes
# is_used_for_training: Yes
# include_all_overloads: No
# debug_info:
# - model1@v100
# - model2@v50
# aten::add.int:
# is_root_operator: No
# is_used_for_training: No
# include_all_overloads: Yes
# et_kernel_metadata:
# aten::add.out:
# # A list of different kernel keys (tensors with dtype-enum/dim-order) combinations used in model
# - v1/6;0,1|6;0,1|6;0,1|6;0,1 # Float, 0, 1
# - v1/3;0,1|3;0,1|3;0,1|3;0,1 # Int, 0, 1
# aten::mul.out:
# - v1/6;0,1|6;0,1|6;0,1|6;0,1 # Float, 0, 1
# <END FILE CONTENTS>
class ScalarType(IntEnum):
Byte = 0
Char = 1
Short = 2
Int = 3
Long = 4
Float = 6
Double = 7
Bool = 11
# TODO(jakeszwe): Verify these are unused and then remove support
QInt8 = 12
QUInt8 = 13
QInt32 = 14
QUInt4X2 = 16
QUInt2X4 = 17
# Types currently not implemented.
# Half = 5
# ComplexHalf = 8
# ComplexFloat = 9
# ComplexDouble = 10
# BFloat16 = 15
class KernelType(IntEnum):
TENSOR = 5
TENSOR_LIST = 10
OPTIONAL_TENSOR_LIST = 11
def _get_operators(model_file: str) -> List[str]:
from executorch.codegen.tools.selective_build import ( # type: ignore[import-not-found]
_get_program_from_buffer,
_get_program_operators,
)
print("Processing model file: ", model_file)
with open(model_file, "rb") as f:
buf = f.read()
program = _get_program_from_buffer(buf)
operators = _get_program_operators(program)
print(f"Model file loaded, operators are: {operators}")
return operators
def _get_kernel_metadata_for_model(model_file: str) -> Dict[str, List[str]]:
from executorch.codegen.tools.selective_build import ( # type: ignore[import-not-found]
_get_io_metadata_for_program_operators,
_get_program_from_buffer,
_IOMetaData,
)
with open(model_file, "rb") as f:
buf = f.read()
program = _get_program_from_buffer(buf)
operators_with_io_metadata = _get_io_metadata_for_program_operators(program)
op_kernel_key_list: Dict[str, List[str]] = {}
specialized_kernels: Set[List[_IOMetaData]]
for op_name, specialized_kernels in operators_with_io_metadata.items():
print(op_name)
if op_name not in op_kernel_key_list:
op_kernel_key_list[op_name] = []
for specialized_kernel in specialized_kernels:
version = "v1"
kernel_key = version + "/"
for io_metadata in specialized_kernel:
if io_metadata.kernel_type in [
KernelType.TENSOR,
KernelType.TENSOR_LIST,
KernelType.OPTIONAL_TENSOR_LIST,
]:
dim_order = ",".join(map(str, io_metadata.dim_order))
kernel_key += f"{io_metadata.dtype};{dim_order}|"
op_kernel_key_list[op_name].append(kernel_key[:-1])
return op_kernel_key_list
def _get_et_kernel_metadata_from_ops_yaml(ops_yaml_path: str) -> Dict[str, List[str]]:
ops = []
with open(ops_yaml_path, "r") as f:
es = yaml.load(f, Loader=LineLoader)
func_entries = []
for e in es:
if "op" in e:
ops.append(("aten::" if "::" not in e.get("op") else "") + e.get("op"))
else:
func_entries.append(e)
strip_et_fields(es)
parsed_yaml = parse_native_yaml_struct(
func_entries, set(), None, path=ops_yaml_path, skip_native_fns_gen=True
)
ops.extend([f"{f.namespace}::{f.func.name}" for f in parsed_yaml.native_functions])
# TODO (larryliu): accept the new op yaml syntax
return {op: ["default"] for op in ops}
def _dump_yaml(
op_list: List[str],
output_path: str,
model_name: Optional[str] = None,
et_kernel_metadata: Optional[Dict[str, List[str]]] = None,
include_all_operators: bool = False,
):
# no debug info yet
output: dict[str, Any] = {}
operators: Dict[str, Dict[str, object]] = {}
for op_name in op_list:
op = SelectiveBuildOperator.from_yaml_dict(
op_name,
{
"is_root_operator": True,
"is_used_for_training": True,
"include_all_overloads": False,
"debug_info": [model_name],
},
)
operators[op_name] = op.to_dict()
output["operators"] = operators
output["custom_classes"] = []
output["build_features"] = []
output["include_all_non_op_selectives"] = False
output["include_all_operators"] = include_all_operators
output["kernel_metadata"] = {}
output["et_kernel_metadata"] = et_kernel_metadata
with open(output_path, "wb") as out_file:
out_file.write(
yaml.safe_dump(
output,
default_flow_style=False,
).encode("utf-8")
)
def create_kernel_key(maybe_kernel_key: str) -> str:
# It is a kernel key.
if maybe_kernel_key.lstrip().startswith("v1"):
return maybe_kernel_key
# It is a dtype.
else:
# Generate a kernel key based on the dtype provided.
# Note: no dim order is included in this kernel key.
# For a description of the kernel key format, see
# executorch/blob/main/runtime/kernel/operator_registry.h#L97-L123
try:
dtype = ScalarType[maybe_kernel_key]
return "v1/" + str(dtype.value) + ";"
except KeyError:
raise Exception(f"Unknown dtype: {maybe_kernel_key}")
def gen_oplist(
output_path: str,
model_file_path: Optional[str] = None,
ops_schema_yaml_path: Optional[str] = None,
root_ops: Optional[str] = None,
ops_dict: Optional[str] = None,
include_all_operators: bool = False,
):
assert (
model_file_path
or ops_schema_yaml_path
or root_ops
or ops_dict
or include_all_operators
), "Need to provide either model_file_path or ops_schema_yaml_path or root_ops or ops_dict or include_all_operators."
assert output_path, "Need to provide output_path for dumped yaml file."
op_set = set()
source_name = None
et_kernel_metadata = {} # type: ignore[var-annotated]
if root_ops:
# decide delimiter
delimiter = "," if "," in root_ops else " "
print(root_ops)
op_set.update(
set(filter(lambda x: len(x) > 0, map(str.strip, root_ops.split(delimiter))))
)
et_kernel_metadata = merge_et_kernel_metadata(
et_kernel_metadata, {op: ["default"] for op in op_set}
)
if ops_dict:
ops_and_metadata = json.loads(ops_dict)
for op, metadata in ops_and_metadata.items():
op_set.update({op})
op_metadata = (
[create_kernel_key(x) for x in metadata]
if len(metadata) > 0
else ["default"]
)
et_kernel_metadata = merge_et_kernel_metadata(
et_kernel_metadata, {op: op_metadata}
)
if model_file_path:
assert os.path.isfile(
model_file_path
), f"The value for --model_file_path needs to be a valid file, got {model_file_path}"
op_set.update(_get_operators(model_file_path))
source_name = model_file_path
et_kernel_metadata = merge_et_kernel_metadata(
et_kernel_metadata, _get_kernel_metadata_for_model(model_file_path)
)
if ops_schema_yaml_path:
assert os.path.isfile(
ops_schema_yaml_path
), f"The value for --ops_schema_yaml_path needs to be a valid file, got {ops_schema_yaml_path}"
et_kernel_metadata = merge_et_kernel_metadata(
et_kernel_metadata,
_get_et_kernel_metadata_from_ops_yaml(ops_schema_yaml_path),
)
op_set.update(et_kernel_metadata.keys())
source_name = ops_schema_yaml_path
_dump_yaml(
sorted(op_set),
output_path,
source_name,
et_kernel_metadata,
include_all_operators,
)
def main(args: List[Any]) -> None:
"""This binary generates selected_operators.yaml which will be consumed by caffe2/torchgen/gen.py.
It reads the model file, deserialize it and dumps all the operators into selected_operators.yaml so
it can be used in gen.py.
"""
parser = argparse.ArgumentParser(
description="Generate operator list from a model file"
)
parser.add_argument(
"--output_path",
help=("The path to the output yaml file (selected_operators.yaml)"),
required=True,
)
parser.add_argument(
"--model_file_path",
help=("Path to an executorch program"),
required=False,
)
parser.add_argument(
"--ops_schema_yaml_path",
help=("Dump operator names from operator schema yaml path"),
required=False,
)
parser.add_argument(
"--root_ops",
help=("A comma separated list of root operators used by the model"),
required=False,
)
parser.add_argument(
"--ops_dict",
help=(
"A json object containing operators and their associated dtype and dim order"
),
required=False,
)
parser.add_argument(
"--include-all-operators",
"--include_all_operators",
action="store_true",
default=False,
help="Set this flag to request inclusion of all operators (i.e. build is not selective).",
required=False,
)
options = parser.parse_args(args)
try:
gen_oplist(
output_path=options.output_path,
model_file_path=options.model_file_path,
ops_schema_yaml_path=options.ops_schema_yaml_path,
root_ops=options.root_ops,
ops_dict=options.ops_dict,
include_all_operators=options.include_all_operators,
)
except Exception as e:
command = ["python codegen/tools/gen_oplist.py"]
if options.model_file_path:
command.append(f"--model_file_path {options.model_file_path}")
if options.ops_schema_yaml_path:
command.append(f"--ops_schema_yaml_path {options.ops_schema_yaml_path}")
if options.root_ops:
command.append(f"--root_ops {options.root_ops}")
if options.ops_dict:
command.append(f"--ops_dict {options.ops_dict}")
if options.include_all_operators:
command.append("--include-all-operators")
repro_command = " ".join(command)
raise RuntimeError(
f"""Failed to generate selected_operators.yaml. Repro command:
{repro_command}
"""
) from e
if __name__ == "__main__":
main(sys.argv[1:])