-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgen_operators.py
1377 lines (1138 loc) · 49.9 KB
/
gen_operators.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) 2019 Graphcore Ltd. All rights reserved.
import onnx.defs
import io
import os
import numpy as np # type: ignore
import textwrap
import subprocess
# Remove leading new lines and then set the identation on a
# multi line string.
def format_method(x, indent=0):
if x.startswith("\n"):
x = x[1:]
x = textwrap.dedent(x)
x = textwrap.indent(x, " " * indent)
return x
overrideOP = {
"ai.onnx.AveragePool:7": {"attributes": {"auto_pad": {"deprecated": True}}},
"ai.onnx.Conv:1": {
"verifyInput": True,
},
"ai.onnx.Conv:11": {
"verifyInput": True,
},
"ai.onnx.AveragePool:1": {
"verifyInput": True,
},
"ai.onnx.AveragePool:7": {
"verifyInput": True,
},
"ai.onnx.AveragePool:10": {
"verifyInput": True,
},
"ai.onnx.AveragePool:11": {
"verifyInput": True,
},
"ai.onnx.MaxPool:1": {"verifyInput": True},
"ai.onnx.MaxPool:8": {"verifyInput": True},
"ai.onnx.MaxPool:10": {"verifyInput": True},
"ai.onnx.MaxPool:11": {"verifyInput": True},
"ai.onnx.Pad:2": {
"verifyInput": True,
},
}
class Schema:
def __init__(self):
self.domains = {}
class Domain:
def __init__(self, name):
self.name = name
self.opsets = {}
self.operations = []
def AddOpDef(self, op):
# Only go as far back as opset 6
opset_version = op.version
if op.version <= 6:
opset_version = 6
if str(opset_version) not in self.opsets:
# Create new opset if not already defined
opset = Opset(self, opset_version)
self.opsets[str(opset_version)] = opset
# Add the op into the right opset
self.opsets[str(opset_version)].operators.append(op)
# Add the op to the list of all ops
self.operations.append(op)
op.opset = self.opsets[str(opset_version)]
def CppName(self):
"""Return a C++ compliment name for the operations."""
return "".join([s.capitalize() for s in self.name.split(".")])
def isLatestOpVersion(self, op):
"""Return whether the op is the latest defined version."""
for _op in self.operations:
if _op.name == op.name:
if _op.version > op.version:
return False
return True
class Opset:
def __init__(self, domain, version):
self.domain = domain
self.version = version
self.operators = []
def RemoveDuplicates(self):
"""
Remove duplicates from opset, leaving the largest version of each op.
When putting ops into the opset, the opset can end up with multiple
versions of the same op, this function will remove duplicates with the
smallest version number
"""
ops = []
for op in self.operators:
found = [x for x in ops if x.name == op.name]
if len(found) > 0:
ops.remove(found[0])
ops.append(op)
else:
ops.append(op)
self.operators = ops
class Attribute:
def __init__(self, op, name, type, default):
self.name = name
self.op = op
self.type = type
self.default = default
self.required = True
def isFloat(self):
return self.type == onnx.defs.OpSchema.AttrType.FLOAT
def isList(self):
if self.type == onnx.defs.OpSchema.AttrType.INTS:
return True
elif self.type == onnx.defs.OpSchema.AttrType.FLOATS:
return True
elif self.type == onnx.defs.OpSchema.AttrType.STRINGS:
return True
else:
return False
def isTensor(self):
return (
self.type == onnx.defs.OpSchema.AttrType.TENSOR
or self.type == onnx.defs.OpSchema.AttrType.SPARSE_TENSOR
)
def CppType(self):
"""
Determine the C++ type for an attribute.
"""
# Special case of Cast where we replace int with DataType
if self.op.name == "Cast":
return "const std::string&"
elif self.type == onnx.defs.OpSchema.AttrType.INT:
if self.required:
return "int64_t"
else:
if self.hasDefault():
return "int64_t"
else:
return "nonstd::optional<int64_t>"
elif self.type == onnx.defs.OpSchema.AttrType.INTS:
# Special case for axes in reduce operators as we need to distinguish
# default params from empty params. In future we may want to
# all optional parameters nonstd::optional of some sort.
# TODO T21033: Investigate all other cases
if self.op.name.lower().find("reduce") >= 0 and self.name == "axes":
return "nonstd::optional<std::vector<int64_t>>"
else:
return "const std::vector<int64_t>&"
elif self.type == onnx.defs.OpSchema.AttrType.FLOAT:
if self.required:
return "float"
else:
if self.hasDefault():
return "float"
else:
return "nonstd::optional<float>"
elif self.type == onnx.defs.OpSchema.AttrType.FLOATS:
return "const std::vector<float>&"
elif self.type == onnx.defs.OpSchema.AttrType.STRING:
if self.required:
return "const std::string&"
else:
if self.hasDefault():
return "const std::string&"
else:
return "nonstd::optional<std::string>"
elif self.type == onnx.defs.OpSchema.AttrType.STRINGS:
return "const std::vector<std::string>&"
# Special case of Loop, If, Scan where we replace
# onnx::GraphProto with Builder
elif self.type == onnx.defs.OpSchema.AttrType.GRAPH:
return "const Builder&"
elif self.type == onnx.defs.OpSchema.AttrType.TENSOR:
return "const ConstVoidData& "
elif self.type == onnx.defs.OpSchema.AttrType.SPARSE_TENSOR:
return "const ConstVoidData& "
else:
return "unknown"
def isBoostOptional(self):
if not self.required:
if not self.hasDefault():
if self.type == onnx.defs.OpSchema.AttrType.INT:
return True
elif self.type == onnx.defs.OpSchema.AttrType.FLOAT:
return True
elif self.type == onnx.defs.OpSchema.AttrType.STRING:
return True
# TODO T21033: Investigate all other cases
if (
self.type == onnx.defs.OpSchema.AttrType.INTS
and self.op.name.lower().find("reduce") >= 0
and self.name == "axes"
):
return True
return False
def hasDefault(self):
if len(str(self.default)) == 0:
return False
else:
if (
self.type == onnx.defs.OpSchema.AttrType.TENSOR
or self.type == onnx.defs.OpSchema.AttrType.SPARSE_TENSOR
):
# Not sure how to express a tensor as a default value
return False
else:
return True
def hasDefaultValue(self):
if self.required:
return False
if len(str(self.default)) == 0:
if (
self.type == onnx.defs.OpSchema.AttrType.TENSOR
or self.type == onnx.defs.OpSchema.AttrType.SPARSE_TENSOR
):
# Not sure how to express a tensor as a default value
return False
else:
return True
return True
def hasPrimitiveDefaultValue(self):
if len(str(self.default)) == 0:
return False
if self.type == onnx.defs.OpSchema.AttrType.INT:
return True
if self.type == onnx.defs.OpSchema.AttrType.FLOAT:
return True
return False
def DefaultValue(self):
"""
Return the default value for an attribute.
If there is a default value return that, else
if the attribute is not required return the default value
that the code can use to decide if the attribute can be
left out
"""
if len(str(self.default)) == 0:
# Optional but not default
if self.type == onnx.defs.OpSchema.AttrType.INT:
return "nonstd::optional<int64_t>()"
elif self.type == onnx.defs.OpSchema.AttrType.FLOAT:
return "nonstd::optional<float>()"
elif self.type == onnx.defs.OpSchema.AttrType.INTS:
# Special case for axes in reduce operators as we need to distinguish
# default params from an empty access list. In future we may want to
# all optional parameters nonstd::optional of some sort.
# TODO T21033: Investigate all other cases
if self.op.name.lower().find("reduce") >= 0 and self.name == "axes":
return "nonstd::optional<std::vector<int64_t>>()"
else:
return "std::vector<int64_t>()"
elif self.type == onnx.defs.OpSchema.AttrType.FLOATS:
return "std::vector<float>()"
elif self.type == onnx.defs.OpSchema.AttrType.STRINGS:
return "std::vector<std::string>()"
elif self.type == onnx.defs.OpSchema.AttrType.GRAPH:
return "onnx::GraphProto()"
elif self.type == onnx.defs.OpSchema.AttrType.TENSOR:
return "0"
elif self.type == onnx.defs.OpSchema.AttrType.SPARSE_TENSOR:
return "0"
elif self.type == onnx.defs.OpSchema.AttrType.STRING:
return "std::string()"
else:
return "UNKNOWN"
else:
if self.type == onnx.defs.OpSchema.AttrType.INT:
return self.default.i
elif self.type == onnx.defs.OpSchema.AttrType.FLOAT:
value = np.round(self.default.f, 5)
return str(value) + "f"
elif self.type == onnx.defs.OpSchema.AttrType.STRING:
return '"' + self.default.s.decode("utf-8") + '"'
elif self.type == onnx.defs.OpSchema.AttrType.INTS:
return "std::vector<int64_t>()"
elif self.type == onnx.defs.OpSchema.AttrType.FLOATS:
return "std::vector<float>()"
elif self.type == onnx.defs.OpSchema.AttrType.STRINGS:
return "std::vector<std::string>()"
elif self.type == onnx.defs.OpSchema.AttrType.GRAPH:
return "onnx::GraphProto()"
elif self.type == onnx.defs.OpSchema.AttrType.TENSOR:
return "0"
elif self.type == onnx.defs.OpSchema.AttrType.SPARSE_TENSOR:
return "0"
else:
return "??"
def isDeprecated(self):
# The auto_pad attribute is deprecated in all ops
if self.name == "auto_pad":
return True
if self.op.fullName() in overrideOP:
if "attributes" in overrideOP[self.op.fullName()]:
if self.name in overrideOP[self.op.fullName()]["attributes"]:
if (
"deprecated"
in overrideOP[self.op.fullName()]["attributes"][self.name]
):
return overrideOP[self.op.fullName()]["attributes"][self.name][
"deprecated"
]
return False
def isRequired(self):
if self.op.fullName() in overrideOP:
if "attributes" in overrideOP[self.op.fullName()]:
if self.name in overrideOP[self.op.fullName()]["attributes"]:
if (
"required"
in overrideOP[self.op.fullName()]["attributes"][self.name]
):
return overrideOP[self.op.fullName()]["attributes"][self.name][
"required"
]
return None
class Operation:
def __init__(self, name, version, support, onnx_schema=None):
self.opset = None
self.name = name
self.version = version
self.support = support
self.attributes = []
self.inputs = 0
self.min_input = 1
self.max_input = 1
self.outputs = 0
self.min_ouput = 1
self.max_ouput = 1
self.onnx_schema = onnx_schema
def __lt__(self, other):
"""Sort based on name."""
return self.name < other.name
def CppName(self):
"""
Return a C++ name for the operation.
Need the replace C++ key words.
"""
keywords = ["and", "or", "not", "xor", "if"]
cppname = self.name.lower()
if cppname in keywords:
cppname = "logical_" + cppname
return cppname
def CppId(self):
return self.name + "_" + str(self.version)
def fullName(self):
return f"{self.opset.domain.name}.{self.name}:{self.version}"
def verifyInput(self):
if self.fullName() in overrideOP:
if "verifyInput" in overrideOP[self.fullName()]:
return overrideOP[self.fullName()]["verifyInput"]
return False
def spaces(n):
"""
Return a string of spaces the same length as in the input string.
"""
return " " * n
def parseDefinitions():
"""Convert the schema definition to the internal representation."""
schema = Schema()
for s in onnx.defs.get_all_schemas_with_history():
domain = s.domain
if domain == "":
domain = "ai.onnx"
if domain not in schema.domains:
schema.domains[domain] = Domain(domain)
op = Operation(s.name, s.since_version, s.support_level, s)
for _ in s.inputs:
op.inputs = op.inputs + 1
op.min_input = s.min_input
if s.max_input == 2147483647:
op.max_input = -1
else:
op.max_input = s.max_input
op.min_output = s.min_output
if s.max_output == 2147483647:
op.max_output = -1
else:
op.max_output = s.max_output
for k, v in s.attributes.items():
attribute = Attribute(op, v.name, v.type, v.default_value)
attribute.required = v.required
op.attributes.append(attribute)
schema.domains[domain].AddOpDef(op)
for k, d in schema.domains.items():
for v, opset in d.opsets.items():
opset.RemoveDuplicates()
for k, v in schema.domains.items():
for op in v.operations:
print(
f"{k}:{op.name}:{op.version} i:{op.min_input}-{op.max_input} o:{op.min_output}-{op.max_output}"
)
if op.attributes is not None:
for a in sorted(op.attributes, key=lambda x: x.hasDefault()):
print(
f"- {a.name} {a.type} V:{a.hasDefaultValue()}={a.DefaultValue()} R:{a.required} D:{a.isDeprecated()}"
)
if op.fullName() in overrideOP:
if a.isRequired() is not None:
a.required = a.isRequired()
return schema
def addHeader(f: io.TextIOWrapper, opset_version: int) -> None:
f.write("// Copyright (c) 2018 Graphcore Ltd. All rights reserved.\n")
f.write("/*\n")
f.write(" * THIS IS AN AUTOGENERATED FILE, DO NOT EDIT DIRECTLY\n")
f.write(" *\n")
f.write(" * To regenerate this file run the gen_operators.py script\n")
f.write(" */\n")
# Add guard for hpp files
file_base_name = os.path.basename(f.name)
if file_base_name.endswith(".hpp"):
f.write(f"#ifndef GUARD_NEURALNET_{file_base_name.upper().replace('.', '_')}\n")
f.write(f"#define GUARD_NEURALNET_{file_base_name.upper().replace('.', '_')}\n")
# Include the docs in the popart_opset#.gen.cpp files.
if opset_version:
f.write(f'#include "popart/docs/opset{opset_version}_docs.hpp"\n')
def genBuilderHpp(filename: str, schema: Schema) -> None:
with io.open(filename, "w", encoding="utf-8") as f:
addHeader(f, None)
f.write(
"""
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include "popart/debugcontext.hpp"
#include "popart/domainopset.hpp"
#include "popart/names.hpp"
#include "popart/vendored/optional.hpp"
namespace popart {
class Builder;
class BuilderImpl;
class ConstVoidData;
"""
)
for (
k,
v,
) in schema.domains.items():
if k != "ai.onnx":
continue
for opset_version, opset in sorted(
v.opsets.items(), key=lambda x: int(x[0])
):
classname = v.CppName() + "Opset" + opset_version
if int(opset_version) == 6:
baseclass = "DomainOpSet"
else:
baseclass = v.CppName() + "Opset" + str(int(opset_version) - 1)
f.write(f"class {classname} : private {baseclass} {{\n")
f.write("\n")
f.write(" protected:\n")
f.write(f" using {baseclass}::impl;\n")
f.write(" public:\n")
f.write(
f" {classname}(std::unique_ptr<BuilderImpl>& impl_) :"
f" {baseclass}(impl_) {{}} \n"
)
f.write("\n")
f.write(" // return the opset version\n")
f.write(
" int getOpsetVersion() const override { return"
f" {opset_version};}} \n"
)
f.write("\n")
seen = []
for op in sorted(v.operations, key=lambda x: x.CppName()):
found = [x for x in opset.operators if x.name == op.name]
if (
len(found) == 0
and op.version < int(opset_version)
and int(opset_version) > 6
and op.name not in seen
):
f.write(f" using {baseclass}::{op.CppName()};\n")
seen.append(op.name)
# Add a newline after the using statements.
if len(seen) > 0:
f.write("\n")
for op in sorted(opset.operators, key=lambda x: x.name):
f.write(" /**\n")
f.write(f" * Add the '{op.name}' to the model\n")
f.write(" *\n")
if v.isLatestOpVersion(op):
f.write(
f" * https://github.com/onnx/onnx/blob/master/docs/Operators.md#{op.name}\n"
)
else:
f.write(
f" * https://github.com/onnx/onnx/blob/master/docs/Changelog.md#{op.name}-{op.version}\n"
)
f.write(" *\n")
if op.inputs > 0:
f.write(r" * \param args List of input tensor ids" + "\n")
if op.min_output != op.max_output:
f.write(
r" * \param num_outputs The number of output tensor ids"
+ "\n"
)
if int(opset_version) == 11 and op.name == "Constant":
f.write(
format_method(
r"""
* \param value The 'value' attribute"
* \param is_value_sparse If true, set the 'sparse_value' attribute
""",
5,
)
)
else:
for a in sorted(op.attributes, key=lambda x: x.hasDefault()):
if not a.isDeprecated():
f.write(
f" * \\param {a.name} The '{a.name}'"
" attribute\n"
)
f.write(
r" * \param name Optional identifier for the operation"
+ "\n"
)
if op.max_output > 1:
f.write(
r" * \\return A list of normalized output tensors"
+ "\n"
)
else:
f.write(
r" * \\return The normalized output tensor ids" + "\n"
)
f.write(" */\n")
# Handle special case Constant_11
if int(opset_version) == 11 and op.name == "Constant":
x = """
TensorId
constant(const ConstVoidData& value,
bool is_value_sparse = false,
const DebugContext &debugContext = {});
"""
x = format_method(x, 5)
f.write(x)
f.write("\n")
else:
if op.max_output == 1:
f.write(" TensorId\n")
else:
f.write(" std::vector<TensorId>\n")
f.write(f" {op.CppName()}(")
if op.inputs > 0:
f.write("const std::vector<TensorId>& args,\n")
# In the case of a variable number outputs, set the number of ouputs
if op.min_output != op.max_output:
f.write(
f" {spaces(len(op.CppName()))}unsigned"
" num_outputs,\n"
)
for a in sorted(
op.attributes,
key=lambda x: x.hasDefault() or not x.required,
):
if not a.isDeprecated():
f.write(
f" {spaces(len(op.CppName()))}{a.CppType()} {a.name}"
)
if a.hasDefaultValue():
f.write(f" = {a.DefaultValue()}")
f.write(",\n")
f.write(
f" {spaces(len(op.CppName()))}const"
" popart::DebugContext& debugContext = {});\n"
)
f.write("\n")
f.write("};\n")
f.write("\n")
f.write("} // namespace popart\n")
f.write("#endif")
subprocess.run(["clang-format", "-i", filename])
def genBuilderCpp(filename: str, schema: Schema):
with io.open(filename, "w", encoding="utf-8") as f:
addHeader(f, None)
f.write(
"""
#include "popart/builder.gen.hpp"
#include <cstdint>
#include <cstdlib>
#include <limits>
#include <map>
#include <onnx/onnx_pb.h>
#include "builder_helper.hpp"
#include "builder_impl.hpp"
#include "builderdebuginfo.hpp"
#include "filereader.hpp"
#include "onnxutil.hpp"
#include "popart/builder.hpp"
#include "popart/datatype.hpp"
#include "popart/error.hpp"
#include "popart/logging.hpp"
#include "popart/operators.hpp"
#include "popart/tensordebuginfo.hpp"
#include "popart/tensorinfo.hpp"
#include "popart/vendored/any.hpp"
#include "poparttracepoint.hpp"
namespace popart {
class ConstVoidData;
"""
)
for (
k,
v,
) in schema.domains.items():
if k != "ai.onnx":
continue
for opset_version, opset in sorted(
v.opsets.items(), key=lambda x: int(x[0])
):
classname = v.CppName() + "Opset" + opset_version
for op in sorted(opset.operators):
if int(opset_version) == 11 and op.name == "Constant":
x = """
TensorId
AiOnnxOpset11::constant(const ConstVoidData& value,
bool is_value_sparse,
const DebugContext& debugContext) {
std::map<std::string, popart::any> attributes;
if (is_value_sparse) {
throw error("Attributes of type `sparse_tensor' are currently not supported.");
} else {
attributes["value"] = value;
}
BuilderDebugInfo di(debugContext, __POPART_FUNCTION_NAME__, {}, attributes);
attributes.insert({sDebugInfoId, di.getId()});
auto outputs = impl->op(Onnx::Operators::Constant_11,
getOpsetVersion(),
{},
attributes,
{di});
di.setOutputs(outputs);
return outputs.at(0);
}
"""
x = format_method(x)
f.write(x)
f.write("\n")
continue
if op.max_output == 1:
f.write("TensorId\n")
else:
f.write("std::vector<TensorId>\n")
f.write(f"{classname}::{op.CppName()}(")
if op.inputs > 0:
f.write("const std::vector<TensorId>& args,\n")
# In the case of a variable number outputs, set the number of ouputs
if op.min_output != op.max_output:
f.write(
f"{spaces(len(classname))} "
f" {spaces(len(op.CppName()))} unsigned num_outputs,\n"
)
for a in sorted(
op.attributes, key=lambda x: x.hasDefault() or not x.required
):
if not a.isDeprecated():
f.write(
f"{spaces(len(classname))} "
f" {spaces(len(op.CppName()))} {a.CppType()} {a.name},\n"
)
f.write(
f"{spaces(len(classname))} {spaces(len(op.CppName()))} const"
" popart::DebugContext& debugContext) {\n"
)
f.write(" std::map<std::string, popart::any> attributes;\n")
for a in op.attributes:
if not a.isDeprecated():
if a.required:
isLoopOrScanBody = (
op.name == "Loop" or op.name == "Scan"
) and a.name == "body"
isIfBranch = op.name == "If" and (
a.name == "else_branch" or a.name == "then_branch"
)
if isLoopOrScanBody or isIfBranch:
f.write(
" // Special case where we convert from a Builder object to an\n"
)
f.write(
" // onnx::GraphProto object so as not to expose the onnx class\n"
)
f.write(" // at the API level\n")
f.write(
f' attributes["{a.name}"] ='
f" io::getModelFromString({a.name}.getModelProto()).graph();\n"
)
elif op.name == "Cast":
f.write(
" // Special case where we cast from DataType to int\n"
)
f.write(
" DataType toDataType ="
f" dataTypeFromString({a.name});\n"
)
f.write(
f' attributes["{a.name}"] ='
" static_cast<int>(onnxutil::getTPDataType(toDataType));\n"
)
else:
f.write(f' attributes["{a.name}"] = {a.name};\n')
elif a.isTensor():
f.write(f' attributes["{a.name}"] = {a.name};\n')
else:
if a.isList() and not a.isBoostOptional():
f.write(f" if (!{a.name}.empty()) {{\n")
elif a.isFloat() and not a.isBoostOptional():
f.write(
f" if ({a.name} != {a.DefaultValue()}) {{\n"
)
else:
if a.hasPrimitiveDefaultValue():
f.write(
" // Workaround Onnx not "
+ "applying default values "
+ "during type/shape inference"
+ "\n {\n"
)
else:
f.write(
f" if ({a.name} != {a.DefaultValue()})"
" {\n"
)
if a.isBoostOptional():
f.write(
f' attributes["{a.name}"] = *{a.name};\n'
)
else:
f.write(f' attributes["{a.name}"] = {a.name};\n')
f.write(" }\n")
if op.inputs > 0:
f.write(
" BuilderDebugInfo di(debugContext, __POPART_FUNCTION_NAME__, args, attributes);\n"
)
else:
f.write(
" BuilderDebugInfo di(debugContext, __POPART_FUNCTION_NAME__, {}, attributes);\n"
)
f.write(" attributes.insert({sDebugInfoId, di.getId()});\n")
f.write(
f" auto outputs = impl->op(Onnx::Operators::{op.CppId()},\n"
)
# Add the opset version
f.write(" getOpsetVersion(),\n")
# Add the input tensors
if op.inputs > 0:
f.write(" args,\n")
else:
f.write(" {},\n")
if op.min_output != op.max_output:
f.write(" num_outputs,\n")
f.write(" attributes,\n")
f.write(" {di}")
if op.verifyInput():
f.write(",\n")
f.write(
" [this](const std::vector<TensorId> &inputs_,\n"
)
f.write(
" std::map<std::string, popart::any> attributes_) {\n"
)
f.write(
f" verify_{classname}_{op.CppId()}(this->impl, inputs_, attributes_);\n"
)
f.write(" }")
f.write(");\n")
f.write(" di.setOutputs(outputs);\n")
if op.max_output == 1:
f.write(" return outputs[0];\n")
else:
f.write(" return outputs;\n")
f.write("}\n")
f.write("\n")
f.write("} // namespace popart\n")
subprocess.run(["clang-format", "-i", filename])
def genPythonBuilderBinds(schema: Schema) -> None:
"""
Generate the python bindings for all of the onnx operators, per opset.
Each opset's operators will be stored in a different file. This speeds
up compile time.
"""
for (
k,
v,
) in schema.domains.items():
if k != "ai.onnx":
continue
ops = []
for opset_version, opset in sorted(v.opsets.items(), key=lambda x: int(x[0])):
opset_dir = os.path.join("python", "popart", f"popart_opset{opset_version}")
os.makedirs(opset_dir, exist_ok=True)
filename = os.path.join(opset_dir, f"popart_opset{opset_version}.gen.cpp")
with io.open(filename, "w", encoding="utf-8") as f:
addHeader(f, opset_version)
# Add the include file.
f.write(
f"""#include <cstdint>
#include <initializer_list>
#include <pybind11/buffer_info.h> // IWYU pragma: keep
#include <pybind11/cast.h> // IWYU pragma: keep
#include <pybind11/functional.h> // IWYU pragma: keep
#include <pybind11/numpy.h> // IWYU pragma: keep
#include <pybind11/pybind11.h> // IWYU pragma: keep
#include <pybind11/stl.h> // IWYU pragma: keep
#include <pybind11/pytypes.h> // IWYU pragma: keep
#include <string>
#include <vector>
#include "../shared_cpp/np_utils.hpp"
#include "popart/builder.gen.hpp"
#include "popart/builder.hpp" // IWYU pragma: keep
#include "popart/debugcontext.hpp"
#include "popart/names.hpp"
#include "popart/tensordebuginfo.hpp"
#include "popart/tensorinfo.hpp"
#include "popart/vendored/optional.hpp"
#include "popart/voiddata.hpp"
namespace py = pybind11;
using namespace popart;
PYBIND11_MODULE(popart_opset{opset_version}, m) {{
"""
)
# Add all ops in the this op set
for op in opset.operators:
# Create a list of op with the greatest version number less than the opset version
# This is to deal with the opset-6
found = [x for x in ops if x.name == op.name]
if len(found) > 0:
ops.remove(found[0])
ops.append(op)
classname = v.CppName() + "Opset" + opset_version
# For each opset
f.write(f'py::class_<{classname}>(m, "{classname}")\n')
for op in sorted(ops):
def getFunc(f, op):
# Operator
f.write(f' .def("{op.CppName()}",\n')
# Special case of the constant operator
if op.name == "Constant":
if op.version == 11:
x = f"""
[]({classname} &opset, py::array array, bool is_value_sparse, const DebugContext& debugContext) {{
array = makeContiguous(array);
ConstVoidData initData;
initData.data = array.request().ptr;
initData.info = getTensorInfo(array);