forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
buckbuild.bzl
2149 lines (2020 loc) · 79.8 KB
/
buckbuild.bzl
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
# NOTE: This file is shared by internal and OSS BUCK build.
# These load paths point to different files in internal and OSS environment
load("@bazel_skylib//lib:paths.bzl", "paths")
load("//tools/build_defs:fb_native_wrapper.bzl", "fb_native")
load("//tools/build_defs:fb_xplat_cxx_library.bzl", "fb_xplat_cxx_library")
load("//tools/build_defs:fb_xplat_genrule.bzl", "fb_xplat_genrule")
load("//tools/build_defs:fbsource_utils.bzl", "is_arvr_mode")
load("//tools/build_defs:glob_defs.bzl", "subdir_glob")
load("//tools/build_defs:platform_defs.bzl", "APPLETVOS", "IOS", "MACOSX")
load("//tools/build_defs:type_defs.bzl", "is_list", "is_string")
load("//tools/build_defs/android:build_mode_defs.bzl", is_production_build_android = "is_production_build")
load("//tools/build_defs/apple:build_mode_defs.bzl", is_production_build_ios = "is_production_build")
load("//tools/build_defs/windows:windows_flag_map.bzl", "windows_convert_gcc_clang_flags")
load(
":build_variables.bzl",
"aten_cpu_source_list",
"aten_native_source_list",
"core_sources_common",
"core_sources_full_mobile_no_backend_interface",
"core_trainer_sources",
"jit_core_headers",
"jit_core_sources",
"libtorch_profiler_sources",
)
load(
":pt_ops.bzl",
"USED_PT_BACKENDS",
)
load(
":pt_template_srcs.bzl",
"METAL_MASKRCNN_SOURCE_LIST",
"METAL_SOURCE_LIST",
"TEMPLATE_MASKRCNN_SOURCE_LIST",
"TEMPLATE_SOURCE_LIST",
"aten_ufunc_generated_all_cpu_sources",
"get_gen_oplist_outs",
"get_generate_code_bin_outs",
"get_metal_registration_files_outs",
"get_metal_registration_files_outs_windows",
"get_metal_source_dict",
"get_template_registration_file_rules",
"get_template_registration_files_outs",
"get_template_source_dict",
)
load(
":ufunc_defs.bzl",
"aten_ufunc_generated_cpu_kernel_sources",
"aten_ufunc_generated_cpu_sources",
"aten_ufunc_generated_cuda_sources",
)
def read_bool(section, field, default, required = True):
# @lint-ignore BUCKRESTRICTEDSYNTAX
val = read_config(section, field)
if val != None:
if val in ["true", "True", "1"]:
return True
elif val in ["false", "False", "0"]:
return False
else:
fail(
"`{}:{}`: must be one of (0, 1, true, false, True, False), but was {}".format(section, field, val),
)
elif default != None:
return default
elif not required:
return None
else:
fail("`{}:{}`: no value set".format(section, field))
def _is_build_mode_dev():
if is_production_build_android():
# Android Prod builds
return False
if is_production_build_ios():
# iOS Prod builds
return False
return True
def _get_enable_lightweight_dispatch():
return read_bool("pt", "enable_lightweight_dispatch", False)
def _get_enable_record_kernel_dtype():
return read_bool("pt", "enable_record_kernel_dtype", False)
def get_enable_mobile_dispatch_keys_trimming():
return read_bool("pt", "enable_mobile_dispatch_keys_trimming", False)
def get_disable_per_op_profiling():
return read_bool("pt", "disable_per_op_profiling", True)
def get_strip_error_messages():
if IS_OSS:
return True # always strip in OSS CI to expose potential issues
return read_bool("pt", "strip_error_messages", not _is_build_mode_dev())
def get_enable_eager_symbolication():
return read_bool("pt", "enable_eager_symbolication", default = False, required = False)
def get_static_dispatch_backend():
static_dispatch_backend = native.read_config("pt", "static_dispatch_backend", None)
if static_dispatch_backend == None:
return []
return static_dispatch_backend.split(";")
# @lint-ignore BUCKRESTRICTEDSYNTAX
IS_OSS = read_config("pt", "is_oss", "0") == "1" # True for OSS BUCK build, and False for internal BUCK build
NOT_OSS = not IS_OSS
# for targets in caffe2 root path
ROOT = "//" if IS_OSS else "//xplat/caffe2"
# for targets in subfolders
ROOT_PATH = "//" if IS_OSS else "//xplat/caffe2/"
C10 = "//c10:c10" if IS_OSS else "//xplat/caffe2/c10:c10"
# a dictionary maps third party library name to fbsource and oss target
THIRD_PARTY_LIBS = {
"FP16": ["//xplat/third-party/FP16:FP16", "//third_party:FP16"],
"FXdiv": ["//xplat/third-party/FXdiv:FXdiv", "//third_party:FXdiv"],
"XNNPACK": ["//xplat/third-party/XNNPACK:XNNPACK", "//third_party:XNNPACK"],
"clog": ["//xplat/third-party/clog:clog", "//third_party:clog"],
"cpuinfo": ["//third-party/cpuinfo:cpuinfo", "//third_party:cpuinfo"],
"flatbuffers-api": ["//third-party/flatbuffers/fbsource_namespace:flatbuffers-api", "//third_party:flatbuffers-api"],
"flatc": ["//third-party/flatbuffers/fbsource_namespace:flatc", "//third_party:flatc"],
"fmt": ["//third-party/fmt:fmt", "//third_party:fmt"],
"glog": ["//third-party/glog:glog", "//third_party:glog"],
"gmock": ["//xplat/third-party/gmock:gtest", "//third_party:gmock"],
"gtest": ["//xplat/third-party/gmock:gmock", "//third_party:gtest"],
"kineto": ["//xplat/kineto/libkineto:libkineto", "//third_party:libkineto"],
"libkineto_headers": ["//xplat/kineto/libkineto:libkineto_headers", "//third_party:libkineto_headers"],
"omp": ["//xplat/third-party/linker_lib:omp", "//third_party:no-op"],
"pocketfft": ["//third-party/pocket_fft:pocketfft", "//third_party:pocketfft_header"],
"psimd": ["//xplat/third-party/psimd:psimd", "//third_party:psimd"],
"pthreadpool": ["//xplat/third-party/pthreadpool:pthreadpool", "//third_party:pthreadpool"],
"pthreadpool_header": ["//xplat/third-party/pthreadpool:pthreadpool_header", "//third_party:pthreadpool_header"],
"pyyaml": ["//third-party/pyyaml:pyyaml", "//third_party:pyyaml"],
"rt": ["//xplat/third-party/linker_lib:rt", "//third_party:rt"],
"ruy": ["//third-party/ruy:ruy_xplat_lib", "//third_party:ruy_lib"],
"typing-extensions": ["//third-party/typing-extensions:typing-extensions", "//third_party:typing-extensions"],
}
def third_party(name):
if name not in THIRD_PARTY_LIBS:
fail("Cannot find third party library " + name + ", please register it in THIRD_PARTY_LIBS first!")
return THIRD_PARTY_LIBS[name][1] if IS_OSS else THIRD_PARTY_LIBS[name][0]
def get_pt_compiler_flags():
return select({
"DEFAULT": _PT_COMPILER_FLAGS + [
"-std=gnu++17", #to accomodate for eigen
],
"ovr_config//compiler:cl": windows_convert_gcc_clang_flags(_PT_COMPILER_FLAGS),
})
_PT_COMPILER_FLAGS = [
"-fexceptions",
"-frtti",
"-Os",
"-Wno-unknown-pragmas",
"-Wno-write-strings",
"-Wno-unused-variable",
"-Wno-unused-function",
"-Wno-deprecated-declarations",
"-Wno-shadow",
"-Wno-global-constructors",
"-Wno-missing-prototypes",
]
ATEN_COMPILER_FLAGS = [
"-fexceptions",
"-frtti",
"-fPIC",
"-Os",
"-Wno-absolute-value",
"-Wno-deprecated-declarations",
"-Wno-macro-redefined",
"-Wno-tautological-constant-out-of-range-compare",
"-Wno-unknown-pragmas",
"-Wno-unknown-warning-option",
"-Wno-unused-function",
"-Wno-unused-variable",
"-Wno-pass-failed",
"-Wno-shadow",
]
def get_aten_compiler_flags():
return ATEN_COMPILER_FLAGS
_COMMON_PREPROCESSOR_FLAGS = [
"-DC10_MOBILE",
"-DNO_EXPORT",
] + (
["-DC10_MOBILE_TRIM_DISPATCH_KEYS"] if get_enable_mobile_dispatch_keys_trimming() else []
) + (
["-DSTRIP_ERROR_MESSAGES"] if get_strip_error_messages() else []
)
def get_aten_preprocessor_flags():
# read_config is not allowed outside of function in Starlark
ATEN_PREPROCESSOR_FLAGS = _COMMON_PREPROCESSOR_FLAGS + [
"-DCPU_CAPABILITY_DEFAULT",
"-DCPU_CAPABILITY=DEFAULT",
"-DCAFFE2_USE_LITE_PROTO",
"-DATEN_CUDNN_ENABLED_FBXPLAT=0",
"-DATEN_MKLDNN_ENABLED_FBXPLAT=0",
"-DATEN_NNPACK_ENABLED_FBXPLAT=0",
"-DATEN_MKL_ENABLED_FBXPLAT=0",
"-DATEN_MKL_SEQUENTIAL_FBXPLAT=0",
"-DUSE_PYTORCH_METAL",
"-DUSE_PYTORCH_QNNPACK",
"-DUSE_XNNPACK",
"-DPYTORCH_QNNPACK_RUNTIME_QUANTIZATION",
"-DAT_PARALLEL_OPENMP_FBXPLAT=0",
"-DAT_PARALLEL_NATIVE_FBXPLAT=1",
"-DAT_PARALLEL_NATIVE_TBB_FBXPLAT=0",
"-DUSE_LAPACK_FBXPLAT=0",
"-DAT_BLAS_F2C_FBXPLAT=0",
"-DAT_BLAS_USE_CBLAS_DOT_FBXPLAT=0",
"-DUSE_RUY_QMATMUL",
]
if get_disable_per_op_profiling():
ATEN_PREPROCESSOR_FLAGS.append("-DPYTORCH_DISABLE_PER_OP_PROFILING")
if _get_enable_record_kernel_dtype():
ATEN_PREPROCESSOR_FLAGS.append("-DENABLE_RECORD_KERNEL_FUNCTION_DTYPE")
return ATEN_PREPROCESSOR_FLAGS
def get_pt_preprocessor_flags():
# read_config is not allowed outside of function in Starlark
PT_PREPROCESSOR_FLAGS = _COMMON_PREPROCESSOR_FLAGS + [
"-D_THP_CORE",
"-DUSE_SCALARS",
"-DNO_CUDNN_DESTROY_HANDLE",
"-DBUILD_CAFFE2",
]
if _is_build_mode_dev():
PT_PREPROCESSOR_FLAGS.append("-DENABLE_PYTORCH_NON_PRODUCTION_BUILDS")
return PT_PREPROCESSOR_FLAGS
# This needs to be kept in sync with https://github.com/pytorch/pytorch/blob/release/1.9/torchgen/gen.py#L892
PT_BACKEND_HEADERS = [
"CPU",
"CUDA",
"CompositeExplicitAutograd",
"CompositeExplicitAutogradNonFunctional",
"CompositeImplicitAutograd",
"Meta",
]
def get_aten_static_dispatch_backend_headers(existing_headers):
static_backends = get_static_dispatch_backend()
for backend in static_backends:
if backend != "CPU":
existing_headers["{}Functions.h".format(backend)] = ":gen_aten[{}Functions.h]".format(backend)
existing_headers["{}Functions_inl.h".format(backend)] = ":gen_aten[{}Functions_inl.h]".format(backend)
return existing_headers
def get_aten_codegen_extra_params(backends):
extra_params = {
"force_schema_registration": True,
}
static_backends = get_static_dispatch_backend()
if static_backends:
extra_params["static_dispatch_backend"] = static_backends
extra_params["enabled_backends"] = static_backends
else:
extra_params["enabled_backends"] = backends
return extra_params
def get_jit_codegen_params():
return []
def get_unboxing_generated_files():
srcs = []
if _get_enable_lightweight_dispatch():
srcs = [
"UnboxingFunctions.h",
"UnboxingFunctions_0.cpp",
"UnboxingFunctions_1.cpp",
"UnboxingFunctions_2.cpp",
"UnboxingFunctions_3.cpp",
"UnboxingFunctions_4.cpp",
"RegisterCodegenUnboxedKernels_0.cpp",
"RegisterCodegenUnboxedKernels_1.cpp",
"RegisterCodegenUnboxedKernels_2.cpp",
"RegisterCodegenUnboxedKernels_3.cpp",
"RegisterCodegenUnboxedKernels_4.cpp",
"RegisterCodegenUnboxedKernels_5.cpp",
"RegisterCodegenUnboxedKernels_6.cpp",
"RegisterCodegenUnboxedKernels_7.cpp",
"RegisterCodegenUnboxedKernels_8.cpp",
"RegisterCodegenUnboxedKernels_9.cpp",
]
res = {}
for file_name in srcs:
res[file_name] = [file_name]
return res
def get_aten_generated_files(enabled_backends):
# NB: RegisterMeta counts as an optionally enabled backend,
# and is intentionally omitted from here
src_files = [
"RegisterBackendSelect.cpp",
"RegisterCompositeImplicitAutograd.cpp",
"RegisterCompositeExplicitAutograd.cpp",
"RegisterCompositeExplicitAutogradNonFunctional.cpp",
"CompositeViewCopyKernels.cpp",
"RegisterSchema.cpp",
"Declarations.yaml",
"Functions.cpp",
"Functions.h",
"RedispatchFunctions.h",
"NativeFunctions.h",
"NativeMetaFunctions.h",
"MethodOperators.h",
"FunctionalInverses.h",
"Operators.h",
"Operators_0.cpp",
"Operators_1.cpp",
"Operators_2.cpp",
"Operators_3.cpp",
"Operators_4.cpp",
"CompositeImplicitAutogradFunctions.h",
"CompositeImplicitAutogradFunctions_inl.h",
"CompositeExplicitAutogradFunctions.h",
"CompositeExplicitAutogradFunctions_inl.h",
"CompositeExplicitAutogradNonFunctionalFunctions.h",
"CompositeExplicitAutogradNonFunctionalFunctions_inl.h",
"core/ATenOpList.cpp",
"core/TensorBody.h",
"core/TensorMethods.cpp",
"core/aten_interned_strings.h",
"core/enum_tag.h",
] + get_aten_derived_type_srcs(enabled_backends)
# This is tiresome. A better strategy would be to unconditionally
# generate these files, and then only actually COMPILE them depended
# on the generated set. C'est la vie...
if "CPU" in enabled_backends:
src_files.extend(aten_ufunc_generated_cpu_sources())
src_files.extend(aten_ufunc_generated_cpu_kernel_sources())
if "CUDA" in enabled_backends:
# Cannot unconditionally include this, because in the Edge selective
# build CUDA is not enabled and thus the ufunc codegen for CUDA gets
# skipped
src_files.extend(aten_ufunc_generated_cuda_sources())
res = {}
for file_name in src_files:
res[file_name] = [file_name]
return res
def get_aten_derived_type_src_rules(aten_rule_name, enabled_backends):
return [
":{}[{}]".format(aten_rule_name, "Register" + backend + ".cpp")
for backend in enabled_backends
]
def get_aten_selective_cpp_rules(aten_rule_name, enabled_backends):
return [
":{}[{}]".format(aten_rule_name, f)
for f in ["RegisterCompositeImplicitAutograd.cpp", "RegisterCompositeExplicitAutograd.cpp", "RegisterCompositeExplicitAutogradNonFunctional.cpp", "RegisterSchema.cpp", "RegisterBackendSelect.cpp", "CompositeViewCopyKernels.cpp"]
] + get_aten_derived_type_src_rules(aten_rule_name, enabled_backends)
def get_aten_derived_type_srcs(enabled_backends):
return [
"Register" + derived_type + ".cpp"
for derived_type in enabled_backends
] + [
derived_type + "Functions.h"
for derived_type in enabled_backends
if derived_type in PT_BACKEND_HEADERS or derived_type in get_static_dispatch_backend()
] + [
derived_type + "Functions_inl.h"
for derived_type in enabled_backends
if derived_type in PT_BACKEND_HEADERS or derived_type in get_static_dispatch_backend()
]
def gen_aten_files(
name,
extra_flags = {},
visibility = [],
compatible_with = [],
apple_sdks = None):
extra_params = []
force_schema_registration = extra_flags.get("force_schema_registration", False)
op_registration_allowlist = extra_flags.get("op_registration_allowlist", None)
op_selection_yaml_path = extra_flags.get("op_selection_yaml_path", None)
enabled_backends = extra_flags.get("enabled_backends", None)
static_dispatch_backend = extra_flags.get("static_dispatch_backend", None)
if force_schema_registration:
extra_params.append("--force_schema_registration")
if op_registration_allowlist != None and is_string(op_registration_allowlist):
extra_params.append("--op_registration_whitelist")
extra_params.append(op_registration_allowlist)
if op_selection_yaml_path != None and is_string(op_selection_yaml_path):
extra_params.append("--op_selection_yaml_path")
extra_params.append(op_selection_yaml_path)
if enabled_backends != None and is_list(enabled_backends):
extra_params.append("--backend_whitelist")
extra_params.extend(enabled_backends)
if _get_enable_lightweight_dispatch():
extra_params.append("--skip_dispatcher_op_registration")
if static_dispatch_backend:
extra_params.append("--static_dispatch_backend")
extra_params.extend(static_dispatch_backend)
backends = static_dispatch_backend
else:
backends = enabled_backends
fb_xplat_genrule(
name = name,
default_outs = ["."],
outs = get_aten_generated_files(backends),
cmd = "$(exe {}torchgen:gen) ".format(ROOT_PATH) + " ".join([
"--source-path $(location {}:aten_src_path)/aten/src/ATen".format(ROOT),
"--install_dir $OUT",
] + extra_params),
visibility = visibility,
compatible_with = compatible_with,
apple_sdks = apple_sdks,
)
def gen_aten_unboxing_files(
genrule_name,
extra_flags = {}):
extra_params = []
op_selection_yaml_path = extra_flags.get("op_selection_yaml_path", None)
op_registration_allowlist = extra_flags.get("op_registration_allowlist", None)
if op_selection_yaml_path != None and is_string(op_selection_yaml_path):
extra_params.append("--op_selection_yaml_path")
extra_params.append(op_selection_yaml_path)
if op_registration_allowlist != None and is_string(op_registration_allowlist):
extra_params.append("--op_registration_allowlist")
extra_params.append(op_registration_allowlist)
fb_xplat_genrule(
name = genrule_name,
default_outs = ["."],
outs = get_unboxing_generated_files(),
cmd = "$(exe {}tools:gen_unboxing_bin) ".format(ROOT_PATH) + " ".join([
"--source-path $(location {}:aten_src_path)/aten/src/ATen".format(ROOT),
"--install_dir $OUT",
] + extra_params),
visibility = ["PUBLIC"],
)
def copy_template_registration_files(name, apple_sdks = None):
cmd = []
cmd_exe = []
template_source_dict = get_template_source_dict()
# Ideally, we would run one copy command for a single source directory along
# with all its child directories, but it's somewhat hard to know if a directory
# is a child of another just bu looking at the metadata (directory relative
# path) that we currently have since 1 directory could look like a parent of
# another and yet come from a different filegroup() rule.
#
for (path_prefix, file_paths) in template_source_dict.items():
cmd.append("mkdir -p $OUT/{}".format(path_prefix))
cmd_exe.append("md $OUT/{}".format(path_prefix))
# Adding *.cpp is a workaround to prevent cp from thrown an error when it
# encounters a directory (since -r was not specified). If files with an
# extension other than .cpp need to be copied, then the command below
# will not work and will need to be updated.
#
cmd.append("cp -f $(location {0}:templated_selective_build_srcs)/{1}/*.cpp $OUT/{1}/".format(ROOT, path_prefix))
cmd_exe.append("robocopy /E $(location {0}:templated_selective_build_srcs)/{1} $OUT/{1}".format(ROOT, path_prefix))
if NOT_OSS:
for file_path in TEMPLATE_MASKRCNN_SOURCE_LIST:
maskrcnn_file = "$(location //xplat/caffe2/fb/custom_ops/maskrcnn:templated_selective_build_srcs)/" + file_path
cmd.append("cp -f " + maskrcnn_file + " $OUT")
cmd_exe.append("copy " + maskrcnn_file + " $OUT")
cmd.append("mkdir -p $OUT/aten/src/ATen")
cmd_exe.append("md $OUT/aten/src/ATen")
# NB: CUDA is skipped here because this is selective build and CUDA is not
# supported for selective build
for ufunc_file in aten_ufunc_generated_all_cpu_sources("$(location " + ROOT + ":gen_aten[{}])"):
cmd.append("cp -f " + ufunc_file + " $OUT/aten/src/ATen")
cmd_exe.append("copy " + ufunc_file + " $OUT/aten/src/ATen")
if NOT_OSS:
pvd_batch_box_cox_file = "$(location //xplat/caffe2/fb/custom_ops/batch_box_cox:templated_selective_build_srcs)/register_batch_box_cox_ops.cpp"
cmd.append("cp -f " + pvd_batch_box_cox_file + " $OUT")
cmd_exe.append("copy " + pvd_batch_box_cox_file + " $OUT")
fb_xplat_genrule(
name = name,
cmd = " && ".join(cmd),
cmd_exe = "@powershell -Command " + ("; ".join(cmd_exe)),
outs = get_template_registration_files_outs(IS_OSS),
default_outs = ["."],
apple_sdks = apple_sdks,
)
def pt_operator_query_codegen(
name,
deps = [],
train = False,
enforce_traced_op_list = False,
pt_allow_forced_schema_registration = True,
compatible_with = [],
apple_sdks = None):
oplist_dir_name = name + "_pt_oplist"
# @lint-ignore BUCKLINT
fb_native.genrule(
name = oplist_dir_name,
cmd = ("$(exe {}tools:gen_oplist) ".format(ROOT_PATH) +
"--model_file_list_path $(@query_outputs 'attrfilter(labels, pt_operator_library, deps(set({deps})))') " +
("" if enforce_traced_op_list else "--allow_include_all_overloads ") +
"--output_dir $OUT ").format(deps = " ".join(["\"{}\"".format(d) for d in deps])),
outs = get_gen_oplist_outs(),
default_outs = ["."],
compatible_with = compatible_with,
)
# Aten files
aten_genrule = name + "_aten"
extra_flags = {
"enabled_backends": USED_PT_BACKENDS,
"op_selection_yaml_path": "$(location :{}[selected_operators.yaml])".format(oplist_dir_name),
}
if train and pt_allow_forced_schema_registration:
extra_flags["force_schema_registration"] = True
unboxing_genrule = name + "_unboxing"
if _get_enable_lightweight_dispatch():
gen_aten_unboxing_files(
unboxing_genrule,
extra_flags = extra_flags,
)
static_dispatch_backend = get_static_dispatch_backend()
if static_dispatch_backend:
extra_flags["static_dispatch_backend"] = static_dispatch_backend
gen_aten_files(
aten_genrule,
extra_flags = extra_flags,
compatible_with = compatible_with,
apple_sdks = apple_sdks,
)
# unboxing_wrappers files
extra_params = [
"--operators_yaml_path",
"$(location :" + oplist_dir_name + "[selected_operators.yaml])",
]
unboxing_and_autograd_genrule = name + "_unboxing_and_autograd"
gen_aten_libtorch_files(
unboxing_and_autograd_genrule,
extra_params,
compatible_with,
apple_sdks = apple_sdks,
)
# Template runtime files (prim ops, etc)
template_registration_genrule = name + "_template_registration"
copy_template_registration_files(template_registration_genrule, apple_sdks = apple_sdks)
# Files needed for metal
if NOT_OSS:
metal_genrule = name + "_metal"
copy_metal(metal_genrule, apple_sdks = apple_sdks)
srcs = get_aten_selective_cpp_rules(
aten_genrule,
static_dispatch_backend if static_dispatch_backend else USED_PT_BACKENDS,
) + get_template_registration_file_rules(template_registration_genrule, IS_OSS) + ([
":{}[autograd/generated/VariableType_0.cpp]".format(unboxing_and_autograd_genrule),
":{}[autograd/generated/VariableType_1.cpp]".format(unboxing_and_autograd_genrule),
":{}[autograd/generated/VariableType_2.cpp]".format(unboxing_and_autograd_genrule),
":{}[autograd/generated/VariableType_3.cpp]".format(unboxing_and_autograd_genrule),
":{}[autograd/generated/VariableType_4.cpp]".format(unboxing_and_autograd_genrule),
":{}[autograd/generated/ADInplaceOrViewType_0.cpp]".format(unboxing_and_autograd_genrule),
":{}[autograd/generated/ADInplaceOrViewType_1.cpp]".format(unboxing_and_autograd_genrule),
] if train else []) + ([
":{}[SupportedMobileModelsRegistration.cpp]".format(oplist_dir_name),
] if NOT_OSS else [])
headers = {
"selected_mobile_ops.h": ":{}[selected_mobile_ops.h]".format(oplist_dir_name),
}
if _get_enable_lightweight_dispatch():
srcs.extend([
":{}[UnboxingFunctions_0.cpp]".format(unboxing_genrule),
":{}[UnboxingFunctions_1.cpp]".format(unboxing_genrule),
":{}[UnboxingFunctions_2.cpp]".format(unboxing_genrule),
":{}[UnboxingFunctions_3.cpp]".format(unboxing_genrule),
":{}[UnboxingFunctions_4.cpp]".format(unboxing_genrule),
":{}[RegisterCodegenUnboxedKernels_0.cpp]".format(unboxing_genrule),
":{}[RegisterCodegenUnboxedKernels_1.cpp]".format(unboxing_genrule),
":{}[RegisterCodegenUnboxedKernels_2.cpp]".format(unboxing_genrule),
":{}[RegisterCodegenUnboxedKernels_3.cpp]".format(unboxing_genrule),
":{}[RegisterCodegenUnboxedKernels_4.cpp]".format(unboxing_genrule),
":{}[RegisterCodegenUnboxedKernels_5.cpp]".format(unboxing_genrule),
":{}[RegisterCodegenUnboxedKernels_6.cpp]".format(unboxing_genrule),
":{}[RegisterCodegenUnboxedKernels_7.cpp]".format(unboxing_genrule),
":{}[RegisterCodegenUnboxedKernels_8.cpp]".format(unboxing_genrule),
":{}[RegisterCodegenUnboxedKernels_9.cpp]".format(unboxing_genrule),
])
headers["UnboxingFunctions.h"] = ":{}[UnboxingFunctions.h]".format(unboxing_genrule)
return {"headers": headers, "srcs": srcs}
def gen_aten_libtorch_files(name, extra_params = [], compatible_with = [], apple_sdks = None):
fb_xplat_genrule(
name = name,
outs = get_generate_code_bin_outs(),
default_outs = ["."],
bash = "mkdir -p tools && " +
"$(exe {}tools:generate_code_bin) ".format(ROOT_PATH) + " ".join(
# Mobile build only needs libtorch - skip python bindings for now, except
# for ovrsource, which needs Python bindings.
(["--subset libtorch"] if not is_arvr_mode() else []) + [
"--native-functions-path $(location {}:aten_src_path)/aten/src/ATen/native/native_functions.yaml".format(ROOT),
"--tags-path $(location {}:aten_src_path)/aten/src/ATen/native/tags.yaml".format(ROOT),
"--install_dir $OUT",
] + extra_params,
),
cmd_exe = "@powershell -Command New-Item -Path tools -ItemType Directory -Force; " +
"$(exe {}tools:generate_code_bin) ".format(ROOT_PATH) + " ".join(
# Mobile build only needs libtorch - skip python bindings for now, except
# for ovrsource, which needs Python bindings.
(["--subset libtorch"] if not is_arvr_mode() else []) + [
"--native-functions-path $(location {}:aten_src_path)/aten/src/ATen/native/native_functions.yaml".format(ROOT),
"--tags-path $(location {}:aten_src_path)/aten/src/ATen/native/tags.yaml".format(ROOT),
"--install_dir $OUT",
] + extra_params,
),
compatible_with = compatible_with,
apple_sdks = apple_sdks,
)
def copy_metal(name, apple_sdks = None):
cmd = []
cmd_exe = []
metal_source_dict = get_metal_source_dict()
# Copy all source files over to bring them into the per app build
for path_prefix in sorted(metal_source_dict.keys()):
cmd.append("mkdir -p $OUT/{}".format(path_prefix))
cmd_exe.append("mkdir -Force $OUT/{0}".format(path_prefix))
# Not every directory has a mm or cpp file so '2>/dev/null || :' are tricks to suppress the error messages and codes.
cmd.append("cp -f {0}/{1}/*.mm $OUT/{1}/ 2>/dev/null || :".format("$(location //xplat/caffe2:metal_build_srcs)", path_prefix))
cmd.append("cp -f {0}/{1}/*.cpp $OUT/{1}/ 2>/dev/null || :".format("$(location //xplat/caffe2:metal_build_srcs)", path_prefix))
# Robocopy has a default success code of 1 which buck treats as failure so the echo masks that problem
cmd_exe.append("(robocopy /E /NFL /NDL /NJH /NJS {0}/{1} $OUT/{1}) || ECHO robocopy failed".format("$(location //xplat/caffe2:metal_build_srcs)", path_prefix))
# Metal custom ops currently have to be brought into selective build because they directly reference metal ops instead of
# going through the dispatcher. There is some weird issues with the genrule and these files locations on windows though, so
# for now we simply skip building them for windows where they very likely arent needed anyway.
# Metal MaskRCNN custom op
for full_path in METAL_MASKRCNN_SOURCE_LIST:
path_prefix = paths.dirname(full_path)
cmd.append("mkdir -p $OUT/{}".format(path_prefix))
cmd.append("cp -f {0}/{1}/*.mm $OUT/{1}/ 2>/dev/null || :".format("$(location //xplat/caffe2/fb/metal:metal_maskrcnn_sources)", path_prefix))
# Unet Metal Prepack Custom op
unet_metal_prepack_file = "$(location //xplat/caffe2/fb/custom_ops/unet_metal_prepack:unet_metal_prepack_sources)"
cmd.append("cp -f " + unet_metal_prepack_file + "/unet_metal_prepack.cpp" + " $OUT")
cmd.append("cp -f " + unet_metal_prepack_file + "/unet_metal_prepack.mm" + " $OUT")
fb_xplat_genrule(
name = name,
cmd = " && ".join(cmd),
cmd_exe = "@powershell -Command " + ("; ".join(cmd_exe)),
# due to an obscure bug certain custom ops werent being copied correctly on windows. ARVR also sometimes builds android targets on windows,
# so we just exclude those targets from being copied for those platforms (They end up uncompiled anyway).
outs = select({
"DEFAULT": get_metal_registration_files_outs(),
"ovr_config//os:android": get_metal_registration_files_outs_windows(),
"ovr_config//os:windows": get_metal_registration_files_outs_windows(),
}),
default_outs = ["."],
apple_sdks = apple_sdks,
)
def get_pt_operator_registry_dict(
name,
deps = [],
train = False,
labels = [],
env = [],
template_select = True,
enforce_traced_op_list = False,
pt_allow_forced_schema_registration = True,
enable_flatbuffer = False,
**kwargs):
code_gen_files = pt_operator_query_codegen(
name,
deps = deps,
train = train,
enforce_traced_op_list = enforce_traced_op_list,
pt_allow_forced_schema_registration = pt_allow_forced_schema_registration,
compatible_with = kwargs.get("compatible_with", []),
apple_sdks = kwargs.get("apple_sdks"),
)
return dict(
srcs = code_gen_files["srcs"],
linker_flags = [
"-Wl,--no-as-needed",
],
# @lint-ignore BUCKLINT link_whole
link_whole = True,
soname = "libtorch-code-gen.$(ext)",
header_namespace = "ATen",
compiler_flags = get_aten_compiler_flags(),
exported_headers = code_gen_files["headers"],
exported_preprocessor_flags = get_aten_preprocessor_flags() + (["-DTEMPLATE_SELECTIVE_BUILD"] if template_select else []),
headers = kwargs.pop("headers", []),
labels = kwargs.pop("labels", []) + [
# This library has multiple sources with the same file name
# and does not work with Buck filegroup used in bad practices.
# Opt out of the bad practices check with the below label.
"bad_practices_ignore_override",
"pt_operator_registry",
],
deps = [
# need absolute path here
ROOT + ":torch_mobile_core",
ROOT + ":aten_cpu",
ROOT + ":aten_metal_prepack_header",
third_party("glog"),
C10,
] + ([ROOT + ":torch_mobile_train"] if train else []) +
([ROOT + ":flatbuffers_jit"] if enable_flatbuffer else []),
**kwargs
)
# these targets are shared by internal and OSS BUCK
def define_buck_targets(
aten_default_args = dict(),
pt_xplat_cxx_library = fb_xplat_cxx_library,
c2_fbandroid_xplat_compiler_flags = [],
labels = []):
# @lint-ignore BUCKLINT
fb_native.filegroup(
name = "metal_build_srcs",
# @lint-ignore BUCKRESTRICTEDSYNTAX
srcs = glob(METAL_SOURCE_LIST),
visibility = [
"PUBLIC",
],
)
# @lint-ignore BUCKLINT
fb_native.filegroup(
name = "templated_selective_build_srcs",
# NB: no glob here, there are generated targets in this list!
# @lint-ignore BUCKRESTRICTEDSYNTAX
srcs = glob(TEMPLATE_SOURCE_LIST) + aten_ufunc_generated_all_cpu_sources(":gen_aten[{}]"),
visibility = [
"PUBLIC",
],
)
fb_xplat_cxx_library(
name = "th_header",
header_namespace = "",
exported_headers = subdir_glob([
# TH
("aten/src", "TH/*.h"),
("aten/src", "TH/*.hpp"),
("aten/src", "TH/generic/*.h"),
("aten/src", "TH/generic/*.hpp"),
("aten/src", "TH/generic/simd/*.h"),
("aten/src", "TH/vector/*.h"),
("aten/src", "TH/generic/*.c"),
("aten/src", "TH/generic/*.cpp"),
("aten/src/TH", "*.h"), # for #include <THGenerateFloatTypes.h>
# THNN
("aten/src", "THNN/*.h"),
("aten/src", "THNN/generic/*.h"),
("aten/src", "THNN/generic/*.c"),
]),
labels = labels,
)
fb_xplat_cxx_library(
name = "aten_header",
header_namespace = "",
exported_headers = subdir_glob([
# ATen Core
("aten/src", "ATen/core/**/*.h"),
("aten/src", "ATen/ops/*.h"),
# ATen Base
("aten/src", "ATen/*.h"),
("aten/src", "ATen/cpu/**/*.h"),
("aten/src", "ATen/detail/*.h"),
("aten/src", "ATen/quantized/*.h"),
("aten/src", "ATen/vulkan/*.h"),
("aten/src", "ATen/metal/*.h"),
("aten/src", "ATen/nnapi/*.h"),
# ATen Native
("aten/src", "ATen/native/*.h"),
("aten/src", "ATen/native/ao_sparse/quantized/cpu/*.h"),
("aten/src", "ATen/native/cpu/**/*.h"),
("aten/src", "ATen/native/sparse/*.h"),
("aten/src", "ATen/native/nested/*.h"),
("aten/src", "ATen/native/quantized/*.h"),
("aten/src", "ATen/native/quantized/cpu/*.h"),
("aten/src", "ATen/native/transformers/*.h"),
("aten/src", "ATen/native/ufunc/*.h"),
("aten/src", "ATen/native/utils/*.h"),
("aten/src", "ATen/native/vulkan/ops/*.h"),
("aten/src", "ATen/native/xnnpack/*.h"),
("aten/src", "ATen/mps/*.h"),
("aten/src", "ATen/native/mps/*.h"),
# Remove the following after modifying codegen for mobile.
("aten/src", "ATen/mkl/*.h"),
("aten/src", "ATen/native/mkl/*.h"),
("aten/src", "ATen/native/mkldnn/*.h"),
]),
visibility = ["PUBLIC"],
labels = labels,
)
fb_xplat_cxx_library(
name = "aten_vulkan_header",
header_namespace = "",
exported_headers = subdir_glob([
("aten/src", "ATen/native/vulkan/*.h"),
("aten/src", "ATen/native/vulkan/api/*.h"),
("aten/src", "ATen/native/vulkan/ops/*.h"),
("aten/src", "ATen/vulkan/*.h"),
]),
labels = labels,
visibility = ["PUBLIC"],
)
fb_xplat_cxx_library(
name = "jit_core_headers",
header_namespace = "",
exported_headers = subdir_glob([("", x) for x in jit_core_headers]),
labels = labels,
)
fb_xplat_cxx_library(
name = "torch_headers",
header_namespace = "",
exported_headers = subdir_glob(
[
("torch/csrc/api/include", "torch/**/*.h"),
("", "torch/csrc/**/*.h"),
("", "torch/csrc/generic/*.cpp"),
("", "torch/script.h"),
("", "torch/library.h"),
("", "torch/custom_class.h"),
("", "torch/custom_class_detail.h"),
# Add again due to namespace difference from aten_header.
("", "aten/src/ATen/*.h"),
("", "aten/src/ATen/quantized/*.h"),
],
exclude = [
# Don't need on mobile.
"torch/csrc/Exceptions.h",
"torch/csrc/python_headers.h",
"torch/csrc/utils/auto_gil.h",
"torch/csrc/jit/serialization/mobile_bytecode_generated.h",
],
),
labels = labels,
visibility = ["PUBLIC"],
deps = [
":generated-version-header",
],
)
fb_xplat_cxx_library(
name = "aten_test_header",
header_namespace = "",
exported_headers = subdir_glob([
("aten/src", "ATen/test/*.h"),
]),
)
fb_xplat_cxx_library(
name = "aten_metal_prepack_header",
header_namespace = "",
exported_headers = subdir_glob([
("aten/src", "ATen/native/metal/MetalPrepackOpContext.h"),
]),
labels = labels,
visibility = ["PUBLIC"],
)
fb_xplat_cxx_library(
name = "torch_mobile_headers",
header_namespace = "",
exported_headers = subdir_glob(
[
("", "torch/csrc/jit/mobile/*.h"),
],
),
labels = labels,
visibility = ["PUBLIC"],
)
fb_xplat_cxx_library(
name = "generated_aten_config_header",
header_namespace = "ATen",
exported_headers = {
"Config.h": ":generate_aten_config[Config.h]",
},
labels = labels,
)
fb_xplat_cxx_library(
name = "generated-autograd-headers",
header_namespace = "torch/csrc/autograd/generated",
exported_headers = {
"Functions.h": ":gen_aten_libtorch[autograd/generated/Functions.h]",
"VariableType.h": ":gen_aten_libtorch[autograd/generated/VariableType.h]",
"variable_factories.h": ":gen_aten_libtorch[autograd/generated/variable_factories.h]",
# Don't build python bindings on mobile.
#"python_functions.h",
},
labels = labels,
visibility = ["PUBLIC"],
)
fb_xplat_cxx_library(
name = "generated-version-header",
header_namespace = "torch",
exported_headers = {
"version.h": ":generate-version-header[version.h]",
},
labels = labels,
)
# @lint-ignore BUCKLINT
fb_native.genrule(
name = "generate-version-header",
srcs = [
"torch/csrc/api/include/torch/version.h.in",
"version.txt",
],
cmd = "$(exe {}tools:gen-version-header) ".format(ROOT_PATH) + " ".join([
"--template-path",
"torch/csrc/api/include/torch/version.h.in",
"--version-path",
"version.txt",
"--output-path",
"$OUT/version.h",
]),
outs = {
"version.h": ["version.h"],
},
default_outs = ["."],
)
# @lint-ignore BUCKLINT
fb_native.filegroup(
name = "aten_src_path",
srcs = [
"aten/src/ATen/native/native_functions.yaml",
"aten/src/ATen/native/tags.yaml",
# @lint-ignore BUCKRESTRICTEDSYNTAX
] + glob(["aten/src/ATen/templates/*"]),
visibility = [
"PUBLIC",
],
)
fb_xplat_cxx_library(
name = "common_core",
srcs = [
"caffe2/core/common.cc",
],
apple_sdks = (IOS, MACOSX, APPLETVOS),
compiler_flags = get_pt_compiler_flags(),
labels = labels,
# @lint-ignore BUCKLINT link_whole
link_whole = True,
visibility = ["PUBLIC"],
windows_preferred_linkage = "static" if is_arvr_mode() else None,
deps = [
":caffe2_headers",
C10,
],
)
# @lint-ignore BUCKLINT
fb_native.genrule(