-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathascend.py
1642 lines (1435 loc) · 54.2 KB
/
ascend.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
import json
import os
import math
import torch
from typing import Any, List
from torch.fx.node import Node
from torch.utils._pytree import tree_map_only
from torch._inductor.utils import IndentedBuffer
from dicp.dynamo_bridge.utils import symint_in_shape
from dicp.vendor.AscendGraph.codegen.utils import (
get_ascend_dtype,
get_cpp_dtype,
get_ascend_dtype_num
)
graph_id = 0
precision_check = bool(os.environ.get("DICP_ASCEND_PRECISION_CHECK", False))
def get_graph_id():
global graph_id
graph_id = graph_id + 1
return graph_id
def process_name(name, target):
if hasattr(target, "name"):
real_op = target.name().split('::')[-1]
if real_op.find('.') != -1:
real_op = real_op.split('.')[0]
else:
real_op = name.rsplit('_', 1)[0] if name[-1].isdigit() else name
return real_op
class AscendCodegen(torch.fx.Interpreter):
def __init__(self, graph, aten_graph=None, folder=None, graph_key=None):
self.graph = graph
self.aten_graph = aten_graph
self.override = AscendOverrides
self.import_code = IndentedBuffer()
self.build_graph_code = IndentedBuffer(initial_indent=1)
self.graph_id = str(get_graph_id())
self.args_dict = {}
self.input_args = []
self.output_args = []
self.dynamic_inputs = []
self.dynamic_shape = []
self.actual_shape = []
self.dynamic_index = []
self.symint_outputs = []
self.data_nodes = []
self.common_nodes = []
self.graph_input_names = []
self.py_output_names = []
self.graph_output_names = []
self.build_options = []
self.folder = folder
self.graph_key = graph_key
self.sym_to_inputs = {}
self.sym_in_args = {}
# for modified args return
self.assign_args = []
self.cpu_tensor = []
super().__init__(graph)
def placeholder(self, name, target, args, kwargs):
self.args_dict[name] = name
self.input_args.append(self.cur_node)
fake_tensor = self.cur_node.meta['val']
format = "NCHW"
index = -1
if isinstance(fake_tensor, torch.SymInt):
dims = [1]
data_type = "INT32"
format = "ND"
self.sym_to_inputs[fake_tensor.node.str()] = name
elif symint_in_shape(fake_tensor.shape):
# mention symint position in args
# dynamic shape feature
for idx, dim in enumerate(fake_tensor.shape):
if isinstance(dim, torch.SymInt):
st = dim.node.str()
if st not in self.sym_in_args:
self.sym_in_args[st] = (name, idx)
# deal with dynamic shape -1
shape = [-1 if isinstance(elem, torch.SymInt)
else elem for elem in fake_tensor.shape]
actual_shape = [elem.node.str() if isinstance(
elem, torch.SymInt) else str(elem) for elem in fake_tensor.shape]
self.dynamic_inputs.append(self.args_dict[name])
self.dynamic_shape.append(shape)
self.actual_shape.append(actual_shape)
self.dynamic_index.append(len(self.graph_input_names))
dims = shape
data_type = get_ascend_dtype(fake_tensor.dtype).upper()
else:
dims = list(fake_tensor.shape)
data_type = get_ascend_dtype(fake_tensor.dtype).upper()
if 'native_memory_format' in self.cur_node.meta:
format = self.cur_node.meta['native_memory_format']
# gen data_nodes
self.data_nodes.append({
"op_name": self.args_dict[name],
"op_type": "Data",
"dims": dims,
"format": format,
"data_type": data_type,
"cpp_data_type": data_type,
"index": index
})
self.graph_input_names.append(self.args_dict[name])
def call_function(self, name, target, args, kwargs):
if name not in self.args_dict.keys():
self.args_dict[name] = name
if hasattr(self.cur_node, 'meta'):
if 'prop' in self.cur_node.meta and 'cpu_tensor' in self.cur_node.meta['prop']:
self.cpu_tensor.append(self.cur_node.meta['prop']['cpu_tensor'])
if 'prop' in self.cur_node.meta and 'assign_args' in self.cur_node.meta['prop']:
self.assign_args.append(self.cur_node.meta['prop']['assign_args'])
_, args_list = AscendOverrides.gen_args(
self.args_dict[name], self.args_dict, args)
real_op = process_name(name, target)
op = getattr(self.override, real_op)(*args_list, **kwargs)
if isinstance(op, list):
self.common_nodes.extend(op)
else:
self.common_nodes.append(op)
def get_attr(self, name, target, args, kwargs):
assert isinstance(target, str)
attr = self.fetch_attr(target)
assert (isinstance(attr, torch.Tensor))
self.args_dict[name] = name
op = getattr(self.override, 'get_const_attr')(name, attr)
self.common_nodes.append(op)
def call_method(self, name, target, args, kwargs):
pass
def output(self, name, target, args, kwargs):
for arg in args:
self.output_args.extend(arg)
def run_node(self, n: Node) -> Any:
self.cur_node = n
op = n.op
name = n.name
target = n.target
args = n.args
kwargs = n.kwargs
assert isinstance(args, tuple)
assert isinstance(kwargs, dict)
return getattr(self, op)(name, target, args, kwargs)
def codegen(self):
self.run()
return self.generate_code()
def parse_outputs(self):
symint_inputs = self.sym_to_inputs.values()
real_output_args = []
for node in self.output_args:
if isinstance(node, torch.fx.node.Node):
name = self.args_dict[node.name]
self.py_output_names.append(name)
if name in self.graph_output_names or name in self.graph_input_names:
continue
else:
real_output_args.append(node)
self.graph_output_names.append(name)
if name in symint_inputs:
self.symint_outputs.append(name)
else:
self.py_output_names.append(str(node))
self.output_args = real_output_args
if len(self.assign_args) > 0:
self.graph_output_names.extend(list(zip(*self.assign_args))[0])
def gen_import_code(self):
self.import_code.splice(
"""
from ctypes import c_void_p, c_long
import torch
import torch_dipu
import random
from torch import empty_strided, as_strided, device
from dicp.dynamo_bridge.compile import AsyncCompileKernel
from dicp.vendor.AscendGraph.compile_job import AscendCompileJob
aten = torch.ops.aten
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
def check_tensor(a, b, atol=5e-2, rtol=1e-2):
if not torch.allclose(a, b, atol=atol, rtol=rtol, equal_nan=True):
import pdb;pdb.set_trace()
pass
""", strip=True
)
return self.import_code.getvalue()
def operator_in_str(self, st):
for op in ['+', '-', '*', '/']:
if op in st:
return True
return False
def process_sym_name(self, st):
# dynamic shape feature
# return string wrapper in new version
# node.str() will not fallback SymInt value form
if isinstance(st, torch.SymInt):
return st.node.str()
return str(st)
def gen_call_func(self):
# TODO check scalar input
call_body = IndentedBuffer()
self.args = [self.args_dict[x.name] for x in self.input_args]
shape_symint = [value[0] for value in self.sym_in_args.values()]
# dynamic shape feature
if len(self.sym_in_args) > 0 or len(self.sym_to_inputs) > 0:
args = ['_' if arg not in shape_symint and arg not in self.sym_to_inputs.values() else arg for arg in self.args]
call_body.writeline(f"({','.join(args)}) = args")
# assign SymInt to InputArgs relationship
if len(self.sym_in_args) > 0:
for key in self.sym_in_args.keys():
if not key.isdigit() and not self.operator_in_str(key):
call_body.writeline(f"{key} = {self.sym_in_args[key][0]}.shape[{self.sym_in_args[key][1]}]")
if len(self.sym_to_inputs) > 0:
for key in self.sym_to_inputs.keys():
if not key.isdigit() and not self.operator_in_str(key):
call_body.writeline(f"{key} = {self.sym_to_inputs[key]}")
# generate input dims
if len(self.dynamic_inputs) > 0:
dim_len = 0
for shape in self.actual_shape:
dim_len += len(shape)
dims = 'dims = {'
for idx, elem in enumerate(self.actual_shape):
if len(elem) == 0:
continue
elem = [self.process_sym_name(dim) for dim in elem]
dims += str(self.dynamic_index[idx]) + \
":[" + ','.join(map(str, elem)) + '],'
dims = dims[:-1] + '}'
call_body.writeline(dims)
else:
call_body.writeline('''dims = None''')
# generate output shapes
# dynamic shape feature
extra_stride_str = ''
extra_storage_offset_str = ''
if len(self.sym_in_args) > 0 or len(self.sym_to_inputs) > 0:
shape_str = '''output_shape = ['''
for elem in self.output_args:
if hasattr(elem, 'meta'):
elem = elem.meta['val']
if isinstance(elem, torch.SymInt) or isinstance(elem, torch.SymBool):
shape_str += '[1],'
continue
shape = list(elem.shape)
if len(shape) == 0:
raise RuntimeError("Error handling empty output_shape")
shape = [self.process_sym_name(dim) for dim in shape]
shape_str += "[" + ','.join(map(str, shape)) + "],"
# process output_shape with modified args
for elem in self.assign_args:
shape = list(self.input_args[elem[1]].meta['val'].shape)
if len(shape) == 0:
raise RuntimeError("Error handling empty output_shape")
shape = [self.process_sym_name(dim) for dim in shape]
shape_str += "[" + ','.join(map(str, shape)) + "],"
stride = list(self.input_args[elem[1]].meta['val'].stride())
if len(stride) == 0:
raise RuntimeError("Error handling empty output_stride")
stride = [self.process_sym_name(dim) for dim in stride]
extra_stride_str += '[' + ','.join(map(str, stride)) + '],'
extra_storage_offset_str += str(self.input_args[elem[1]].meta['val'].storage_offset()) + ','
shape_str = shape_str[:-1] + ''']'''
call_body.writeline(shape_str)
else:
call_body.writeline('''output_shape = None''')
# add stride & storage_offset info
out_strides = []
out_storage_offsets = []
for elem in self.output_args:
if hasattr(elem, 'meta'):
elem = elem.meta['val']
if isinstance(elem, torch.SymInt) or isinstance(elem, torch.SymBool):
out_strides.append('[1]')
out_storage_offsets.append('0')
continue
if elem.dim() == 0: # temporary solution for sum.default(a) whose result is a scalar(no dim no stride)
out_strides.append('[1]')
out_storage_offsets.append('0')
continue
stride = list(elem.stride())
stride = [self.process_sym_name(dim) for dim in stride]
out_strides.append(str(stride))
out_storage_offsets.append(elem.storage_offset())
call_body.writeline(f'out_stride = {out_strides}')
call_body.writeline(f'out_storage_offset = {out_storage_offsets}')
call_body.splice("""
import torch_dipu
dipu_device_str = torch_dipu.dipu.device.__diputype__
for idx in range(len(args)):
if isinstance(args[idx], int):
args[idx] = torch.tensor(args[idx], device=dipu_device_str, dtype=torch.int32)
""", strip=True)
call_body.writeline(f"({','.join(self.args)}) = args")
# dealing with modified args passing back
allocated_output = {}
for item in self.assign_args:
input_index = item[1]
output_index = self.graph_output_names.index(item[0])
allocated_output[output_index] = input_index
call_body.writeline(f'allocated_output= {allocated_output}')
call_str = ['output_tensor = kernel_cpp_0(args, dims, output_shape, out_stride, out_storage_offset, allocated_output)']
if precision_check and self.aten_graph is not None:
# import aten graph
call_str.append("import sys")
call_str.append(f"if '{self.folder}' not in sys.path:")
call_str.append(f" sys.path.insert(0, '{self.folder}')")
call_str.append(f"from {self.graph_key[:4]} import {self.graph_key} as graph_module")
call_str.append("aten_call = graph_module()")
call_str.append('aten_args = list(map(lambda x: x.to("cpu"), args))')
call_str.append('for idx in modified:')
call_str.append(' aten_args[idx] = aten_args[idx].item()')
call_str.append('aten_output = aten_call(*aten_args)')
for i, name in enumerate(self.graph_output_names):
if name not in self.symint_outputs:
if name in self.cpu_tensor:
call_str.append(f'{name} = output_tensor[{i}].cpu()')
else:
call_str.append(f'{name} = output_tensor[{i}]')
else:
call_str.extend([f'del {name}',
f'{name} = int(output_tensor[{i}])'])
if precision_check:
for i, name in enumerate(self.py_output_names):
if name != 'None' and name not in self.args and name not in self.symint_outputs:
call_str.append(f"{name}_cpu = aten_output[{i}]")
call_str.append(f"check_tensor({name}.cpu(), {name}_cpu)")
call_body.writelines(call_str)
del_args = [f'del {x}' for x in self.args if x not in self.py_output_names]
call_body.writelines(del_args)
call_body.writeline("args.clear()")
call_body.writeline(f"return ({', '.join(self.py_output_names)})")
call_func = IndentedBuffer()
call_func.writeline("def call(args):")
with call_func.indent():
call_func.splice(call_body)
return call_func.getvalue()
def gen_main_func(self):
main_body = IndentedBuffer()
main_body.splice(
"""
from torch._dynamo.testing import rand_strided
from torch._inductor.utils import print_performance
""", strip=True
)
py_rand_inputs = []
for i in range(len(self.input_args)):
node = self.input_args[i]
name = self.args[i]
val = node.meta['val']
if isinstance(val, torch.SymInt):
code_str = f'''{name} = random.randint(0, 4)'''
else:
shape = str(tuple(val.size()))
stride = str(tuple(val.stride()))
device = val.device.type
dtype = str(val.dtype)
code_str = f'''{name} = rand_strided({shape}, {stride}, device='{device}', dtype={dtype})'''
py_rand_inputs.append(code_str)
main_body.writelines(py_rand_inputs)
main_body.writeline(
f"print_performance(lambda: call([{', '.join(self.args)}]))")
main_func = IndentedBuffer()
main_func.writeline("""if __name__ == "__main__":""")
with main_func.indent():
main_func.splice(main_body)
return main_func.getvalue()
def gen_build_options(self):
if len(self.dynamic_inputs) > 0:
self.build_options.append(
{
"name": "input_format",
"value": "ND"
}
)
value_str = ""
for idx, name in enumerate(self.dynamic_inputs):
value_str += f"{name}:"
value_str += ','.join(map(str, self.dynamic_shape[idx])) + ';'
value_str = value_str[:-1]
self.build_options.append(
{
"name": "input_shape",
"value": value_str
}
)
def expand_symint(self, d, k):
if isinstance(d[k], torch.SymInt):
if d[k].node.str().isdigit():
d[k] = d[k].node.hint
else:
raise RuntimeError("expand_symint failed!")
def remove_symint(self, cur):
if isinstance(cur, list):
for idx in range(len(cur)):
self.expand_symint(cur, idx)
self.remove_symint(cur[idx])
elif isinstance(cur, dict):
for k in cur.keys():
self.expand_symint(cur, k)
self.remove_symint(cur[k])
def gen_graph_json(self):
self.parse_outputs()
self.gen_build_options()
has_dynamic_shape = False if len(self.sym_in_args) == 0 and len(self.sym_to_inputs) == 0 else True
graph = {
"name": "graph",
"input_names": self.graph_input_names,
"output_names": self.graph_output_names,
"has_dynamic_shape": has_dynamic_shape,
"build_options": self.build_options,
"data_nodes": self.data_nodes,
"common_nodes": self.common_nodes,
}
self.remove_symint(graph)
return json.dumps(graph)
def gen_compile_graph_code(self):
compile_graph_code = IndentedBuffer()
graph_json = self.gen_graph_json()
compile_graph_code.splice(
f"""
ascend_compile_job = AscendCompileJob('''{graph_json}''')
async_compile = AsyncCompileKernel()
kernel_cpp_0 = async_compile.compile_kernel(ascend_compile_job)
""", strip=True
)
compile_graph_code.writeline('async_compile.wait(globals())')
compile_graph_code.writeline('del async_compile')
return compile_graph_code.getvalue()
def generate_code(self):
return (self.gen_import_code() + self.gen_compile_graph_code() + self.gen_call_func() + self.gen_main_func())
class AscendOperator:
def __init__(self, op_name: str, op_type: str):
self.op_name = op_name
self.op_type = op_type
self.inputs = []
self.outputs = []
self.attrs = []
self.dynamic_inputs = []
self.dynamic_outputs = []
def to_node(self):
node = {
"op_name": self.op_name,
"op_type": self.op_type,
}
if len(self.inputs) > 0:
node["inputs"] = self.inputs
if len(self.outputs) > 0:
node["outputs"] = self.outputs
if len(self.attrs) > 0:
node["attrs"] = self.attrs
if len(self.dynamic_inputs) > 0:
node["dynamic_inputs"] = self.dynamic_inputs
if len(self.dynamic_outputs) > 0:
node["dynamic_outputs"] = self.dynamic_outputs
return node
def set_input(self, name, value):
self.inputs.append({
"name": name,
"value": value,
})
def set_output_desc(self, name, shape, format, data_type):
self.outputs.append({
"output_name": name,
"update_desc": {
"format": format,
"shape": shape,
"data_type": data_type
}
})
def set_input_with_index(self, name, value, index):
self.inputs.append({
"name": name,
"value": value,
"index": index,
})
def set_dynamic_output(self, name, num):
self.dynamic_outputs.append({
"name": name,
"num": num
})
def set_and_update_input(self, name, value, shape, format, data_type, output_name="y"):
self.inputs.append({
"name": name,
"value": value,
"update_desc": {
"format": format,
"shape": shape,
"data_type": data_type,
"output_name": output_name,
}
})
def set_dynamic_input(self, name, num, value, set_input_with_name=False):
assert len(value) == num
dy_inputs = {
"name": name,
"num": num,
"value": [],
}
if set_input_with_name is False:
for i in range(num):
dy_inputs["value"].append({
"index": i,
"value": value[i],
})
else:
for i in range(num):
dy_inputs["value"].append({
"index": i,
"value": value[i]["input_name"],
"edge": value[i]["edge_name"]
})
self.dynamic_inputs.append(dy_inputs)
def set_attr_list_int(self, name: str, value: List[int]):
self.attrs.append({
"name": name,
"value_type": "list_int",
"value": value,
})
def set_attr_list_float(self, name: str, value: List[float]):
self.attrs.append({
"name": name,
"value_type": "list_float",
"value": value,
})
def set_attr_bool(self, name: str, value: bool):
self.attrs.append({
"name": name,
"value_type": "bool",
"value": value,
})
def set_attr_str(self, name: str, value: str):
self.attrs.append({
"name": name,
"value_type": "str",
"value": value,
})
def set_attr_int(self, name: str, value: int):
self.attrs.append({
"name": name,
"value_type": "int",
"value": value
})
def set_attr_int64(self, name: str, value: int):
self.attrs.append({
"name": name,
"value_type": "int64",
"value": value
})
def set_attr_float(self, name: str, value: float):
self.attrs.append({
"name": name,
"value_type": "float",
"value": float(value)
})
def set_attr_dtype_str(self, name: str, value: str):
self.attrs.append({
"name": name,
"value_type": "dtype_str",
"value": value
})
def set_attr_tensor(self, name: str, data_type: str,
cpp_data_type: str,
format: str,
value: List,
dims: List[int]):
self.attrs.append({
"name": name,
"value_type": "tensor",
"tensor_data_type": data_type,
"tensor_cpp_data_type": cpp_data_type,
"tensor_format": format,
"tensor_value": value,
"tensor_dims": dims,
})
OP = AscendOperator
class AscendOverrides:
@staticmethod
def gen_args(op_var, args_dict, args):
src_code = IndentedBuffer()
args_str = [op_var]
args_str.extend(tree_map_only(Node, lambda x: args_dict[x.name], args))
return src_code, args_str
@staticmethod
def LayerNorm(name, x, begin_dim, weight, bias, eps):
op = OP(name, "LayerNorm")
op.set_input("x", x)
op.set_input("gamma", weight)
op.set_input("beta", bias)
op.set_attr_int("begin_norm_axis", begin_dim)
op.set_attr_int("begin_params_axis", begin_dim)
op.set_attr_float("epsilon", eps)
return op.to_node()
@staticmethod
def GroupNorm(name, x, weight, bias, N, C, HxW, group, eps):
op = OP(name, "GroupNorm")
op.set_input("x", x)
op.set_input("gamma", weight)
op.set_input("beta", bias)
op.set_attr_int("num_groups", group)
op.set_attr_float("eps", eps)
return op.to_node()
@staticmethod
def Mul(name, x, y):
op = OP(name, "Mul")
op.set_input("x1", x)
op.set_input("x2", y)
return op.to_node()
@staticmethod
def Muls(name, x, y):
op = OP(name, "Muls")
op.set_input("x", x)
op.set_attr_float("value", float(y))
return op.to_node()
@staticmethod
def IdentityN(name, *args, **kwargs):
input_names = []
for input in args:
if f"{input}_edge_name" in kwargs:
edges: list(str) = kwargs[f"{input}_edge_name"]
for i in range(len(edges)):
input_names.append(
{"input_name": input, "edge_name": edges[i]})
else:
input_names.append(input)
id_op = OP(name, "IdentityN")
id_op.set_dynamic_input("x", len(input_names),
input_names, len(kwargs) > 0)
id_op.set_dynamic_output("y", len(input_names))
return id_op.to_node()
@staticmethod
def Adds(name, x, y):
adds_op = OP(name, "Adds")
adds_op.set_input("x", x)
adds_op.set_attr_float("value", float(y))
return adds_op.to_node()
@staticmethod
def Add(name, x, y):
add_op = OP(name, "Add")
add_op.set_input("x1", x)
add_op.set_input("x2", y)
return add_op.to_node()
@staticmethod
def Sub(name, x, y):
sub_op = OP(name, "Sub")
sub_op.set_input("x1", x)
sub_op.set_input("x2", y)
return sub_op.to_node()
@staticmethod
def Relu(name, x):
op = OP(name, "Relu")
op.set_input("x", x)
return op.to_node()
@staticmethod
def Gelu(name, x):
op = OP(name, "Gelu")
op.set_input("x", x)
return op.to_node()
@staticmethod
def Swish(name, x, scale):
silu_op = OP(name, "Swish")
silu_op.set_input("x", x)
silu_op.set_attr_float("scale", scale)
return silu_op.to_node()
@staticmethod
def Transpose(name, input, perm):
transpose_op = OP(name, "Transpose")
transpose_op.set_input("x", input)
transpose_op.set_input("perm", perm)
return transpose_op.to_node()
@staticmethod
def Sqrt(name, x):
op = OP(name, "Sqrt")
op.set_input("x", x)
return op.to_node()
@staticmethod
def Div(name, x1, x2):
op = OP(name, "Div")
op.set_input("x1", x1)
op.set_input("x2", x2)
return op.to_node()
@staticmethod
def DivNoNan(name, x1, x2):
op = OP(name, "DivNoNan")
op.set_input("x1", x1)
op.set_input("x2", x2)
return op.to_node()
@staticmethod
def Select(name, cond, x1, x2):
op = OP(name, "SelectV2")
op.set_input("condition", cond)
op.set_input("then", x1)
op.set_input("else", x2)
return op.to_node()
@staticmethod
def Rsqrt(name, x):
op = OP(name, "Rsqrt")
op.set_input("x", x)
return op.to_node()
@staticmethod
def Conv2D(name, input, weight, stride, padding,
dilation, groups, format, bias):
op = OP(name, "Conv2D")
op.set_input("x", input)
op.set_input("filter", weight)
op.set_attr_list_int("strides", stride)
op.set_attr_list_int("pads", padding)
op.set_attr_list_int("dilations", dilation)
op.set_attr_int("groups", groups)
op.set_attr_str("data_format", format)
if bias is not None:
op.set_input("bias", bias)
return op.to_node()
@staticmethod
def ReduceMeanD(name, x, axes, keepdim=False, noop_with_empty_axes=False):
mean_op = OP(name, "ReduceMeanD")
mean_op.set_input("x", x)
mean_op.set_attr_list_int("axes", axes)
mean_op.set_attr_bool("keep_dims", keepdim)
mean_op.set_attr_bool("noop_with_empty_axes", noop_with_empty_axes)
return mean_op.to_node()
@staticmethod
def GreaterEqual(name, x, y):
ge_op = OP(name, "GreaterEqual")
ge_op.set_input("x1", x)
ge_op.set_input("x2", y)
return ge_op.to_node()
@staticmethod
def AddV2(name, x1, x2):
add_op = OP(name, "AddV2")
add_op.set_input("x1", x1)
add_op.set_input("x2", x2)
return add_op.to_node()
@staticmethod
def get_const_attr(name, x):
if hasattr(x, 'meta'):
x = x.meta['val']
x_shape = list(x.shape)
x_value = x.tolist()
if not isinstance(x_value, list):
x_value = [x_value]
torch_dtype = x.dtype
cpp_dtype = get_cpp_dtype(torch_dtype)
ascend_dtype = get_ascend_dtype(torch_dtype)
op = OP(name, "Const")
op.set_attr_tensor("value", ascend_dtype, cpp_dtype,
"ND", x_value, x_shape)
return op.to_node()
@staticmethod
def MaskedFill(name, x, mask, value):
op = OP(name, "MaskedFill")
op.set_input("x", x)
op.set_input("mask", mask)
op.set_input("value", value)
return op.to_node()
@staticmethod
def Unsqueeze(name, x, dim):
op = OP(name, "Unsqueeze")
op.set_input("x", x)
op.set_attr_list_int("axes", dim)
return op.to_node()
@staticmethod
def Squeeze(name, x, dim):
op = OP(name, "Squeeze")
op.set_input("x", x)
op.set_attr_list_int("axis", dim)
return op.to_node()
@staticmethod
def Identity(name, input, index=None):
op = OP(name, "Identity")
if index is not None and isinstance(index, int):
op.set_input_with_index("x", input, index)
else:
op.set_input("x", input)
return op.to_node()
@staticmethod
def IdentityInp(name, input, dst=None):
op = OP(name, "Identity")
op.set_input("x", input)
return op.to_node()
@staticmethod
def Exp(name, x):
op = OP(name, "Exp")
op.set_input("x", x)
return op.to_node()
@staticmethod
def Sigmoid(name, x):
op = OP(name, "Sigmoid")
op.set_input("x", x)
return op.to_node()
@staticmethod
def Pow(name, x, exp):
op = OP(name, "Pow")
op.set_input("x1", x)
op.set_input("x2", exp)
return op.to_node()
@staticmethod
def Maximum(name, a, b):
op = OP(name, "Maximum")
op.set_input("x1", a)
op.set_input("x2", b)
return op.to_node()
@staticmethod
def SoftmaxV2(name, x, dim):
op = OP(name, "SoftmaxV2")
op.set_input("x", x)
op.set_attr_list_int("axes", dim)
return op.to_node()
@staticmethod
def ReduceSum(name, x, axes, keep_dims):
op = OP(name, "ReduceSum")
op.set_input("x", x)
op.set_input("axes", axes)
op.set_attr_bool("keep_dims", keep_dims)
return op.to_node()
@staticmethod
def ReduceSumD(name, x, axes, keep_dims):
op = OP(name, "ReduceSumD")
op.set_input("x", x)
op.set_attr_list_int("axes", axes)
op.set_attr_bool("keep_dims", keep_dims)
return op.to_node()
@staticmethod
def ReduceMaxD(name, x, axes, keep_dims):
op = OP(name, "ReduceMaxD")
op.set_input("x", x)
op.set_attr_list_int("axes", axes)
op.set_attr_bool("keep_dims", keep_dims)
return op.to_node()
@staticmethod
def Permute(name, x, order=[0]):
op = OP(name, "Permute")
op.set_input("x", x)
op.set_attr_list_int("order", order)
return op.to_node()
@staticmethod
def ReduceStdV2Update(name, x, mean, dim, unbiased, keepdim):
op = OP(name, "ReduceStdV2Update")
op.set_input("x", x)
op.set_input("mean", mean)
op.set_attr_list_int("dim", dim)
op.set_attr_bool("unbiased", unbiased)
op.set_attr_bool("keepdim", keepdim)
return op.to_node()
@staticmethod
def Log(name, x):
op = OP(name, "Log")
op.set_input("x", x)
return op.to_node()
@staticmethod
def Neg(name, x):
op = OP(name, "Neg")
op.set_input("x", x)
return op.to_node()
@staticmethod
def Expand(name, x, shape):
op = OP(name, "Expand")
op.set_input("x", x)
op.set_input("shape", shape)
return op.to_node()
@staticmethod
def ExpandD(name, x, shape):
op = OP(name, "ExpandD")
op.set_input("x", x)
op.set_attr_list_int("shape", shape)
return op.to_node()
@staticmethod
def ZerosLike(name, x, *args):
# TODO(tangzhiyi): ignore kwargs, need to check this
op = OP(name, "ZerosLike")
op.set_input("x", x)
return op.to_node()