forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgen_python_functions.py
1480 lines (1230 loc) · 51.3 KB
/
gen_python_functions.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
# Generates Python bindings for ATen functions
#
# The bindings are generated as methods on python_variable or functions on the
# torch._C._nn object.
#
# Code tries to stick to the following rules:
#
# - templates should be colocated with the functions that use them.
# no templates are currently shared between functions, but if that
# happens, maybe put the template with the first one
#
# - don't use environment dictionaries when calling template.substitute().
# pass named arguments directly for everything, otherwise it's much too
# hard to track what's actually being used and by who
#
# - colocate any new hacks/adjustments with existing ones of the same kind.
# ideally in a data structure rather than code if possible. See e.g.
# SCHEMA_DEFAULT_CONVERSION_HACKS, etc.
#
# - similarly, conversions from one format to another should ideally happen
# all at once in a single place.
#
# - no nontrivial nested functions. couple-liners are ok but please no more.
# especially avoid functions that read/write outer variables defined far away.
#
# - raise RuntimeError instead of asserting, and put as much
# information as is available into the message. I.e. no need to
# plumb in new params whose only purpose is to fill out an error
# message, but use what's there
#
from collections import defaultdict
import re
from .gen_variable_type import should_trace
from .utils import write
try:
from src.ATen.code_template import CodeTemplate
except ImportError:
from tools.shared.module_loader import import_module
CodeTemplate = import_module('code_template', 'aten/src/ATen/code_template.py').CodeTemplate
#
# declarations blacklist
# We skip codegen for these functions, for various reasons.
# Future PRs will categorize this list and eliminate or hoist
# them out of eager-only codegen.
# See https://github.com/pytorch/pytorch/issues/30788
#
# These functions require manual Python bindings or are not exposed to Python
SKIP_PYTHON_BINDINGS = [
'alias', 'contiguous', 'is_cuda', 'is_sparse', 'size', 'stride',
'.*_backward', '.*_backward_(out|input|weight|bias)', '.*_forward',
'.*_forward_out', '_unsafe_view', 'tensor', '_?sparse_coo_tensor.*',
'_arange.*', '_range.*', '_linspace.*', '_logspace.*',
'_sparse_add_out', '_sparse_div.*', '_sparse_mul.*', '_sparse_sub.*', '_sparse_dense_add_out',
'index', 'unique_dim_consecutive',
'_indexCopy_', 'max_values', 'min_values',
'_cumsum.*', '_cumprod.*', '_sum.*', '_prod.*',
'_th_.*', '_thnn_.*',
'arange.*', 'range.*', '_solve.*', '_inverse.*',
'_cholesky.*', '_triangular_solve.*', '_qr.*', '_symeig.*', '_svd.*',
'slice', 'randint(_out)?',
'item', '_local_scalar_dense', 'to',
'copy_sparse_to_sparse_', 'copy_',
'numpy_T', # this needs to be an attribute in Python, not a function
'nonzero(_(out|numpy))?',
'set_quantizer_', # return types not supported yet
'set_data',
'.*_overrideable', # overrideable functions for backend extension
'data', 'is_leaf', 'output_nr', '_version', 'requires_grad_', 'retain_grad'
]
# These function signatures are not exposed to Python. Note that this signature
# list does not support regex.
SKIP_PYTHON_BINDINGS_SIGNATURES = [
'add(Tensor, Scalar, Scalar)', 'add_(Tensor, Scalar, Scalar)',
'sub(Tensor, Scalar, Scalar)', 'sub_(Tensor, Scalar, Scalar)',
'mul(Tensor, Scalar)', 'mul_(Tensor, Scalar)',
'div(Tensor, Scalar)', 'div_(Tensor, Scalar)',
]
NATIVE_NAMESPACE_MAPPING = {
"torch": "THPVariableFunctionsModule",
"torch.nn": "THPNNVariableFunctionsModule"
}
def should_generate_python_binding(declaration):
name = declaration['name']
for pattern in SKIP_PYTHON_BINDINGS:
if re.match('^' + pattern + '$', name):
return False
simple_types = [arg['simple_type'] for arg in declaration['arguments']]
signature = '{}({})'.format(name, ', '.join(simple_types))
for pattern in SKIP_PYTHON_BINDINGS_SIGNATURES:
if pattern == signature:
return False
return True
#
# top-level codegen functions, called from gen_autograd
#
def get_py_variable_methods(declarations):
"""
Get declarations (grouped by name) which should be generated
as methods on Tensor.
"""
def should_bind(declaration):
return (should_generate_python_binding(declaration) and
not is_nn_module_function(declaration) and
is_tensor_method(declaration))
return group_declarations_by_op_name([d for d in declarations if should_bind(d)])
def gen_py_variable_methods(out, declarations, template_path):
"""
Generate Tensor methods.
"""
PY_VARIABLE_METHODS_CPP = CodeTemplate.from_file(template_path + '/python_variable_methods.cpp')
py_variable_methods = get_py_variable_methods(declarations)
env = create_python_bindings(py_variable_methods, is_python_method=True, module=None)
write(out, 'python_variable_methods.cpp', PY_VARIABLE_METHODS_CPP, env)
def get_py_nn_functions(declarations):
"""
Get declarations (grouped by name) which should be generated
as functions in the "nn" module.
"""
def should_bind(declaration):
return (should_generate_python_binding(declaration) and
is_nn_module_function(declaration))
return group_declarations_by_op_name([d for d in declarations if should_bind(d)])
def gen_py_nn_functions(out, declarations, template_path):
"""
Generate functions in the "nn" module.
"""
PY_NN_FUNCTIONS_CPP = CodeTemplate.from_file(template_path + '/python_nn_functions.cpp')
py_nn_functions = get_py_nn_functions(declarations)
env = create_python_bindings(py_nn_functions, is_python_method=False, module="torch.nn")
write(out, 'python_nn_functions.cpp', PY_NN_FUNCTIONS_CPP, env)
def get_py_torch_functions(declarations):
"""
Get declarations (grouped by name) which should be generated
as functions in the "torch" module.
"""
def should_bind(declaration):
return (should_generate_python_binding(declaration) and
not is_nn_module_function(declaration) and
is_torch_function(declaration))
return group_declarations_by_op_name([d for d in declarations if should_bind(d)])
def gen_py_torch_functions(out, declarations, template_path):
"""
Generate functions in the "torch" module.
"""
PY_TORCH_FUNCTIONS_CPP = CodeTemplate.from_file(template_path + '/python_torch_functions.cpp')
py_torch_functions = get_py_torch_functions(declarations)
env = create_python_bindings(py_torch_functions, is_python_method=False, module="torch")
write(out, 'python_torch_functions.cpp', PY_TORCH_FUNCTIONS_CPP, env)
def group_declarations_by_op_name(declarations):
groups = defaultdict(list)
for d in declarations:
groups[op_name(d)].append(d)
return groups
def create_python_bindings(python_functions, is_python_method, module):
"""Generates Python bindings to ATen functions"""
py_methods = []
py_method_defs = []
py_forwards = []
for name in sorted(python_functions.keys()):
overload_decls = python_functions[name]
py_methods.append(method_impl(name, overload_decls, is_python_method, module))
py_method_defs.append(method_def(name, overload_decls, is_python_method, module))
py_forwards.extend(forward_decls(name, overload_decls, is_python_method, module))
return {
'py_forwards': py_forwards,
'py_methods': py_methods,
'py_method_defs': py_method_defs,
}
#
# extracting and storing parsed args
#
UNPACK_METHODS = {
'const Tensor &': 'tensor',
'Tensor &': 'tensor',
'Generator *': 'generator',
'Storage': 'storage',
'Storage &': 'storage',
'const ScalarType &': 'scalartype',
'const THPLayout &': 'layout',
'const Device &': 'device',
'c10::optional<DimnameList>': 'toDimnameListOptional',
'c10::optional<ScalarType>': 'scalartypeOptional',
'c10::optional<MemoryFormat>': 'memoryformatOptional',
'c10::optional<Scalar>': 'scalarOptional',
'c10::optional<int64_t>': 'toInt64Optional',
'c10::optional<bool>': 'toBoolOptional',
'c10::optional<double>': 'toDoubleOptional',
'IntArrayRef': 'intlist',
'Scalar': 'scalar',
'ScalarType': 'scalartype',
'Dimname': 'dimname',
'DimnameList': 'dimnamelist',
'TensorList': 'tensorlist',
'int64_t': 'toInt64',
'bool': 'toBool',
'double': 'toDouble',
'std::string': 'string',
}
UNPACK_WITH_SIZE_METHODS = {
'TensorList': 'tensorlist_n<{}>',
'DimnameList': 'dimnamelist',
'IntArrayRef': 'intlist',
}
UNPACK_WITH_DEFAULT_METHODS = {
'const ScalarType &': 'scalartypeWithDefault',
'const THPLayout &': 'layoutWithDefault',
'const Device &': 'deviceWithDefault',
}
def parsed_arg_expr(arg, arg_index):
# e.g. for arg name 'foo', arg type 'bool', arg_index = 2, returns '_r.toBool(2)'
typename = arg['type']
default_init = arg.get('python_default_init')
if default_init is not None:
# Note: only introduced by make_python_binding_args
default_init = arg['python_default_init']
if typename not in UNPACK_WITH_DEFAULT_METHODS:
raise RuntimeError(
'type \'{}\' is not supported in python_default_init'.
format(typename))
unpack_with_default = UNPACK_WITH_DEFAULT_METHODS[typename]
return '_r.{}({}, {})'.format(unpack_with_default, arg_index, default_init)
size = arg.get('size')
if size is not None:
if typename not in UNPACK_WITH_SIZE_METHODS:
raise RuntimeError(
'type \'{}\' with definite size ({}) is not supported'.
format(typename, size))
unpack_with_size = UNPACK_WITH_SIZE_METHODS[typename].format(size)
return '_r.{}({})'.format(unpack_with_size, arg_index)
unpack = UNPACK_METHODS.get(typename)
if unpack is None:
raise RuntimeError('type \'{}\' is not supported'.format(typename))
return '_r.{}({})'.format(unpack, arg_index)
# TODO make this part of something more general, or get rid of it
def unpack_optional_dimname_list_hack(name, expr):
# optional<ArrayRef<T>> are special. The PythonArgParser returns an
# optional<vector<T>>, which cannot be implicitly converted to
# optional<ArrayRef<T>>. One needs to unwrap the optional and rewrap.
result = """\
auto __{name} = {expr};
c10::optional<{typ}> {name} = __{name} ? c10::make_optional({typ}(__{name}.value())) : c10::nullopt;
""".format(name=name, expr=expr, typ='DimnameList')
return [line.strip() for line in result.split('\n')]
def parse_arg(arg, arg_index, unpack_to_local=False):
# get parsed rhs
expr = parsed_arg_expr(arg, arg_index)
# maybe unpack to local
name = arg['name']
typename = arg['type']
if typename == 'c10::optional<DimnameList>':
inits = unpack_optional_dimname_list_hack(name, expr)
expr = name
elif unpack_to_local:
inits = ['auto {} = {};'.format(name, expr)]
expr = name
else:
inits = []
return expr, inits
#
# schema type to cpp type conversions
# some of these are to prevent dangling refs to temps, others are more obscure
# TODO don't know if these fold into more general conversions somehere, hope so
#
TEMP_SAFE_CPP_DECL_TYPE = {
'Tensor &': 'Tensor',
}
def get_cpp_decl_type(typename, ensure_temp_safe=True):
if ensure_temp_safe:
typename = TEMP_SAFE_CPP_DECL_TYPE.get(typename, typename)
return typename
def get_cpp_formal(arg, ensure_temp_safe=True):
decl_type = get_cpp_decl_type(arg['type'], ensure_temp_safe)
return '{} {}'.format(decl_type, arg['name'])
# XXX: if you got here because of an assertion failure, it doesn't mean
# it's enough to just extend the list here. Before you do this, make sure
# to add an appropriate wrap() overload in torch/csrc/autograd/utils/wrap_outputs.h.
SUPPORTED_RETURN_TYPES = {
'Tensor',
'std::tuple<Tensor,Tensor>',
'std::tuple<Tensor,Tensor,Tensor>',
'std::tuple<Tensor,Tensor,Tensor,Tensor>',
'std::tuple<Tensor,Tensor,Tensor,Tensor,Tensor>',
'std::tuple<Tensor,Tensor,Tensor,int64_t>',
'std::tuple<Tensor,Tensor,double,int64_t>',
'std::tuple<Tensor,Tensor,Tensor,Tensor,int64_t>',
'std::tuple<Tensor,Tensor,double,Tensor,int64_t>',
'std::vector<Tensor>',
'Scalar', 'bool', 'int64_t', 'void*', 'void',
'QScheme', 'double',
'IntArrayRef',
'ScalarType'
}
def get_simple_return_type(declaration):
# Use the simple_return_type (Tensor) rather than the fancy return type
# (Tensor &). This is important because the dispatch lambdas take
# mutable arguments *by value*, not by reference. If you then return
# a reference to such an argument, you will now have a pointer to a
# dangling stack entry. Not good.
#
# You want:
#
# auto dispatch_selu_ = [](Tensor self) -> Tensor { ...; return at::selu_(self); };
# ^^^^^^
#
# *not*
#
# auto dispatch_selu_ = [](Tensor self) -> Tensor& { ...; return at::selu_(self); };
# ^^^^^^^
#
# (NB: We can't make dispatch_selu_ take Tensor&, because the enclosing
# codegen looks like dispatch_selu_(_r.tensor(0)), and you can't take a
# mutable reference to temporary. Maybe we could assign it to a
# variable itself.)
#
simple_return_type = declaration['return_type'].replace(' &', '')
if simple_return_type not in SUPPORTED_RETURN_TYPES:
raise RuntimeError(declaration['name'] + " returns unsupported type " + simple_return_type)
return simple_return_type
#
# dispatch codegen
#
def get_dispatch_callee(declaration):
# format the name of the receiving function or method
if is_tensor_method(declaration):
return 'self.{}'.format(declaration['name'])
elif is_torch_function(declaration):
namespace = function_namespace(declaration)
return '{}::{}'.format(namespace, declaration['name'])
else:
raise RuntimeError('could not dispatch, neither namespace function nor Tensor method')
def get_op_args(declaration, argmap):
# returns a list of argmap values in op call order, with two wrinkles:
# 1. 'self' is eliminated for methods, it's baked into the callee expression elsewhere
# 2. declaration['call_args'] shims legacy overrides and may contain constant values,
# not just names (see load_deprecated_signatures() in gen_autograd.py)
call_args_override = declaration.get('call_args')
if call_args_override:
# names or constants
keys = call_args_override
else:
# only names
keys = [param['name'] for param in declaration['arguments']]
if is_tensor_method(declaration):
# exclude self for method calls
keys = [k for k in keys if k != 'self']
if call_args_override:
# assume missing keys are constants
return [argmap.get(k, k) for k in keys]
else:
return [argmap[k] for k in keys]
TENSOR_OPTIONS_DECL = CodeTemplate("""\
const auto ${name} = TensorOptions()
.dtype(${dtype})
.device(${device})
.layout(${layout}.layout)
.requires_grad(${requires_grad})
.pinned_memory(${pin_memory});
""")
# addition to output-variant handler in which tensor options params
# (if present) are checked against properties of a tensor output param
# TODO remove hardcoding, use unpack logic from emit_single_dispatch
PY_VARIABLE_CHECK_OUT_TYPE_HACK = CodeTemplate("""\
check_out_type_matches(_r.tensor(${out_idx}), _r.scalartype(${type_idx}), _r.isNone(${type_idx}),
_r.layout(${layout_idx}), _r.isNone(${layout_idx}),
_r.device(${device_idx}), _r.isNone(${device_idx}));
""")
# Unpack parsed args to locals, call the op, and wrap the result.
# Lambda is so GIL is back on by wrap() time (wrap can allocate)
PY_VARIABLE_WRAP = CodeTemplate("""\
${inits}
auto dispatch_${name} = [](${lambda_formals}) -> ${simple_return_type} {
${auto_no_gil}
return ${dispatch_callee}(${dispatch_args});
};
return wrap(${namedtuple_typeref}dispatch_${name}(${lambda_args})${set_requires_grad});
""")
# void return variant
PY_VARIABLE_RETURN_VOID = CodeTemplate("""\
${inits}
auto dispatch_${name} = [](${lambda_formals}) -> ${simple_return_type} {
${auto_no_gil}
${dispatch_callee}(${dispatch_args});
};
dispatch_${name}(${lambda_args})${set_requires_grad};
Py_RETURN_NONE;
""")
def emit_single_dispatch(declaration, is_python_method, output_gap=0):
"""
Emit dispatch code for a single declared overload.
"""
deprecated = '[deprecated] ' if declaration.get('deprecated', False) else ''
schema_comment = '// ' + deprecated + declaration['schema_string']
inits = [schema_comment]
pa = declaration['python_arglists']
args = pa['input_args'] + pa['input_kwargs'] + pa['output_args']
has_options = has_tensor_options(declaration)
argmap = {}
if is_python_method:
# self is passed directly to python binding, rather than parsed
argmap['self'] = {'value': 'self', 'formal': 'Tensor & self'}
for i, arg in enumerate(args):
unpack = is_scatter(arg) or (has_options and is_tensor_self(arg))
arg_expr, unpack_stmts = parse_arg(arg, i, unpack_to_local=unpack)
inits.extend(unpack_stmts)
if is_scatter(arg):
for j, elem in enumerate(arg['scatter_args']):
argmap[elem['name']] = {
'value': '{}[{}]'.format(arg_expr, j),
'formal': get_cpp_formal(elem, ensure_temp_safe=False),
}
else:
argmap[arg['name']] = {'value': arg_expr, 'formal': get_cpp_formal(arg)}
# synthetic python binding args deliver op args
binding_argmap, binding_inits, set_requires_grad = \
handle_python_binding_args(declaration, output_gap)
argmap.update(binding_argmap)
inits.extend(binding_inits)
lambda_formals = [argmap[arg['name']]['formal'] for arg in declaration['arguments']]
lambda_args = [argmap[arg['name']]['value'] for arg in declaration['arguments']]
dispatch_callee = get_dispatch_callee(declaration)
dispatch_args = get_op_args(declaration, {name: name for name, _ in argmap.items()})
auto_no_gil = [] if declaration['with_gil'] else ['pybind11::gil_scoped_release no_gil;']
simple_return_type = get_simple_return_type(declaration)
if simple_return_type == 'void':
template = PY_VARIABLE_RETURN_VOID
else:
template = PY_VARIABLE_WRAP
return template.substitute(
name=declaration['name'],
inits=inits,
lambda_formals=lambda_formals,
lambda_args=lambda_args,
dispatch_callee=dispatch_callee,
dispatch_args=dispatch_args,
auto_no_gil=auto_no_gil,
set_requires_grad=set_requires_grad,
simple_return_type=simple_return_type,
namedtuple_typeref=declaration['namedtuple_typeref'],
)
# arg['name'] to arg['simple_type'] for scattered tensor options fields
TENSOR_OPTIONS_FIELDS = {
'dtype': 'ScalarType',
'device': 'Device',
'layout': 'Layout',
'pin_memory': 'bool',
'requires_grad': 'bool',
}
def handle_python_binding_args(declaration, output_gap):
# map synthetic python binding args to op args and misc other stuff
# note: this logic shares arcane knowledge with make_python_binding_args
# and isn't completely airtight w.r.t. the possible contents of
# python_binding_args. TODO
argmap = {}
inits = []
set_requires_grad = ''
pa = declaration['python_arglists']
python_binding_args = pa['python_binding_args']
if len(python_binding_args) == 0:
# nothing to see here
return argmap, inits, set_requires_grad
args = pa['input_args'] + pa['input_kwargs'] + pa['output_args']
binding_arg_base = len(args) + output_gap
binding_arg_offsets = {arg['name']: i for i, arg in enumerate(python_binding_args)}
def binding_arg_index(name):
return binding_arg_base + binding_arg_offsets[name]
def parse_binding_arg(name):
binding_arg = python_binding_args[binding_arg_offsets[name]]
expr, _ = parse_arg(binding_arg, binding_arg_index(name))
return expr
has_output = len(pa['output_args']) == 1
tensor_options_arg = get_tensor_options(declaration)
if tensor_options_arg is not None:
# if our op has a tensor options arg, these are its scattered fields.
# first some checks
if has_output:
raise RuntimeError('{}: tensor options with output arg'.format(declaration['name']))
for arg in python_binding_args:
typename = TENSOR_OPTIONS_FIELDS.get(arg['name'])
if typename is None:
raise RuntimeError(
'{}: unrecognized tensor options field \'{}\' in python binding arguments'.
format(declaration['name'], arg['name']))
if typename != arg['simple_type']:
raise RuntimeError(
'{}: unrecognized type \'{}\' for tensor options field \'{}\' in python binding arguments'.
format(declaration['name'], arg['type'], arg['name']))
python_binding_argnames = [arg['name'] for arg in python_binding_args]
if not all([key in python_binding_argnames for key in TENSOR_OPTIONS_FIELDS.keys()]):
raise RuntimeError(
'{}: incomplete tensor options args: {}'.
format(declaration['name'], [arg['name'] for arg in python_binding_args]))
# generate a gathering initialization of options struct
argname = tensor_options_arg['name']
inits.append(TENSOR_OPTIONS_DECL.substitute({
'name': argname,
'dtype': parse_binding_arg('dtype'),
'layout': parse_binding_arg('layout'),
'device': parse_binding_arg('device'),
'requires_grad': parse_binding_arg('requires_grad'),
'pin_memory': parse_binding_arg('pin_memory'),
}))
inits.append('torch::utils::maybe_initialize_cuda({});'.format(argname))
# and add to op arg map
argmap['options'] = {
'value': argname,
'formal': get_cpp_formal(tensor_options_arg),
}
else:
# not the scattered fields of a tensor options - sort of a grab bag
if 'dtype' in binding_arg_offsets:
# we're an output-arg variant, check these args against output tensor
if not has_output:
raise RuntimeError(
'{}: dtype in python_binding_args without output arg'.
format(declaration['name']))
if not all([name in binding_arg_offsets for name in ['layout', 'device']]):
raise RuntimeError(
'{}: incomplete tensor options for output check'.
format(declaration['name']))
check_type = PY_VARIABLE_CHECK_OUT_TYPE_HACK.substitute(
out_idx=get_python_output_index(declaration),
type_idx=binding_arg_index('dtype'),
layout_idx=binding_arg_index('layout'),
device_idx=binding_arg_index('device'),
)
inits.append(check_type)
# we'll set requires_grad on outgoing tensor
if 'requires_grad' not in binding_arg_offsets:
raise RuntimeError(
'{}: expected "requires_grad" in python_binding_args absent tensor options arg but found [{}]'.
format(declaration['name'], [arg['name'] for arg in python_binding_args]))
requires_grad = parse_binding_arg('requires_grad')
set_requires_grad = '.set_requires_grad({})'.format(requires_grad)
return argmap, inits, set_requires_grad
# handler for output/no-output overload pair
# (plugged into PY_VARIABLE_CASE as ${call_dispatch})
PY_VARIABLE_OUT = CodeTemplate("""\
if (_r.isNone(${out_idx})) {
${call_dispatch}
} else {
${call_dispatch_out}
}
""")
# handler for a single parsed signature - may be a single overload or
# a pair of overloads that whose signatures only differ in output params
PY_VARIABLE_CASE = CodeTemplate("""\
case ${i}: {
${body}
}
""")
def emit_dispatch_case(i, dictionary, is_python_method):
"""
Emit dispatch code for a single parsed signature. This corresponds to either
a single overload, or a pair that differ only in output params. In the latter
case, a single signature is used for both and dispatching switches on the
presence/absence of passed output args.
- i: this signature's position in generated binding's signature list if number of
signatures > 1, otherwise None
- dictionary: contains a no-output overload declaration under 'base', and optionally
a second overload with outputs under 'out'
- true if we're generating a python method, in which case self is not parsed but
passed directly
"""
base_decl = dictionary['base']
if 'out' in dictionary:
# dispatch to output or no-output variant based on arg test
out_decl = dictionary['out']
out_idx = get_python_output_index(out_decl)
output_gap = get_python_argc(out_decl) - get_python_argc(base_decl)
call_dispatch = emit_single_dispatch(base_decl, is_python_method, output_gap)
call_dispatch_out = emit_single_dispatch(out_decl, is_python_method)
# dispatch output and no-output variants, branch on _r.isNone(<out_idx>)
body = PY_VARIABLE_OUT.substitute(
out_idx=out_idx,
call_dispatch=call_dispatch,
call_dispatch_out=call_dispatch_out,
)
else:
# no-output version only
body = emit_single_dispatch(base_decl, is_python_method)
if i is not None:
# generate case for ith overload
return PY_VARIABLE_CASE.substitute(i=i, body=body)
else:
# only one overload, omit case wrapper
return body
#
# named tuple codegen
#
def namedtuple_fieldnames(declaration):
returns = declaration['returns']
if len(returns) <= 1 or all(['field_name' not in x for x in returns]):
return []
else:
def get_field_name(x):
# See Note [field_name versus name]
if 'field_name' not in x:
# When building on Windows, `PyStructSequence_UnnamedField` could not be
# resolved by the linker for some reason, which cause error in building:
#
# python_nn_functions.cpp.obj : error LNK2001: unresolved external symbol
# PyStructSequence_UnnamedField
#
# Thus, at this point in time, we do not support unnamed
# fields in namedtuple; you must either name all fields,
# or none of them.
raise ValueError("Unnamed field is not supported by codegen")
else:
return x['field_name']
return [get_field_name(x) for x in returns]
PY_NAMEDTUPLE_FIELDSDEF = CodeTemplate("""\
static PyStructSequence_Field ${fieldsname}[] = { ${fields,} {nullptr} };
""")
PY_NAMEDTUPLE_TYPEDEF = CodeTemplate("""\
static PyTypeObject ${typename};
static bool ${typename}_initialized = false;
if (!${typename}_initialized) {
${typename}_initialized = true;
static PyStructSequence_Desc desc = { "torch.return_types.${name}", nullptr, ${fieldsname}, ${size} };
PyStructSequence_InitType(&${typename}, &desc);
${typename}.tp_repr = (reprfunc)torch::utils::returned_structseq_repr;
}
""")
def emit_namedtuple_typedefs(declarations):
"""
Generate block of named tuple type def inits, and add typeref snippets
to declarations that use them
"""
flddefnames = {} # map from unique field name lists to field def name
flddefs = [] # field def declarations
typenames = {} # map from unique name + field name lists to typedef name
typedefs = [] # typedef declarations and init code
for decl in declarations:
fieldnames = namedtuple_fieldnames(decl)
if fieldnames == []:
decl['namedtuple_typeref'] = ''
continue
fn_key = '_'.join(fieldnames)
fieldsname = flddefnames.get(fn_key)
if fieldsname is None:
fieldsname = 'NamedTuple_fields{}'.format('' if flddefs == [] else len(fielddefs))
fields = ['{{"{}", ""}}'.format(fn) for fn in fieldnames]
fieldsdef = PY_NAMEDTUPLE_FIELDSDEF.substitute(
fieldsname=fieldsname,
fields=fields
)
flddefnames[fn_key] = fieldsname
flddefs.append(fieldsdef)
name = decl['name']
key = '{}_{}'.format(name, '_'.join(fieldnames))
typename = typenames.get(key)
if typename is None:
typename = 'NamedTuple{}'.format('' if typedefs == [] else len(typedefs))
typedef = PY_NAMEDTUPLE_TYPEDEF.substitute(
name=name,
typename=typename,
size=len(fieldnames),
fieldsname=fieldsname
)
typenames[key] = typename
typedefs.append(typedef)
decl['namedtuple_typeref'] = '&{}, '.format(typename)
return flddefs + typedefs
#
# method impl codegen
#
def get_pycname(name):
return 'THPVariable_{}'.format(name)
def is_noarg_binding(overloads):
return len(overloads) == 1 and get_python_argc(overloads[0]) == 0
# python binding for all overloads of a particular function/method
PY_VARIABLE_METHOD_VARARGS = CodeTemplate(r"""\
// ${name}
static PyObject * ${pycname}(PyObject* self_, PyObject* args, PyObject* kwargs)
{
${method_header}
static PythonArgParser parser({
${signatures}
}, /*traceable=*/${traceable});
ParsedArgs<${max_args}> parsed_args;
auto _r = parser.parse(args, kwargs, parsed_args);
${check_has_torch_function}
switch (_r.idx) {
${dispatch}
}
${method_footer}
}
""")
# python binding for single-overload function/method
PY_VARIABLE_METHOD_VARARGS_SINGLETON = CodeTemplate("""\
// ${name}
static PyObject * ${pycname}(PyObject* self_, PyObject* args, PyObject* kwargs)
{
${method_header}
static PythonArgParser parser({
${signatures}
}, /*traceable=*/${traceable});
ParsedArgs<${max_args}> parsed_args;
auto _r = parser.parse(args, kwargs, parsed_args);
${check_has_torch_function}
${dispatch}
${method_footer}
}
""")
# python binding for a method with no args, shortcuts parsing
PY_VARIABLE_METHOD_NOARGS = CodeTemplate("""\
// ${name}
static PyObject * ${pycname}(PyObject* self_, PyObject* args)
{
${method_header}
${dispatch}
${method_footer}
}
""")
TORCH_FUNCTION_CHECK = CodeTemplate("""\
if(_r.has_torch_function()) {
return handle_torch_function(_r, args, kwargs, ${namespace}, ${modulename});
}
""")
# NOTE: we type the unpacked self as Tensor not Variable to avoid return type
# discrepancies on method resolution (e.g. Variable::detach_ returns void
# rather than Tensor &)
UNPACK_SELF = "Tensor& self = reinterpret_cast<THPVariable*>(self_)->cdata;"
def method_impl(name, declarations, is_python_method, module):
"""
Generate a python binding for all overloads of an op.
"""
for declaration in declarations:
# formals for python binding signature
declaration['python_arglists'] = make_python_arglists(declaration, is_python_method)
pycname = get_pycname(name)
method_header = ['HANDLE_TH_ERRORS']
method_header += emit_namedtuple_typedefs(declarations)
method_header += [UNPACK_SELF] if is_python_method else []
method_footer = ['END_HANDLE_TH_ERRORS']
# emit dispatch
if is_noarg_binding(declarations):
dispatch = emit_single_dispatch(declaration, is_python_method)
return PY_VARIABLE_METHOD_NOARGS.substitute(
name=name,
pycname=pycname,
method_header=method_header,
dispatch=dispatch,
method_footer=method_footer,
)
method_footer = ['Py_RETURN_NONE;'] + method_footer
grouped = group_overloads(declarations, is_python_method)
is_singleton = len(grouped) == 1
signatures = []
dispatch = []
for i, dictionary in enumerate(grouped):
signature = dictionary['signature']
signatures.append('"{}",'.format(signature))
overload_index = i if not is_singleton else None
dispatch.append(emit_dispatch_case(overload_index, dictionary, is_python_method))
if is_singleton:
template = PY_VARIABLE_METHOD_VARARGS_SINGLETON
else:
template = PY_VARIABLE_METHOD_VARARGS
if module:
check_has_torch_function = TORCH_FUNCTION_CHECK.substitute(
namespace=NATIVE_NAMESPACE_MAPPING[module],
modulename='"' + module + '"',
)
else:
check_has_torch_function = ''
max_args = max([get_python_argc(decl) for decl in declarations])
traceable = 'true' if all(should_trace(d) for d in declarations) else 'false'
return template.substitute(
name=name,
pycname=pycname,
method_header=method_header,
max_args=max_args,
signatures=signatures,
traceable=traceable,
check_has_torch_function=check_has_torch_function,
dispatch=dispatch,
method_footer=method_footer,
)
#
# forward declarations
#
PY_VARIABLE_FUNCTION_VARARGS_FORWARD_DECLARATION = CodeTemplate("""\
static PyObject * ${pycname}(PyObject* self_, PyObject* args, PyObject* kwargs);
""")
PY_VARIABLE_FUNCTION_NOARGS_FORWARD_DECLARATION = CodeTemplate("""\
static PyObject * ${pycname}(PyObject* self_, PyObject* args);
""")
def forward_decls(name, declarations, is_python_method, module):
if is_python_method:
return []
if is_noarg_binding(declarations):
template = PY_VARIABLE_FUNCTION_NOARGS_FORWARD_DECLARATION
else:
template = PY_VARIABLE_FUNCTION_VARARGS_FORWARD_DECLARATION
pycname = get_pycname(name)
return [template.substitute(pycname=pycname)]
#
# method def (binding table entry) codegen
#
# Python binary operator dunder methods
BINARY_OP_NAMES = [
'__lt__', '__le__',
'__gt__', '__ge__',
'__eq__', '__ne__',
'__add__', '__radd__', '__iadd__',
'__sub__', '__rsub__', '__isub__',
'__mul__', '__rmul__', '__imul__',
'__matmul__', '__rmatmul__', '__imatmul__',
'__truediv__', '__rtruediv__', '__itruediv__',
'__floordiv__', '__rfloordiv__', '__ifloordiv__',
'__mod__', '__rmod__', '__imod__',
'__divmod__', '__rdivmod__', '__idivmod__',
'__pow__', '__rpow__', '__ipow__',
'__lshift__', '__rlshift__', '__ilshift__',
'__rshift__', '__rrshift__', '__irshift__',
'__and__', '__rand__', '__iand__',
'__xor__', '__rxor__', '__ixor__',
'__or__', '__ror__', '__ior__',
]
# PyMethodDef entry for binary op, throws not implemented error
PY_VARIABLE_METHOD_BINOP_DEF = CodeTemplate("""\
{"${name}", (PyCFunction)${pycfunc_voidcast}TypeError_to_NotImplemented_<${pycname}>, ${flags}, NULL},""")
# PyMethodDef entry
PY_VARIABLE_METHOD_DEF = CodeTemplate("""\
{"${name}", (PyCFunction)${pycfunc_voidcast}${pycname}, ${flags}, NULL},""")
def method_def(name, declarations, is_python_method, module):
"""
Generate method def entry.
"""
pycname = get_pycname(name)
if is_noarg_binding(declarations):
pycfunc_voidcast = ''
flags = 'METH_NOARGS' if is_python_method else 'METH_VARARGS | METH_KEYWORDS'