forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
function_wrapper.py
1624 lines (1452 loc) · 68.7 KB
/
function_wrapper.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
# HEY! Trying to understand what this file does? Read
# "what has to be done to add a Operation ..." first!
import re
from code_template import CodeTemplate
try:
import typing # noqa: F401
except ImportError:
raise RuntimeError(
'Missing build dependency: Unable to import the `typing` module. '
'Please install it via `conda install typing` or `pip install typing`')
# flake8 doesn't take into account usages in type annotations.
from typing import Union, Set # noqa: F401
from typing import Any, Dict, List, Optional, Tuple, NamedTuple
try:
from mypy_extensions import TypedDict
except ImportError:
# Avoid the dependency on the mypy_extensions package.
# It is required, however, for type checking.
def TypedDict(name, attrs, total=True): # type: ignore
return Dict[Any, Any]
import sys
if sys.version_info[0] == 3:
string_type = str
else:
string_type = basestring
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# what has to be done to add a Operation ...
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# 1. if broadcasting or without the full list of arguments, add a non-virtual
# declaration under Type.h (right now, we call this template
# BROADCAST but it also handles default arguments)
TYPE_METHOD_DECLARATION_BROADCAST = CodeTemplate("""\
${return_type} ${api_name}(${type_method_formals}) const override;
""")
# 2. broadcasting functions are implemented in Type.cpp
TYPE_METHOD_DEFINITION_BROADCAST = CodeTemplate("""\
${return_type} TypeDefault::${api_name}(${type_method_formals}) const {
${device_guard_declaration}
Tensor ${broadcast_returns};
std::tie(${broadcast_returns}) = ${broadcast_function}(${broadcast_actuals}, "${api_name}");
return ${method_prefix_derived}${api_name}(${broadcast_modified_actuals});
}
""")
# 3. add virtual dispatch declaration to Type.h and impl to Type.cpp; method_prefix_derived
# is present for providing a base-class definition for a derived-type method with a prefix.
#
# If the declaration is abstract, then the actual implementation will
# be in a derived type; we put in a simple default "not implemented"
# stub. However, if the declaration is concrete, we dispatch to the
# actual implementation. At the moment, this situation *only* occurs
# for 'native' declarations (so the native dispatch is hardcoded into
# the template here.)
PURE_VIRTUAL_TYPE_METHOD_DECLARATION = CodeTemplate("""\
virtual ${return_type} ${method_prefix_derived}${api_name}(${type_method_formals}) const = 0;
""")
DEPRECATED_PURE_VIRTUAL_TYPE_METHOD_DECLARATION = CodeTemplate("""\
C10_DEPRECATED virtual ${return_type} \
${method_prefix_derived}${api_name}(${type_method_formals}) const = 0;
""")
PURE_VIRTUAL_TYPE_METHOD_DECLARATION_BROADCAST = CodeTemplate("""\
virtual ${return_type} ${api_name}(${type_method_formals}) const = 0;
""")
TYPE_METHOD_DECLARATION_ABSTRACT = CodeTemplate("""\
${return_type} ${method_prefix_derived}${api_name}(${type_method_formals}) const override;
""")
TYPE_METHOD_DEFINITION_ABSTRACT = CodeTemplate("""\
${return_type} TypeDefault::${method_prefix_derived}${api_name}(${type_method_formals}) const {
AT_ERROR("${method_prefix_derived}${api_name} is not implemented for type ", toString());
}
""")
TYPE_METHOD_DECLARATION_CONCRETE = CodeTemplate("""\
${return_type} ${api_name}(${type_method_formals}) const override;
""")
TYPE_METHOD_DEFINITION_CONCRETE = CodeTemplate("""\
${return_type} TypeDefault::${api_name}(${type_method_formals}) const {
${device_guard_declaration}
${type_definition_body}
}
""")
# 4. add override to TypeDerived.h
TYPE_DERIVED_DECLARATION = CodeTemplate("""\
${return_type} ${method_prefix_derived}${api_name}(${type_method_formals}) const override;
""")
# 5. add override definition to TypeDerived.cpp
TYPE_DERIVED_DEFINITION = CodeTemplate("""\
${return_type} ${Type}::${method_prefix_derived}${api_name}(${type_method_formals}) const {
${device_guard_declaration}
${type_definition_body}
}
""")
# NB: As far as ezyang can tell, we don't *have* to codegen this,
# because we will inherit it from the TYPE_METHOD_DEFINITION_CONCRETE in
# the superclass. But it doesn't seem to be harmful.
TYPE_DERIVED_DEFINITION_NATIVE = CodeTemplate("""\
${return_type} ${Type}::${api_name}(${type_method_formals}) const {
${device_guard_declaration}
${return_call} at::native::${native_type_method_dispatch}(/* actuals */ ${actuals});
}
""")
TYPE_DERIVED_DEFINITION_NATIVE_MISSING = CodeTemplate("""\
${return_type} ${Type}::${api_name}(${type_method_formals}) const {
AT_ERROR("${api_name} not supported on ${Type}");
}
""")
TYPE_DEFINITION_BODY_NATIVE = CodeTemplate("""\
${return_call} at::native::${native_type_method_dispatch}(/* native_actuals */ ${native_actuals});
""")
# Overrideable stubs to be used in user-extendable backends
TYPE_DEFINITION_EXTENSION_BACKEND = CodeTemplate("""\
${return_type} ${Type}::${method_prefix_derived}${api_name}(${type_method_formals}) const {
return ${Type}Dispatch::get_function<${return_type} (*)(${formals_types})>("${schema}")(${native_actuals});
}
""")
# add non-virtual declaration to Tensor.h
TENSOR_METHOD_DECLARATION = CodeTemplate("""\
${return_type} ${api_name}(${method_formals_with_defaults})${const_mark};
""")
# add non-virtual declaration to Tensor.cpp
TENSOR_METHOD_DEFINITION = CodeTemplate("""\
inline ${return_type} Tensor::${api_name}(${method_formals})${const_mark} {
return type().${api_name}(${method_actuals});
}
""")
# add a method declaration in Functions.h
FUNCTION_DECLARATION = CodeTemplate("""\
static inline ${return_type} ${api_name}(${formals_with_defaults});
""")
# add a method declaration in Functions.h
DEPRECATED_FUNCTION_DECLARATION = CodeTemplate("""\
C10_DEPRECATED static inline ${return_type} ${api_name}(${formals_with_defaults});
""")
# add method definition in Functions.h
FUNCTION_DEFINITION = CodeTemplate("""\
static inline ${return_type} ${api_name}(${formals}) {
return ${inferred_type}.${api_name}(${type_method_actuals});
}
""")
# add a native declaration for a native function
NATIVE_DECLARATION = CodeTemplate("""\
CAFFE2_API ${return_type} ${native_type_method_dispatch}(${formals_with_defaults});
""")
# special method definition for factory functions in Functions.h
FACTORY_DEFINITION = CodeTemplate("""\
static inline ${return_type} ${api_name}(${formals}) {
const DeviceGuard guard(options.device());
return at::native::${api_name}(${type_method_actuals});
}
""")
# We need to cast to the base type because C++ may hide the base class
# implementation of ${api_name} if we have overloaded a function with
# the same name (but different signature) already
ZERO_DIM_CHECK = CodeTemplate("""\
if (${check_name}.dim() == 0) {
return static_cast<const TypeExtendedInterface*>(this)->${api_name}(${zero_dim_actuals});
}""")
ZERO_DIM_ONLY = CodeTemplate("""\
AT_ERROR("${api_name} only supports a 0-dimensional ${check_name} tensor, but got tensor "
"with ", ${check_name}.dim(), " dimension(s).");
""")
SPARSE_CHECK = CodeTemplate("""\
if(${check_name}.is_sparse()) {
return static_cast<const TypeExtendedInterface*>(this)->${api_name}(${sparse_actuals});
}""")
BUFFER_DEFINITION = CodeTemplate("""\
auto ${name}_ = c10::make_intrusive<TensorImpl, UndefinedTensorImpl>(
${Backend}TensorId(), caffe2::TypeMeta::Make<${ScalarType}>(), ${THTensor}_new(), false).release();
auto ${name} = Tensor(${name}_, false);""")
CONDITIONAL_INITIALIZER = CodeTemplate("""\
if (${name}.defined()) {
${initializer}
}""")
CALL_TEMPLATE = CodeTemplate("${cname}(${actuals})")
class NYIError(Exception):
"""Indicates we don't support this declaration yet"""
def __init__(self, reason):
self.reason = reason
TYPE_FORMAL_GENERIC = {
'THTensor*': 'Tensor &',
'THSTensor*': 'SparseTensorRef',
'THBoolTensor*': 'Tensor &',
'THIndexTensor*': 'Tensor &',
'THIntegerTensor*': 'Tensor &',
'THDenseTensor*': 'Tensor &',
'THDenseIndexTensor*': 'Tensor &',
'THStorage*': 'Storage',
'THGenerator*': 'Generator *',
'IntArrayRefSize': 'IntArrayRef',
'accreal': 'Scalar',
'real': 'Scalar',
'long': 'int64_t',
}
DYNAMIC_TYPE = {
'THTensor*': 'Tensor',
'THSTensor*': 'SparseTensorRef',
'THBoolTensor*': 'BoolTensor',
'THIndexTensor*': 'IndexTensor',
'THIntegerTensor*': 'IntegerTensor',
'THDenseTensor*': 'Tensor',
'THDenseIndexTensor*': 'IndexTensor',
'THStorage*': 'Storage',
'THGenerator*': 'Generator*',
'IntArrayRefSize': 'IntArrayRef',
'accreal': 'accreal',
'real': 'real',
'long': 'int64_t',
}
NATIVE_DYNAMIC_TYPE = {
'Tensor &': 'Tensor',
'const Tensor &': 'Tensor',
}
TYPE_RETURN = {
'THTensor*': 'Tensor',
'THIndexTensor*': 'Tensor',
'THBoolTensor*': 'Tensor',
'THIntegerTensor*': 'Tensor',
'THSTensor*': 'Tensor',
'THDenseTensor*': 'Tensor',
'THDenseIndexTensor*': 'Tensor',
'real': 'Tensor',
'accreal': 'Tensor',
'long': 'int64_t',
}
CHECKED_CAST = {
'THTensor*':
CodeTemplate(
'checked_tensor_unwrap('
'${arg_name},"${arg_name}",${arg_pos}, ${null_okay}, '
'Backend::${Backend}, ScalarType::${ScalarName})'),
'THSTensor*':
CodeTemplate(
'checked_tensor_unwrap('
'${arg_name}.tref,"${arg_name}",${arg_pos},false, '
'Backend::${Backend}, ScalarType::${ScalarName})'),
'THBoolTensor*':
CodeTemplate(
'checked_tensor_unwrap('
'${arg_name},"${arg_name}",${arg_pos}, ${null_okay}, '
'Backend::${Backend}, ScalarType::Byte)'),
'THIndexTensor*':
CodeTemplate(
'checked_tensor_unwrap('
'${arg_name},"${arg_name}",${arg_pos}, ${null_okay}, '
'Backend::${Backend}, ScalarType::Long)'),
'THIntegerTensor*':
CodeTemplate(
'checked_tensor_unwrap('
'${arg_name},"${arg_name}",${arg_pos}, ${null_okay}, '
'Backend::${Backend}, ScalarType::Int)'),
'THDenseTensor*':
CodeTemplate(
'checked_tensor_unwrap('
'${arg_name},"${arg_name}",${arg_pos}, ${null_okay}, '
'Backend::${DenseBackend}, ScalarType::${ScalarName})'),
'THDenseIndexTensor*':
CodeTemplate(
'checked_tensor_unwrap('
'${arg_name},"${arg_name}",${arg_pos}, ${null_okay}, '
'Backend::${DenseBackend}, ScalarType::Long)'),
'THStorage*':
CodeTemplate(
'checked_storage('
'${arg_name},"${arg_name}",${arg_pos}, '
# We're punning here (Backend and DeviceType constructors coincide)
# but DeviceType is the correct way to classify storages
'DeviceType::${Backend}, at::scalarTypeToDataType(ScalarType::${ScalarName}))'),
'THGenerator*':
CodeTemplate(
'check_generator<${Backend}Generator>(${arg_name}, &globalContext().defaultGenerator(device_type()))'),
# This is a cast done via direct-construction
'IntArrayRefStride': CodeTemplate('at::IntArrayRef ${result_name} = get_intlist_stride_th(${arg_name});'),
'real': CodeTemplate('${arg_name}.to${ScalarName}()'),
'accreal': CodeTemplate('${arg_name}.to${AccScalarName}()'),
'TensorList': CodeTemplate(
'checked_tensor_list_unwrap(${arg_name},"${arg_name}",${arg_pos}, '
'Backend::${Backend}, ScalarType::${ScalarName})'),
'IntArrayRef': CodeTemplate('check_intlist<${size}>(${arg_name}, "${arg_name}", ${arg_pos}${,default_init})')
}
CHECKED_USE = {
'THTensor*': '{}_',
'THSTensor*': '{}_',
'THIndexTensor*': '{}_',
'THBoolTensor*': '{}_',
'THIntegerTensor*': '{}_',
'THDenseTensor*': '{}_',
'THDenseIndexTensor*': '{}_',
'THStorage*': '{}_.unsafeGetStorageImpl()',
'THGenerator*': '{}_->generator',
'TensorList': "{0}_.data(), {0}_.size()",
}
CHECKED_USE_NULLABLE = CodeTemplate('${arg_name}_ ? ${usage} : NULL')
ALLOC_NOARGS_WRAP = {
'THTensor*': 'c10::make_intrusive<TensorImpl, UndefinedTensorImpl>'
'(${Backend}TensorId(), caffe2::TypeMeta::Make<${ScalarType}>(), allocator(), false).release()',
'THBoolTensor*': 'c10::make_intrusive<TensorImpl, UndefinedTensorImpl>'
'(${Backend}TensorId(), scalarTypeToTypeMeta(ScalarType::Byte), allocator(), false).release()',
'THIndexTensor*': 'c10::make_intrusive<TensorImpl, UndefinedTensorImpl>'
'(${Backend}TensorId(), scalarTypeToTypeMeta(ScalarType::Long), allocator(), false).release()',
'THIntegerTensor*': 'c10::make_intrusive<TensorImpl, UndefinedTensorImpl>'
'(${Backend}TensorId(), scalarTypeToTypeMeta(ScalarType::Int), allocator(), false).release()',
'THDenseTensor*': 'c10::make_intrusive<TensorImpl, UndefinedTensorImpl>'
'(${Backend}TensorId(), caffe2::TypeMeta::Make<${ScalarType}>(), allocator(), false).release()',
'THDenseIndexTensor*': 'c10::make_intrusive<TensorImpl, UndefinedTensorImpl>'
'(${Backend}TensorId(), scalarTypeToTypeMeta(ScalarType::Long), '
'allocator(), false).release()'
}
ALLOC_WRAP = {
'THTensor*': '${arguments}',
'THBoolTensor*': '${arguments}',
'THIndexTensor*': '${arguments}',
'THIntegerTensor*': '${arguments}',
'THDenseTensor*': '${arguments}',
'THDenseIndexTensor*': '${arguments}',
}
# Replacements for constants when calling into TH
CONSTANT_REPLACEMENTS = [
('AS_REAL', '${AS_REAL}'),
('__last_dim', 'self.ndimension()-1'),
]
# Replacements for constants in header file function definitions
HEADER_CONSTANT_REPLACEMENTS = [
(r'AS_REAL\((.*)\)', r'\1'),
('__last_dim', '-1'),
]
class nested_dict(object):
def __init__(self, base, parent):
self.base, self.parent = base, parent
def __getitem__(self, x):
r = self.base.get(x)
if r is not None:
return r
return self.parent[x]
Environment = TypedDict('Environment', {
'ScalarName': str,
'THTensor': str,
'THType': str,
'THTensor': str,
'Backend': str,
'AccScalarName': str,
})
TopEnvironment = TypedDict('TopEnvironment', {
'type_registrations': List[str],
'type_headers': List[str],
'pure_virtual_type_method_declarations': List[str],
'pure_virtual_extended_type_method_declarations': List[str],
'type_method_declarations': List[str],
'type_method_definitions': List[str],
'tensor_method_declarations': List[str],
'tensor_method_definitions': List[str],
'function_declarations': List[str],
'function_definitions': List[str],
'type_ids': List[str],
'native_function_declarations': List[str],
})
# A Declarations.cwrap formal argument
# type can contain THTensor* types
THFormal = TypedDict('THFormal', {
'name': str,
'type': str,
'dynamic_type': str,
'kwarg_only': bool,
'is_nullable': bool,
'default': str,
'default_init': str,
'output': bool,
'size': int,
'declared_type': str,
'ignore_check': bool,
'allocate': bool,
'mask': bool,
'if_true': bool,
'if_false': bool,
'wrap_dim': str,
# Broadcast is originally a str but gets unwrapped to a List or Dict in-place
'broadcast': Any,
'resize': str,
'cpu_zero': bool,
'zero': bool,
}, total=False)
# Generic ATen formal or native_functions.yaml formal argument.
# type can contain Tensor& reference types.
AtFormal = TypedDict('AtFormal', {
'name': str,
'type': str,
'dynamic_type': str,
'kwarg_only': bool,
'is_nullable': bool,
'default': str,
'default_init': str,
'output': bool,
'size': int,
}, total=False)
# Note [field_name versus name]
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# What is the difference between "field_name" and "name"?
#
# Return values of ATen operators always have a name: if it is not
# explicitly assigned a name inside native_functions.yaml like func:
# myop() -> (Tensor indices, Tensor value), then the codegen will
# automatically assign it a name like result0, or name might be
# specified inside Declarations.cwrap. We don't want these assigned
# names to become part of the public API when we return a namedtuple for
# any such multiple-return function.
#
# Thus field_name is like name, but it is defined only when there is a
# name specified in native_functions.yaml. If field_name is defined,
# then the codegen would generate code to return namedtuple. Otherwise,
# it would just return tuple.
ReturnType = TypedDict('ReturnType', {
'name': str,
# See Note [field_name versus name]
'field_name': str,
'type': str,
'dynamic_type': str,
}, total=False)
ReturnDecl = TypedDict('ReturnDecl', {
'kind': str,
'type': str,
'arguments': List[int],
}, total=False)
# Represents a buffer in nn.yaml
NNBuffer = TypedDict('NNBuffer', {
'name': str,
})
FunctionOption = TypedDict('FunctionOption', {
'actuals': List[str],
'api_name': str,
'arguments': List[THFormal],
'aten_custom_call': str,
'aten_dense_sparse': bool,
'backend_type_pairs': List[Tuple[str, str]],
'backends': List[str],
'broadcast_actuals': List[str],
'broadcast_function': str,
'broadcast_modified_actuals': List[str],
'broadcast_returns': List[str],
'buffers': List[NNBuffer],
# cimpls is really a List[FunctionOption]
'cimpls': List[Any],
'cname': str,
'condition': str,
'const_mark': str,
'device_guard': bool,
'device_guard_declaration': str,
'with_gil': bool,
'cpu_half': bool,
'deprecated': bool,
# See Note [field_name versus name]
'field_name': str,
'formals_list': List[AtFormal],
'formals_with_defaults': List[str],
'formals': List[str],
'formals_types': List[str],
'inferred_type': str,
'inplace': bool,
'matches_jit_signature': bool,
# This controls whether or not we generate the interface in Type or
# TypeExtendedInterface
'extended_method': bool,
'method_actuals': List[str],
'method_formals_with_defaults': List[str],
'method_formals': List[str],
'method_prefix_derived': str,
'mode': str,
'python_module': str,
'name': str,
'native_actuals': List[str],
'native_type_method_dispatch': str,
# options should be List[FunctionOption]
'options': Any,
'schema_string': str,
'requires_tensor': bool,
'return_call': str,
'return_type': str,
'return': ReturnDecl,
'returns': List[ReturnType],
'scalar_check': str,
# schema used for extension backend operator registration
'schema': str,
'sparse': bool,
'type_definition_body': List[str],
'type_method_actuals': List[str],
'type_method_definition_dispatch': str,
'type_method_formals': List[str],
'variants': str,
'when_spares_dispatch': str,
'when_sparse_dispatch': str,
'with_gil': bool,
'zero_dim_dispatch_when_scalar': str,
'zero_dim_tensor_only': bool,
})
OutputDeclaration = NamedTuple('OutputDeclaration', [
('name', str),
('matches_jit_signature', bool),
('schema_string', str),
('method_prefix_derived', str),
('arguments', List[AtFormal]),
('method_of', List[str]),
('mode', str),
('python_module', str),
('buffers', Optional[List[str]]),
('returns', List[ReturnType]),
('inplace', bool),
('is_factory_method', bool),
('abstract', bool),
('requires_tensor', bool),
('device_guard', bool),
('with_gil', bool),
('deprecated', bool),
])
def device_guard(option, formals, dispatch_options, dispatch_tensor):
# For factory methods the `DeviceGuard` is already in the template.
if option.get('device_guard', True):
if dispatch_options:
return 'const DeviceGuard device_guard({}.device());'.format(dispatch_options['name'])
if dispatch_tensor:
return 'const OptionalDeviceGuard device_guard(device_of({}));'.format(dispatch_tensor)
return '// DeviceGuard omitted'
def is_real_argument_to_wrapper(argument):
# type: (THFormal) -> bool
return not argument.get('output', False) and\
argument['type'] != 'CONSTANT' and\
argument['type'] != 'argument'
def is_mutable_formal_argument(argument, option):
# type: (THFormal, FunctionOption) -> bool
return argument.get('output') or option['inplace'] and argument['name'] == 'self'
def check_methods_do_not_start_with_underscore(name, is_method):
if name in {'_values', '_indices', '_nnz', '_dimI', '_dimV', '_coalesced_'}:
return
if is_method and name.startswith('_') and not name.startswith('__') and not name.startswith('_th_'):
message = "Function '{}' starts with a single underscore and is ".format(name)
message += "configured to have a method on Tensor. Functions that start with "
message += " a single underscore should only be functions in the at:: "
message += "namespace and not methods on Tensor!"
raise RuntimeError(message)
def to_return_type(arg, option):
# type: (THFormal, FunctionOption) -> ReturnType
t = arg['type']
rt = TYPE_RETURN.get(t, t)
if rt == 'Tensor' and not arg.get('allocate'):
rt = rt + ' &'
if not is_mutable_formal_argument(arg, option):
rt = 'const ' + rt
return {
'name': arg['name'],
'type': rt,
'dynamic_type': DYNAMIC_TYPE.get(arg['type'], arg['type']),
}
def create_generic(top_env, declarations):
# type: (TopEnvironment, List[FunctionOption]) -> List[OutputDeclaration]
# translates defaults from cwrap types to C++ values
def translate_default(argument, type_str, default):
# type: (THFormal, str, Any) -> Any
if default is None:
# cause the default constructor for the object to run
return '{}'
if 'if_true' in argument:
return argument['default'] == argument['if_true']
for pattern, replacement in HEADER_CONSTANT_REPLACEMENTS:
default = re.sub(pattern, replacement, str(default))
if type_str in {'Scalar', 'int64_t', 'double'}:
try:
return int(default)
except Exception:
try:
return float(default)
except Exception:
return default
elif type_str == 'bool':
assert default.lower() in ['true', 'false']
return default.lower() == 'true'
else:
return default
# change from THTensor* to Tensor & so we get how it will appear
# in the aten argument list...
def translate_formal(argument, option):
# type: (THFormal, FunctionOption) -> AtFormal
type_str = TYPE_FORMAL_GENERIC.get(argument['type'], argument['type'])
if type_str == 'Tensor &' and not is_mutable_formal_argument(argument, option):
type_str = 'const ' + type_str
translated = {
'name': argument['name'],
'type': type_str,
'dynamic_type': DYNAMIC_TYPE.get(argument['type'], argument['type']),
} # type: AtFormal
if 'kwarg_only' in argument:
translated['kwarg_only'] = argument['kwarg_only']
if 'default' in argument:
default = translate_default(argument, type_str, argument['default'])
translated['default'] = default
translated['default_init'] = argument.get('default_init', default)
if argument.get('output'):
translated['output'] = True
if argument.get('size'):
translated['size'] = argument['size']
if argument.get('is_nullable') is not None:
translated['is_nullable'] = argument['is_nullable']
return translated
def get_formals(option, include_constants=False):
# type: (FunctionOption, bool) -> List[AtFormal]
seen = set() # type: Set[str]
pos_args = [] # type: List[THFormal]
kwd_args = [] # type: List[THFormal]
def insert(argument):
# type: (THFormal) -> None
if argument['name'] not in seen:
seen.add(argument['name'])
if argument.get('kwarg_only', False):
kwd_args.append(argument)
else:
pos_args.append(argument)
def has_output_mask(argument):
# type: (THFormal) -> bool
return argument.get('allocate', False) and argument.get('mask', False)
for argument in option['arguments']:
if argument.get('output') and not argument.get('allocate', False):
insert(argument)
for argument in option['arguments']:
if argument['type'] == 'THSTensor*':
# only enable for a subset of Dense/Sparse ops
if not (option.get('aten_dense_sparse', False)):
raise NYIError("Sparse Tensor")
if include_constants and argument['type'] == 'CONSTANT':
insert(argument)
elif is_real_argument_to_wrapper(argument):
insert(argument)
if any(has_output_mask(arg) for arg in option['arguments']):
mask_size = sum(has_output_mask(arg) for arg in option['arguments'])
insert({
'name': 'output_mask',
# NB: Lack of space in comma works around parsing
# problem in gen_variable_type.py
'type': 'std::array<bool,{}>'.format(mask_size),
'default': '{{' + ', '.join(['true'] * mask_size) + '}}',
})
result = pos_args + kwd_args
return [translate_formal(argument, option) for argument in result]
def get_return_types(option):
# type: (FunctionOption) -> List[ReturnType]
ret = option['return']
if ret['kind'] == 'arguments':
argument_indices = ret['arguments']
if len(argument_indices) == 1:
the_arg = option['arguments'][argument_indices[0]]
return [to_return_type(the_arg, option)]
else:
return [to_return_type(option['arguments'][idx], option)
for idx in argument_indices]
elif ret['kind'] == 'type':
return [{
'type': TYPE_RETURN.get(ret['type'], ret['type']),
'dynamic_type': DYNAMIC_TYPE.get(ret['type'], ret['type']),
}]
else:
raise Exception("format_return_type")
def format_return_type(return_types):
# type: (List[ReturnType]) -> str
if len(return_types) == 1:
return return_types[0]['type']
return "std::tuple<{}>".format(','.join(r['type'] for r in return_types))
def find_dispatch_tensor(formals):
# type: (List[AtFormal]) -> Optional[str]
# dispatch to self if it's a parameter
for formal in formals:
if formal['name'] == 'self' and formal['dynamic_type'] == 'Tensor' and not formal.get('is_nullable', False):
return formal['name']
# otherwise dispatch to the first Tensor or TensorList
for formal in formals:
if 'TensorList' == formal['dynamic_type'] or formal['dynamic_type'] == 'Tensor' and \
not formal.get('is_nullable', False):
return formal['name']
return None
def format_formal(f):
# type: (AtFormal) -> str
return '{} {}'.format(f['type'], f['name'])
def formal_with_default(f):
# type: (AtFormal) -> str
s = format_formal(f)
v = f.get('default')
if v is None:
return s
if isinstance(v, bool):
v = str(v).lower()
return '{}={}'.format(s, v)
def get_broadcast_argument(option):
# type: (FunctionOption) -> Optional[THFormal]
for argument in option['arguments']:
if argument.get('broadcast'):
return argument
return None
def get_broadcast_actuals(broadcast_arg, broadcast_inplace, broadcast_dims):
# type: (THFormal, bool, bool) -> List[str]
# Note: broadcast_dims can change type...
# return the actuals that will be passed to the broadcast function.
# 1) in the common case, this is the broadcasted argument (e.g. "self") followed by the tensors
# that it is broadcasted against (comma-separated) (e.g. "self, tensor1, tensor2").
# 2) in the broadcast_dims case, this is the broadcasted argument (e.g. "self") followed by the sizes
# it is broadcasted to (as an initializer list), so e.g. the specification
# "mat1.dim0,mat2.dim1" gets transformed to "self, {mat1.size(0),mat2.size(1)}"
if not broadcast_dims:
broadcast_actuals = [broadcast_arg['name']] + broadcast_arg['broadcast'].split()[0].split(",")
else:
broadcast_dims_spec = broadcast_arg['broadcast'].split()[1].split(':')[1].split(',')
# generate size call for each dimension
broadcast_dims = ([x.split('.')[0] + '.size(' + x.split('.')[1].replace('dim', '') + ')' # type: ignore
for x in broadcast_dims_spec])
broadcast_dims_init_list = '{' + ','.join(broadcast_dims) + '}' # type: ignore
broadcast_actuals = [broadcast_arg['name'], broadcast_dims_init_list]
return broadcast_actuals
def emit_nn_body(option):
# type: (FunctionOption) -> Union[str, List[str]]
# Concrete definition on Type.cpp for NN functions. Delegates to the
# xxx_forward variant variant after creating any necessary buffers.
actuals = option['actuals']
base_name = option['name'][:-1] if option['inplace'] else option['name']
fwd_name = option['api_name'].replace(base_name, base_name + '_forward')
if len(option['buffers']) == 0:
return 'return {}({});'.format(fwd_name, ', '.join(actuals))
body = [] # type: List[str]
if option['api_name'].endswith('_out'):
# _out variants must create buffers and insert them in the
# arguments list between output and input arguments
for buffer in option['buffers']:
body.append('Tensor {} = at::empty({{0}}, this->options());'.format(buffer['name']))
actuals = [arg['name'] for arg in option['arguments'] if arg.get('output')]
actuals += [buffer['name'] for buffer in option['buffers']]
actuals += [arg['name'] for arg in option['arguments'] if not arg.get('output')]
body.append('return std::get<0>({}({}));'.format(fwd_name, ', '.join(actuals)))
return body
def process_option(option, output_options):
# type: (FunctionOption, List[OutputDeclaration]) -> None
option['inplace'] = re.search(
'(^__i|[^_]_$)', option['api_name']) is not None
# print(yaml.dump(option))
formals = get_formals(option)
option['formals_list'] = formals
option['formals'] = [format_formal(f) for f in formals]
option['formals_with_defaults'] = [formal_with_default(f) for f in formals]
option['returns'] = get_return_types(option)
option['return_type'] = format_return_type(option['returns'])
option['return_call'] = 'return ' if option['return_type'] != 'void' else ''
option['actuals'] = [f['name'] for f in formals]
option['method_formals'] = [format_formal(f) for f in formals
if f['name'] != 'self']
option['method_formals_with_defaults'] = (
[formal_with_default(f) for f in formals if f['name'] != 'self'])
option['method_actuals'] = [
f['name'] if f['name'] != 'self' else '*this' for f in formals]
# There are no cases where these differ, but they do in native_functions
option['type_method_formals'] = option['formals']
option['type_method_actuals'] = option['actuals']
option['const_mark'] = '' if option['inplace'] else ' const'
assert 'method' not in option['variants'], 'TH functions cannot be methods'
is_function = 'function' in option['variants']
dispatch_tensor = find_dispatch_tensor(formals)
is_namespace_function = is_function and dispatch_tensor is not None
broadcast_arg = get_broadcast_argument(option)
# "s_" for "same size".
option['method_prefix_derived'] = '' if broadcast_arg is None else 's_'
if option['mode'] == 'TH':
option['device_guard'] = False
option['device_guard_declaration'] = device_guard(option, formals, False, dispatch_tensor)
env = nested_dict(option, top_env)
mode = option['mode']
abstract = True
assert option['extended_method'], 'Expected legacy operator to be an extended method'
if mode == 'NN' and option.get('cimpls') is None:
# NN function with no _forward/_backward suffix don't have cimpls.
# They call the _forward function and discard any buffer returns
abstract = False
top_env['pure_virtual_extended_type_method_declarations'].append(
PURE_VIRTUAL_TYPE_METHOD_DECLARATION.substitute(env))
top_env['type_method_declarations'].append(
TYPE_METHOD_DECLARATION_CONCRETE.substitute(env))
body = emit_nn_body(option)
top_env['type_method_definitions'].append(
TYPE_METHOD_DEFINITION_CONCRETE.substitute(
env, type_definition_body=body))
elif broadcast_arg is None:
top_env['pure_virtual_extended_type_method_declarations'].append(
PURE_VIRTUAL_TYPE_METHOD_DECLARATION.substitute(env))
top_env['type_method_declarations'].append(
TYPE_METHOD_DECLARATION_ABSTRACT.substitute(env))
top_env['type_method_definitions'].append(
TYPE_METHOD_DEFINITION_ABSTRACT.substitute(env))
else:
top_env['pure_virtual_extended_type_method_declarations'].append(
PURE_VIRTUAL_TYPE_METHOD_DECLARATION.substitute(env))
top_env['pure_virtual_extended_type_method_declarations'].append(
PURE_VIRTUAL_TYPE_METHOD_DECLARATION_BROADCAST.substitute(env))
top_env['type_method_declarations'].append(
TYPE_METHOD_DECLARATION_BROADCAST.substitute(env))
top_env['type_method_declarations'].append(
TYPE_METHOD_DECLARATION_ABSTRACT.substitute(env))
top_env['type_method_definitions'].append(
TYPE_METHOD_DEFINITION_ABSTRACT.substitute(env))
broadcast_inplace = 'inplace' in broadcast_arg['broadcast']
broadcast_dims = 'dims:' in broadcast_arg['broadcast']
option['broadcast_actuals'] = get_broadcast_actuals(broadcast_arg, broadcast_inplace, broadcast_dims)
if not broadcast_dims:
option['broadcast_returns'] = (["b_" + x for x in option['broadcast_actuals']
if x != broadcast_arg['name'] or not broadcast_inplace])
else:
option['broadcast_returns'] = ["b_" + broadcast_arg['name']]
option['broadcast_function'] = 'expand_' + ('inplace' if broadcast_inplace
else 'size' if broadcast_dims else 'outplace')
option['broadcast_modified_actuals'] = ['b_' + y if 'b_' + y in option['broadcast_returns'] else y
for y in option['actuals']]
top_env['type_method_definitions'].append(
TYPE_METHOD_DEFINITION_BROADCAST.substitute(env))
method_of = ['Type']
if is_namespace_function:
option['inferred_type'] = 'detail::infer_type({})'.format(dispatch_tensor)
top_env['function_declarations'].append(
FUNCTION_DECLARATION.substitute(env))
top_env['function_definitions'].append(
FUNCTION_DEFINITION.substitute(env))
method_of.append('namespace')
buffer_names = [buffer['name'] for buffer in option.get('buffers', [])]
output_options.append(OutputDeclaration(
name=option['api_name'],
matches_jit_signature=option['matches_jit_signature'],
schema_string=option['schema_string'],
method_prefix_derived=option['method_prefix_derived'],
arguments=formals,
method_of=method_of,
mode=mode,
python_module=option.get('python_module', ''),
buffers=buffer_names,
returns=option['returns'],
inplace=option['inplace'],
is_factory_method=False,
# See Note [Abstract ATen methods]
abstract=abstract,
requires_tensor=option.get('requires_tensor', False),
device_guard=option.get('device_guard', True),
with_gil=option.get('with_gil', False),
deprecated=option.get('deprecated', False)
))
def native_get_formals(option, include_constants=False):
# type: (FunctionOption, bool) -> List[AtFormal]
seen = set() # type: Set[str]
pos_args = []
kwd_args = []
def insert(argument):
# type: (AtFormal) -> None
if argument['name'] not in seen:
seen.add(argument['name'])
if argument.get('kwarg_only', False):
kwd_args.append(argument)
else:
pos_args.append(argument)
for argument in option['arguments']:
insert(argument)
# not clear we need dynamic_type translation as we can specify the correct type
# directly in native functions
def add_dynamic_type(argument, option):
# type: (AtFormal, FunctionOption) -> AtFormal
argument['dynamic_type'] = NATIVE_DYNAMIC_TYPE.get(argument['type'], argument['type'])
return argument
result = pos_args + kwd_args
result = [add_dynamic_type(argument, option) for argument in result]
# ensure we get reference-type formals when appropriate
def native_translate_formals(argument, option):
# type: (AtFormal, FunctionOption) -> AtFormal
def translate_map(const):
# type: (bool) -> Dict[str, str]
return {
'Tensor': 'const Tensor &' if const else 'Tensor &',
'BoolTensor': 'const Tensor &' if const else 'Tensor &',
'IndexTensor': 'const Tensor &' if const else 'Tensor &',
'Type': 'const Type &' if const else 'Type &',
'TensorOptions': 'const TensorOptions &' if const else 'TensorOptions &',
'TensorList': 'TensorList',
}
if argument.get('is_nullable') and argument['type'] not in translate_map(False).keys():
argument['type'] = "c10::optional<{}>".format(argument['type'])
if (option['inplace'] and argument['name'] == 'self') or argument.get('output', False):
argument['type'] = translate_map(False).get(argument['type'], argument['type'])
else:
argument['type'] = translate_map(True).get(argument['type'], argument['type'])
return argument
result = [native_translate_formals(argument, option) for argument in result]
return result
# this can return multiple return types in a list, e.g. ['Tensor', 'Tensor']
def native_get_return_types(option):
# type: (FunctionOption) -> List[ReturnType]
ret = option['return']
return_types = [] # List[ReturnType]
for t_raw in ret:
# See Note [field_name versus name]
field_name = None
if isinstance(t_raw, string_type):
t = t_raw
name = None