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
|
"""Generate extended reference model API with eager operator execution entrypoints"""
# Copyright (c) 2021-2023, ARM Limited.
# SPDX-License-Identifier: Apache-2.0
import copy
import os
import subprocess
from pathlib import Path
from xml.dom import minidom
from jinja2 import Environment
from jinja2 import FileSystemLoader
# Note: main script designed to be run from the scripts/operator_api/ directory
def getBasePath():
return Path(__file__).resolve().parent.parent.parent
def getTosaArgTypes(tosaXml):
"""
Returns a list of the TOSA argument types from tosa.xml.
"""
argTypes = {
"tensor_t",
"in_t",
"out_t",
"mul_t",
"weight_t",
"in_out_t",
"tensor_list_t",
}
argTypesXml = tosaXml.getElementsByTagName("type")
for argTypeXml in argTypesXml:
argTypes.add(argTypeXml.getAttribute("name"))
argTypes.remove("TABLE_SIZE")
return argTypes
def getTosaDataTypes(tosaXml):
"""
Returns a list of the TOSA data types from tosa.xml.
"""
argTypes = getTosaArgTypes(tosaXml)
dataTypes = set()
dataTypesXml = tosaXml.getElementsByTagName("typesupport")
for dataTypeXml in dataTypesXml:
for argType in argTypes:
dataType = dataTypeXml.getAttribute(argType)
if dataType != "":
dataTypes.add(f"tosa_datatype_{dataType}")
return sorted(dataTypes)
def getSerializeOpType(tosaOpName):
"""
Returns the Serialization library operator that matches the TOSA operator specified.
"""
map = {
"avg_pool2d": "Pool",
"conv2d": "Conv",
"conv3d": "Conv",
"depthwise_conv2d": "Conv",
"fully_connected": "FullyConnected",
"matmul": "MatMul",
"max_pool2d": "Pool",
"transpose_conv2d": "TransposeConv",
"clamp": "Clamp",
"arithmetic_right_shift": "ArithmeticRightShift",
"mul": "Mul",
"table": "Table",
"negate": "Negate",
"pad": "Pad",
"reshape": "Reshape",
"slice": "Slice",
"tile": "Tile",
"transpose": "Transpose",
"resize": "Resize",
"rescale": "Rescale",
"cond_if": "CondIf",
"while_loop": "WhileLoop",
}
if tosaOpName not in map.keys():
return "None"
else:
return map[tosaOpName]
def getSerialLibAttsForOp(tosaOpName, allSerialLibAtts, tosaArgs):
"""
Returns the attributes required by the Serialization library for the TOSA operator specified.
Generates code to initialize Serialization library attributes. If a matching TOSA argument exists,
that value is used for initialization, otherwise a default value e.g. 0 is used.
"""
serLibOpType = getSerializeOpType(tosaOpName)
if serLibOpType not in allSerialLibAtts.keys():
return {}
else:
serLibOpAtts = copy.deepcopy(allSerialLibAtts[serLibOpType])
tosaArgsDict = {arg["name"]: arg for arg in tosaArgs}
serTosaTypeMap = {"ResizeMode": "tosa_mode"}
serAttsToFix = {
"reshape": {"new_shape": "shape"},
"transpose_conv2d": {"output_shape": "out_shape"},
}
if tosaOpName in serAttsToFix:
# Fix attributes names to match with tosa.xml
for attDefName, tosaSpecName in serAttsToFix[tosaOpName].items():
for opAtts in serLibOpAtts:
if opAtts["name"] == attDefName:
opAtts["name"] = tosaSpecName
for att in serLibOpAtts:
attName = att["name"]
attType = att["dType"]
init = ""
# Translate TOSA data types to Serialization library data types for initialization
if attType in serTosaTypeMap.keys():
init = f"const {attType} {attName} = translate_client_{serTosaTypeMap[att['dType']]}(client_{attName});"
# Initialize Serialization library attributes to their matching function parameter
elif tosaOpName == "avg_pool2d" and attName == "accum_dtype":
init = f"const tosa::DType {attName} = translate_client_acc_size(client_acc_size);"
att["dType"] = "tosa::DType"
elif attName in tosaArgsDict:
if att["SV"] == "V":
if tosaArgsDict[attName]["type"] == "tosa_tensor_t":
init = f"std::vector<{attType}> {attName};"
init = (
init
+ f"size_t {attName}_size = client_{attName}.size / sizeof({attType});"
)
init = (
init
+ f"{attType}* {attName}_data = reinterpret_cast<{attType}*>(client_{attName}.data);"
)
init = (
init
+ f"{attName}.assign({attName}_data, {attName}_data + {attName}_size);"
)
else:
init = f"const std::vector<{attType}> {attName}"
shape = tosaArgsDict[attName]["shape"]
if shape == "[]":
init = (
init
+ f"(&client_{attName}[0], &client_{attName}[0] + client_{attName}_len);"
)
else:
init = (
init
+ f"(&client_{attName}[0], &client_{attName}{shape});"
)
else:
init = ""
else:
# Initialize Serialization library attributes with no matching fuction parameter
if att["SV"] == "V":
init = f"std::vector<int32_t> {attName};"
else:
if att["dType"] == "DType":
att["dType"] = "tosa::DType"
init = f"const tosa::DType {attName} = tosa::DType::DType_FP32;"
else:
init = f"const {attType} {attName} = 0;"
att["init"] = init
return serLibOpAtts
def updateTosaArgs(tosaArgs, serialLibAtts, tosaXml):
"""
Replace TOSA argument data types with their matching Serialization attribute data types.
Delete TOSA arguments where the type couldn't be determined.
Add Serialization attributes that have no matching TOSA argument.
"""
tosaArgTypes = getTosaArgTypes(tosaXml)
serAttsDict = {att["name"]: att for att in serialLibAtts}
tosaArgsNames = [arg["name"] for arg in tosaArgs]
delTosaArgs = []
# Replace TOSA argument data types with their matching Serialization attribute data types.
for tosaArg in tosaArgs:
if tosaArg["type"] in tosaArgTypes:
if tosaArg["name"] in serAttsDict:
tosaArg["type"] = serAttsDict[tosaArg["name"]]["dType"]
else:
# Delete TOSA argument whose data type can't be determined
delTosaArgs.append(tosaArgsNames.index(tosaArg["name"]))
# Delete corresponding length argument if one exists
lenArgName = f"{tosaArg['name']}_len"
if lenArgName in tosaArgsNames:
delTosaArgs.append(tosaArgsNames.index(lenArgName))
# Delete TOSA arguments where the type couldn't be determined
for index in sorted(delTosaArgs, key=int, reverse=True):
del tosaArgs[index]
# Add Serialization attributes that have no matching TOSA argument
tosaArgNames = [arg["name"] for arg in tosaArgs]
for serAtt in serialLibAtts:
attName = serAtt["name"]
attType = serAtt["dType"]
if (attName not in tosaArgNames) and (not attType == "tosa::DType"):
serAttName = serAtt["name"]
if serAtt["SV"] == "V":
# For vector data types, insert a matching length argument
tosaArgs.insert(
len(tosaArgs) - 1,
{
"name": f"{serAttName}_len",
"type": "int32_t",
"shape": "",
"category": "",
},
)
init = f"const std::vector<{attType}> {attName}(&client_{serAttName}[0], &client_{serAttName}[0] + client_{serAttName}_len);"
shape = "[]"
else:
init = ""
shape = ""
serAtt["init"] = init
# Insert new argument
tosaArgs.insert(
len(tosaArgs) - 1,
{
"name": serAttName,
"type": serAtt["dType"],
"shape": shape,
"category": "",
},
)
def getOperators(tosaXml):
"""
Return a list of TOSA operators as defined by tosa.xml.
"""
operators = []
ignoreOps = [
"while_loop",
"cond_if",
"const",
"custom",
"fft2d",
"rfft2d",
"variable",
"variable_read",
"variable_write",
]
opsXml = tosaXml.getElementsByTagName("operator")
allSerialLibAtts = getSerialLibAtts()
for opXml in opsXml:
opName = opXml.getElementsByTagName("name")[0].firstChild.data.lower()
if opName not in ignoreOps:
operator = {"name": opName}
operator["serializeAttType"] = getSerializeOpType(opName)
tosaArgs = getTosaArgs(opXml)
serialLibAtts = getSerialLibAttsForOp(opName, allSerialLibAtts, tosaArgs)
# Handle "axis" arguments
axisList = [arg["name"] for arg in tosaArgs if arg["name"] == "axis"]
if operator["serializeAttType"] == "None" and len(axisList) > 0:
operator["serializeAttType"] = "Axis"
serialLibAtts = [
{
"name": "axis",
"dType": "int32_t",
"SV": "S",
"init": "",
}
]
updateTosaArgs(tosaArgs, serialLibAtts, tosaXml)
operator["arguments"] = tosaArgs
operator["serialLibAtts"] = serialLibAtts
serializationAttNames = [att["name"] for att in serialLibAtts]
operator["inputs"] = [
arg["name"]
for arg in tosaArgs
if arg["category"] == "input"
and arg["name"] not in serializationAttNames
]
operator["outputs"] = [
arg["name"] for arg in tosaArgs if arg["category"] == "output"
]
operators.append(operator)
return operators
def getTosaArgs(opXml):
"""
Return the arguments required for the TOSA operator specified.
"""
arguments = []
argsXml = opXml.getElementsByTagName("argument")
tosaTensorTypes = getTosaArgTypes(tosaXml)
tosaTypeMap = {"bool_t": "bool", "uint6_t": "uint8_t", "mode_t": "tosa_mode_t"}
tensorElemTypeMap = {
"resize_mode_t": "tosa_mode_t",
"acc_size_t": "tosa_acc_size_t",
}
for xmlArg in argsXml:
argName = xmlArg.getAttribute("name").lower()
tensorElemType = xmlArg.getAttribute("tensor-element-type")
if tensorElemType in tensorElemTypeMap:
argType = tensorElemTypeMap[tensorElemType]
else:
argType = xmlArg.getAttribute("type")
argShape = xmlArg.getAttribute("shape")
argCategory = xmlArg.getAttribute("category")
# FullyConnected workaround
if (argName == "weight" or argName == "bias") and (argCategory == "attribute"):
argCategory = "input"
# Update argument type
if argType[-1:] == "*":
argType = argType[:-1]
if argCategory in ["input", "output"] and argType in tosaTensorTypes:
argType = "tosa_tensor_t"
argShape = ""
if argType in tosaTypeMap:
argType = tosaTypeMap[argType]
# Add a length argument for arrays with unknown compile-time size
if argShape != "" and argShape[0] == "[" and not argShape[1:-1].isnumeric():
argShape = "[]"
arguments.append(
{
"name": f"{argName}_len",
"type": "int32_t",
"shape": "",
"category": "",
}
)
elif argShape == "" or not argShape[0] == "[":
argShape = ""
# Append argument
arguments.append(
{
"name": argName,
"type": argType,
"shape": argShape,
"category": argCategory,
}
)
return arguments
def clangFormat(filename):
cmd = ["clang-format", "-i", filename]
with open(os.devnull, "w") as devnull:
subprocess.check_call(cmd, stdout=devnull)
def getSerialLibAtts():
"""
Parse attribute.def file and return a dictionary where the keys are Serialization library operator names.
The values are the arguments required by each Serialization library operator.
"""
serialLibAtts = {}
base_path = getBasePath()
attr_def = (
base_path / "thirdparty" / "serialization_lib" / "include" / "attribute.def"
)
with open(attr_def) as file:
preamble = True
inAtt = False
opName = ""
args = []
for line in file:
if preamble and not line[: len("DEF_ATTRIBUTE(")] == "DEF_ATTRIBUTE(":
continue
else:
preamble = False
line = line.lstrip().rstrip()
if not inAtt and "DEF_ATTRIBUTE(" in line:
opName = line[len("DEF_ATTRIBUTE(") : line.find(",")]
inAtt = True
elif inAtt:
vals = line.split(",")
argName = vals[2].lstrip().strip()
if ")" in argName:
argName = argName[:-1]
arg = {
"name": argName,
"dType": vals[0].lstrip().strip(),
"SV": vals[1].lstrip().strip(),
}
args.append(arg)
if ")" in line:
serialLibAtts[opName] = args
opName = ""
args = []
inAtt = False
return serialLibAtts
def renderTemplate(environment, dataTypes, operators, template, outfile):
content = template.render(dataTypes=dataTypes, operators=operators)
with open(outfile, mode="w", encoding="utf-8") as output:
output.write(content)
print(f"Created {outfile}")
clangFormat(outfile)
def generate(environment, dataTypes, operators, base_path):
# Generate include/operators.h
template = environment.get_template("operators_h.j2")
outfile = base_path / "reference_model/include/operators.h"
renderTemplate(environment, dataTypes, operators, template, outfile)
# Generate src/operators.cc
template = environment.get_template("operators_cc.j2")
outfile = base_path / "reference_model/src/operators.cc"
renderTemplate(environment, dataTypes, operators, template, outfile)
if __name__ == "__main__":
base_path = getBasePath()
environment = Environment(
loader=FileSystemLoader(Path(__file__).resolve().parent / "templates")
)
tosaXml = minidom.parse(str(base_path / "thirdparty/specification/tosa.xml"))
dataTypes = getTosaDataTypes(tosaXml)
operators = getOperators(tosaXml)
generate(environment, dataTypes, operators, base_path)
|