-
Notifications
You must be signed in to change notification settings - Fork 15
/
tensorflow.bzl
2578 lines (2377 loc) · 83.2 KB
/
tensorflow.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
# Return the options to use for a C++ library or binary build.
# Uses the ":optmode" config_setting to pick the options.
load(
"//tensorflow/core/platform:default/build_config_root.bzl",
"if_dynamic_kernels",
"if_static",
"tf_additional_grpc_deps_py",
"tf_additional_xla_deps_py",
"tf_exec_compatible_with",
"tf_gpu_tests_tags",
"tf_sycl_tests_tags",
)
load(
"@local_config_tensorrt//:build_defs.bzl",
"if_tensorrt",
)
load(
"//tensorflow/core/platform:default/cuda_build_defs.bzl",
"if_cuda_is_configured",
)
load(
"@local_config_cuda//cuda:build_defs.bzl",
"cuda_default_copts",
"if_cuda",
)
load(
"@local_config_rocm//rocm:build_defs.bzl",
"if_rocm",
"if_rocm_is_configured",
"rocm_copts",
)
load(
"//third_party/mkl:build_defs.bzl",
"if_enable_mkl",
"if_mkl",
"if_mkl_lnx_x64",
"if_mkl_ml",
"mkl_deps",
)
load(
"//third_party/mkl_dnn:build_defs.bzl",
"if_mkl_open_source_only",
"if_mkl_v1_open_source_only",
)
load(
"//third_party/ngraph:build_defs.bzl",
"if_ngraph",
)
def register_extension_info(**kwargs):
pass
# version for the shared libraries, can
# not contain rc or alpha, only numbers.
# Also update tensorflow/core/public/version.h
# and tensorflow/tools/pip_package/setup.py
VERSION = "2.1.0"
VERSION_MAJOR = VERSION.split(".")[0]
def if_v2(a):
return select({
clean_dep("//tensorflow:api_version_2"): a,
"//conditions:default": [],
})
def if_not_v2(a):
return select({
clean_dep("//tensorflow:api_version_2"): [],
"//conditions:default": a,
})
def if_nvcc(a):
return select({
"@local_config_cuda//cuda:using_nvcc": a,
"//conditions:default": [],
})
def if_cuda_is_configured_compat(x):
return if_cuda_is_configured(x)
# Given a source file, generate a test name.
# i.e. "common_runtime/direct_session_test.cc" becomes
# "common_runtime_direct_session_test"
def src_to_test_name(src):
return src.replace("/", "_").replace(":", "_").split(".")[0]
def full_path(relative_paths):
return [native.package_name() + "/" + relative for relative in relative_paths]
def _add_tfcore_prefix(src):
if src.startswith("//"):
return src
return "//tensorflow/core:" + src
# List of proto files for android builds
def tf_android_core_proto_sources(core_proto_sources_relative):
return [
_add_tfcore_prefix(p)
for p in core_proto_sources_relative
]
# Returns the list of pb.h and proto.h headers that are generated for
# tf_android_core_proto_sources().
def tf_android_core_proto_headers(core_proto_sources_relative):
return ([
_add_tfcore_prefix(p).replace(":", "/").replace(".proto", ".pb.h")
for p in core_proto_sources_relative
] + [
_add_tfcore_prefix(p).replace(":", "/").replace(".proto", ".proto.h")
for p in core_proto_sources_relative
])
# Wrapper for portable protos which currently just creates an empty rule.
def tf_portable_proto_library(name, proto_deps, **kwargs):
_ignore = [kwargs]
native.cc_library(name = name, deps = proto_deps)
# Sanitize a dependency so that it works correctly from code that includes
# TensorFlow as a submodule.
def clean_dep(dep):
return str(Label(dep))
def if_android_x86(a):
return select({
clean_dep("//tensorflow:android_x86"): a,
clean_dep("//tensorflow:android_x86_64"): a,
"//conditions:default": [],
})
def if_android_arm(a):
return select({
clean_dep("//tensorflow:android_arm"): a,
"//conditions:default": [],
})
def if_android_arm64(a):
return select({
clean_dep("//tensorflow:android_arm64"): a,
"//conditions:default": [],
})
def if_android_mips(a):
return select({
clean_dep("//tensorflow:android_mips"): a,
"//conditions:default": [],
})
def if_not_android(a):
return select({
clean_dep("//tensorflow:android"): [],
"//conditions:default": a,
})
def if_not_android_mips_and_mips64(a):
return select({
clean_dep("//tensorflow:android_mips"): [],
clean_dep("//tensorflow:android_mips64"): [],
"//conditions:default": a,
})
def if_android(a):
return select({
clean_dep("//tensorflow:android"): a,
"//conditions:default": [],
})
def if_emscripten(a):
return select({
clean_dep("//tensorflow:emscripten"): a,
"//conditions:default": [],
})
def if_macos(a, otherwise = []):
return select({
clean_dep("//tensorflow:macos"): a,
"//conditions:default": otherwise,
})
def if_ios(a):
return select({
clean_dep("//tensorflow:ios"): a,
"//conditions:default": [],
})
def if_ios_x86_64(a):
return select({
clean_dep("//tensorflow:ios_x86_64"): a,
"//conditions:default": [],
})
def if_mobile(a):
return select({
clean_dep("//tensorflow:android"): a,
clean_dep("//tensorflow:ios"): a,
"//conditions:default": [],
})
def if_not_mobile(a):
return select({
clean_dep("//tensorflow:android"): [],
clean_dep("//tensorflow:ios"): [],
"//conditions:default": a,
})
# Config setting selector used when building for products
# which requires restricted licenses to be avoided.
def if_not_lgpl_restricted(a):
_ = (a,)
return select({
"//conditions:default": [],
})
def if_not_windows(a):
return select({
clean_dep("//tensorflow:windows"): [],
"//conditions:default": a,
})
def if_windows(a, otherwise = []):
return select({
clean_dep("//tensorflow:windows"): a,
"//conditions:default": otherwise,
})
def if_windows_cuda(a, otherwise = []):
return select({
clean_dep("//tensorflow:with_cuda_support_windows_override"): a,
"//conditions:default": otherwise,
})
def if_linux_x86_64(a):
return select({
clean_dep("//tensorflow:linux_x86_64"): a,
"//conditions:default": [],
})
def if_override_eigen_strong_inline(a):
return select({
clean_dep("//tensorflow:override_eigen_strong_inline"): a,
"//conditions:default": [],
})
def if_nccl(if_true, if_false = []):
return select({
"//tensorflow:no_nccl_support": if_false,
"//tensorflow:windows": if_false,
"//conditions:default": if_true,
})
def get_win_copts(is_external = False):
WINDOWS_COPTS = [
"/DPLATFORM_WINDOWS",
"/DEIGEN_HAS_C99_MATH",
"/DTENSORFLOW_USE_EIGEN_THREADPOOL",
"/DEIGEN_AVOID_STL_ARRAY",
"/Iexternal/gemmlowp",
"/wd4018", # -Wno-sign-compare
# Bazel's CROSSTOOL currently pass /EHsc to enable exception by
# default. We can't pass /EHs-c- to disable exception, otherwise
# we will get a waterfall of flag conflict warnings. Wait for
# Bazel to fix this.
# "/D_HAS_EXCEPTIONS=0",
# "/EHs-c-",
"/wd4577",
"/DNOGDI",
# Also see build:windows lines in tensorflow/opensource_only/.bazelrc
# where we set some other options globally.
]
if is_external:
return WINDOWS_COPTS + ["/UTF_COMPILE_LIBRARY"]
else:
return WINDOWS_COPTS + ["/DTF_COMPILE_LIBRARY"]
def tf_copts(
android_optimization_level_override = "-O2",
is_external = False,
allow_exceptions = False):
# For compatibility reasons, android_optimization_level_override
# is currently only being set for Android.
# To clear this value, and allow the CROSSTOOL default
# to be used, pass android_optimization_level_override=None
android_copts = [
"-DTF_LEAN_BINARY",
"-Wno-narrowing",
"-fomit-frame-pointer",
]
if android_optimization_level_override:
android_copts.append(android_optimization_level_override)
return (
if_not_windows([
"-DEIGEN_AVOID_STL_ARRAY",
"-Iexternal/gemmlowp",
"-Wno-sign-compare",
"-ftemplate-depth=900",
]) +
(if_not_windows(["-fno-exceptions"]) if not allow_exceptions else []) +
if_cuda(["-DGOOGLE_CUDA=1"]) +
if_nvcc(["-DTENSORFLOW_USE_NVCC=1"]) +
if_tensorrt(["-DGOOGLE_TENSORRT=1"]) +
if_mkl(["-DINTEL_MKL=1", "-DEIGEN_USE_VML"]) +
if_mkl_open_source_only(["-DINTEL_MKL_DNN_ONLY"]) +
if_mkl_v1_open_source_only(["-DENABLE_MKLDNN_V1"]) +
if_enable_mkl(["-DENABLE_MKL"]) +
if_ngraph(["-DINTEL_NGRAPH=1"]) +
if_android_arm(["-mfpu=neon"]) +
if_linux_x86_64(["-msse3"]) +
if_ios_x86_64(["-msse4.1"]) +
select({
clean_dep("//tensorflow:framework_shared_object"): [],
"//conditions:default": ["-DTENSORFLOW_MONOLITHIC_BUILD"],
}) +
select({
clean_dep("//tensorflow:android"): android_copts,
clean_dep("//tensorflow:macos"): [],
clean_dep("//tensorflow:windows"): get_win_copts(is_external),
clean_dep("//tensorflow:ios"): [],
clean_dep("//tensorflow:no_lgpl_deps"): ["-D__TENSORFLOW_NO_LGPL_DEPS__", "-pthread"],
"//conditions:default": ["-pthread"],
})
)
def tf_openmp_copts():
return if_mkl_lnx_x64(["-fopenmp"])
def tfe_xla_copts():
return select({
"//tensorflow:with_xla_support": ["-DTENSORFLOW_EAGER_USE_XLA"],
"//conditions:default": [],
})
def tf_opts_nortti_if_android():
return if_android([
"-fno-rtti",
"-DGOOGLE_PROTOBUF_NO_RTTI",
"-DGOOGLE_PROTOBUF_NO_STATIC_INITIALIZER",
])
def tf_opts_nortti_if_emscripten():
return if_emscripten([
"-fno-rtti",
"-DGOOGLE_PROTOBUF_NO_RTTI",
"-DGOOGLE_PROTOBUF_NO_STATIC_INITIALIZER",
])
def tf_features_nomodules_if_android():
return if_android(["-use_header_modules"])
def tf_features_nomodules_if_emscripten():
return if_emscripten(["-use_header_modules"])
# Given a list of "op_lib_names" (a list of files in the ops directory
# without their .cc extensions), generate a library for that file.
def tf_gen_op_libs(op_lib_names, deps = None, is_external = True):
# Make library out of each op so it can also be used to generate wrappers
# for various languages.
if not deps:
deps = []
for n in op_lib_names:
native.cc_library(
name = n + "_op_lib",
copts = tf_copts(is_external = is_external),
srcs = ["ops/" + n + ".cc"],
deps = deps + [clean_dep("//tensorflow/core:framework")],
visibility = ["//visibility:public"],
alwayslink = 1,
linkstatic = 1,
)
def _make_search_paths(prefix, levels_to_root):
return ",".join(
[
"-rpath,%s/%s" % (prefix, "/".join([".."] * search_level))
for search_level in range(levels_to_root + 1)
],
)
def _rpath_linkopts(name):
# Search parent directories up to the TensorFlow root directory for shared
# object dependencies, even if this op shared object is deeply nested
# (e.g. tensorflow/contrib/package:python/ops/_op_lib.so). tensorflow/ is then
# the root and tensorflow/libtensorflow_framework.so should exist when
# deployed. Other shared object dependencies (e.g. shared between contrib/
# ops) are picked up as long as they are in either the same or a parent
# directory in the tensorflow/ tree.
levels_to_root = native.package_name().count("/") + name.count("/")
return select({
clean_dep("//tensorflow:macos"): [
"-Wl,%s" % (_make_search_paths("@loader_path", levels_to_root),),
],
clean_dep("//tensorflow:windows"): [],
"//conditions:default": [
"-Wl,%s" % (_make_search_paths("$$ORIGIN", levels_to_root),),
],
})
# Bazel-generated shared objects which must be linked into TensorFlow binaries
# to define symbols from //tensorflow/core:framework and //tensorflow/core:lib.
def tf_binary_additional_srcs(fullversion = False):
if fullversion:
suffix = "." + VERSION
else:
suffix = "." + VERSION_MAJOR
return if_static(
extra_deps = [],
macos = [
clean_dep("//tensorflow:libtensorflow_framework%s.dylib" % suffix),
],
otherwise = [
clean_dep("//tensorflow:libtensorflow_framework.so%s" % suffix),
],
)
def tf_binary_additional_data_deps():
return if_static(
extra_deps = [],
macos = [
clean_dep("//tensorflow:libtensorflow_framework.dylib"),
clean_dep("//tensorflow:libtensorflow_framework.%s.dylib" % VERSION_MAJOR),
clean_dep("//tensorflow:libtensorflow_framework.%s.dylib" % VERSION),
],
otherwise = [
clean_dep("//tensorflow:libtensorflow_framework.so"),
clean_dep("//tensorflow:libtensorflow_framework.so.%s" % VERSION_MAJOR),
clean_dep("//tensorflow:libtensorflow_framework.so.%s" % VERSION),
],
)
def tf_binary_pybind_deps():
return select({
clean_dep("//tensorflow:macos"): [
clean_dep(
"//tensorflow/python:_pywrap_tensorflow_internal_macos",
),
],
clean_dep("//tensorflow:windows"): [
clean_dep(
"//tensorflow/python:_pywrap_tensorflow_internal_windows",
),
],
"//conditions:default": [
clean_dep(
"//tensorflow/python:_pywrap_tensorflow_internal_linux",
),
],
})
# Helper function for the per-OS tensorflow libraries and their version symlinks
def tf_shared_library_deps():
return select({
clean_dep("//tensorflow:macos_with_framework_shared_object"): [
clean_dep("//tensorflow:libtensorflow.dylib"),
clean_dep("//tensorflow:libtensorflow.%s.dylib" % VERSION_MAJOR),
clean_dep("//tensorflow:libtensorflow.%s.dylib" % VERSION),
],
clean_dep("//tensorflow:macos"): [],
clean_dep("//tensorflow:windows"): [
clean_dep("//tensorflow:tensorflow.dll"),
clean_dep("//tensorflow:tensorflow_dll_import_lib"),
],
clean_dep("//tensorflow:framework_shared_object"): [
clean_dep("//tensorflow:libtensorflow.so"),
clean_dep("//tensorflow:libtensorflow.so.%s" % VERSION_MAJOR),
clean_dep("//tensorflow:libtensorflow.so.%s" % VERSION),
],
"//conditions:default": [],
}) + tf_binary_additional_srcs()
# Helper functions to add kernel dependencies to tf binaries when using dynamic
# kernel linking.
def tf_binary_dynamic_kernel_dsos():
return if_dynamic_kernels(
extra_deps = [
"//tensorflow/core/kernels:libtfkernel_all_kernels.so",
],
otherwise = [],
)
# Helper functions to add kernel dependencies to tf binaries when using static
# kernel linking.
def tf_binary_dynamic_kernel_deps(kernels):
return if_dynamic_kernels(
extra_deps = [],
otherwise = kernels,
)
# Shared libraries have different name pattern on different platforms,
# but cc_binary cannot output correct artifact name yet,
# so we generate multiple cc_binary targets with all name patterns when necessary.
# TODO(pcloudy): Remove this workaround when https://github.com/bazelbuild/bazel/issues/4570
# is done and cc_shared_library is available.
SHARED_LIBRARY_NAME_PATTERNS = [
"lib%s.so%s", # On Linux, shared libraries are usually named as libfoo.so
"lib%s%s.dylib", # On macos, shared libraries are usually named as libfoo.dylib
"%s%s.dll", # On Windows, shared libraries are usually named as foo.dll
]
def tf_cc_shared_object(
name,
srcs = [],
deps = [],
data = [],
linkopts = [],
framework_so = tf_binary_additional_srcs(),
soversion = None,
kernels = [],
per_os_targets = False, # Generate targets with SHARED_LIBRARY_NAME_PATTERNS
visibility = None,
**kwargs):
"""Configure the shared object (.so) file for TensorFlow."""
if soversion != None:
suffix = "." + str(soversion).split(".")[0]
longsuffix = "." + str(soversion)
else:
suffix = ""
longsuffix = ""
if per_os_targets:
names = [
(
pattern % (name, ""),
pattern % (name, suffix),
pattern % (name, longsuffix),
)
for pattern in SHARED_LIBRARY_NAME_PATTERNS
]
else:
names = [(
name,
name + suffix,
name + longsuffix,
)]
for name_os, name_os_major, name_os_full in names:
# Windows DLLs cant be versioned
if name_os.endswith(".dll"):
name_os_major = name_os
name_os_full = name_os
if name_os != name_os_major:
native.genrule(
name = name_os + "_sym",
outs = [name_os],
srcs = [name_os_major],
output_to_bindir = 1,
cmd = "ln -sf $$(basename $<) $@",
)
native.genrule(
name = name_os_major + "_sym",
outs = [name_os_major],
srcs = [name_os_full],
output_to_bindir = 1,
cmd = "ln -sf $$(basename $<) $@",
)
soname = name_os_major.split("/")[-1]
data_extra = []
if framework_so != []:
data_extra = tf_binary_additional_data_deps()
native.cc_binary(
name = name_os_full,
srcs = srcs + framework_so,
deps = deps,
linkshared = 1,
data = data + data_extra,
linkopts = linkopts + _rpath_linkopts(name_os_full) + select({
clean_dep("//tensorflow:macos"): [
"-Wl,-install_name,@rpath/" + soname,
],
clean_dep("//tensorflow:windows"): [],
"//conditions:default": [
"-Wl,-soname," + soname,
],
}),
visibility = visibility,
**kwargs
)
flat_names = [item for sublist in names for item in sublist]
if name not in flat_names:
native.filegroup(
name = name,
srcs = select({
"//tensorflow:windows": [":%s.dll" % (name)],
"//tensorflow:macos": [":lib%s%s.dylib" % (name, longsuffix)],
"//conditions:default": [":lib%s.so%s" % (name, longsuffix)],
}),
visibility = visibility,
)
register_extension_info(
extension_name = "tf_cc_shared_object",
label_regex_for_dep = "{extension_name}",
)
# Links in the framework shared object
# (//third_party/tensorflow:libtensorflow_framework.so) when not building
# statically. Also adds linker options (rpaths) so that the framework shared
# object can be found.
def tf_cc_binary(
name,
srcs = [],
deps = [],
data = [],
linkopts = [],
copts = tf_copts(),
kernels = [],
per_os_targets = False, # Generate targets with SHARED_LIBRARY_NAME_PATTERNS
visibility = None,
**kwargs):
if kernels:
added_data_deps = tf_binary_dynamic_kernel_dsos()
else:
added_data_deps = []
if per_os_targets:
names = [pattern % (name, "") for pattern in SHARED_LIBRARY_NAME_PATTERNS]
else:
names = [name]
for name_os in names:
native.cc_binary(
name = name_os,
copts = copts,
srcs = srcs + tf_binary_additional_srcs(),
deps = deps + tf_binary_dynamic_kernel_deps(kernels) + if_mkl_ml(
[
clean_dep("//third_party/mkl:intel_binary_blob"),
],
) + if_static(
extra_deps = [],
otherwise = [
clean_dep("//tensorflow:libtensorflow_framework_import_lib"),
],
),
data = depset(data + added_data_deps),
linkopts = linkopts + _rpath_linkopts(name_os),
visibility = visibility,
**kwargs
)
if name not in names:
native.filegroup(
name = name,
srcs = select({
"//tensorflow:windows": [":%s.dll" % name],
"//tensorflow:macos": [":lib%s.dylib" % name],
"//conditions:default": [":lib%s.so" % name],
}),
visibility = visibility,
)
register_extension_info(
extension_name = "tf_cc_binary",
label_regex_for_dep = "{extension_name}.*",
)
# A simple wrap around native.cc_binary rule.
# When using this rule, you should realize it doesn't link to any tensorflow
# dependencies by default.
def tf_native_cc_binary(
name,
copts = tf_copts(),
linkopts = [],
**kwargs):
native.cc_binary(
name = name,
copts = copts,
linkopts = select({
clean_dep("//tensorflow:windows"): [],
clean_dep("//tensorflow:macos"): [
"-lm",
],
"//conditions:default": [
"-lpthread",
"-lm",
],
}) + linkopts + _rpath_linkopts(name),
**kwargs
)
register_extension_info(
extension_name = "tf_native_cc_binary",
label_regex_for_dep = "{extension_name}.*",
)
def tf_gen_op_wrapper_cc(
name,
out_ops_file,
pkg = "",
op_gen = clean_dep("//tensorflow/cc:cc_op_gen_main"),
deps = None,
include_internal_ops = 0,
# ApiDefs will be loaded in the order specified in this list.
api_def_srcs = []):
# Construct an op generator binary for these ops.
tool = out_ops_file + "_gen_cc"
if deps == None:
deps = [pkg + ":" + name + "_op_lib"]
tf_cc_binary(
name = tool,
copts = tf_copts(),
linkopts = if_not_windows(["-lm", "-Wl,-ldl"]),
linkstatic = 1, # Faster to link this one-time-use binary dynamically
deps = [op_gen] + deps,
)
srcs = api_def_srcs[:]
if not api_def_srcs:
api_def_args_str = ","
else:
api_def_args = []
for api_def_src in api_def_srcs:
# Add directory of the first ApiDef source to args.
# We are assuming all ApiDefs in a single api_def_src are in the
# same directory.
api_def_args.append(
" $$(dirname $$(echo $(locations " + api_def_src +
") | cut -d\" \" -f1))",
)
api_def_args_str = ",".join(api_def_args)
native.genrule(
name = name + "_genrule",
outs = [
out_ops_file + ".h",
out_ops_file + ".cc",
out_ops_file + "_internal.h",
out_ops_file + "_internal.cc",
],
srcs = srcs,
tools = [":" + tool] + tf_binary_additional_srcs(),
cmd = ("$(location :" + tool + ") $(location :" + out_ops_file + ".h) " +
"$(location :" + out_ops_file + ".cc) " +
str(include_internal_ops) + " " + api_def_args_str),
)
# Given a list of "op_lib_names" (a list of files in the ops directory
# without their .cc extensions), generate individual C++ .cc and .h
# files for each of the ops files mentioned, and then generate a
# single cc_library called "name" that combines all the
# generated C++ code.
#
# For example, for:
# tf_gen_op_wrappers_cc("tf_ops_lib", [ "array_ops", "math_ops" ])
#
#
# This will ultimately generate ops/* files and a library like:
#
# cc_library(name = "tf_ops_lib",
# srcs = [ "ops/array_ops.cc",
# "ops/math_ops.cc" ],
# hdrs = [ "ops/array_ops.h",
# "ops/math_ops.h" ],
# deps = [ ... ])
#
# Plus a private library for the "hidden" ops.
# cc_library(name = "tf_ops_lib_internal",
# srcs = [ "ops/array_ops_internal.cc",
# "ops/math_ops_internal.cc" ],
# hdrs = [ "ops/array_ops_internal.h",
# "ops/math_ops_internal.h" ],
# deps = [ ... ])
# TODO(joshl): Cleaner approach for hidden ops.
def tf_gen_op_wrappers_cc(
name,
op_lib_names = [],
other_srcs = [],
other_hdrs = [],
other_srcs_internal = [],
other_hdrs_internal = [],
pkg = "",
deps = [
clean_dep("//tensorflow/cc:ops"),
clean_dep("//tensorflow/cc:scope"),
clean_dep("//tensorflow/cc:const_op"),
],
deps_internal = [],
op_gen = clean_dep("//tensorflow/cc:cc_op_gen_main"),
include_internal_ops = 0,
visibility = None,
# ApiDefs will be loaded in the order specified in this list.
api_def_srcs = [],
# Any extra dependencies that the wrapper generator might need.
extra_gen_deps = []):
subsrcs = other_srcs[:]
subhdrs = other_hdrs[:]
internalsrcs = other_srcs_internal[:]
internalhdrs = other_hdrs_internal[:]
for n in op_lib_names:
tf_gen_op_wrapper_cc(
n,
"ops/" + n,
api_def_srcs = api_def_srcs,
include_internal_ops = include_internal_ops,
op_gen = op_gen,
pkg = pkg,
deps = [pkg + ":" + n + "_op_lib"] + extra_gen_deps,
)
subsrcs += ["ops/" + n + ".cc"]
subhdrs += ["ops/" + n + ".h"]
internalsrcs += ["ops/" + n + "_internal.cc"]
internalhdrs += ["ops/" + n + "_internal.h"]
native.cc_library(
name = name,
srcs = subsrcs,
hdrs = subhdrs,
deps = deps + if_not_android([
clean_dep("//tensorflow/core:core_cpu"),
clean_dep("//tensorflow/core:framework"),
clean_dep("//tensorflow/core:lib"),
clean_dep("//tensorflow/core:ops"),
clean_dep("//tensorflow/core:protos_all_cc"),
]) + if_android([
clean_dep("//tensorflow/core:android_tensorflow_lib"),
]),
copts = tf_copts(),
alwayslink = 1,
visibility = visibility,
)
native.cc_library(
name = name + "_internal",
srcs = internalsrcs,
hdrs = internalhdrs,
deps = deps + deps_internal + if_not_android([
clean_dep("//tensorflow/core:core_cpu"),
clean_dep("//tensorflow/core:framework"),
clean_dep("//tensorflow/core:lib"),
clean_dep("//tensorflow/core:ops"),
clean_dep("//tensorflow/core:protos_all_cc"),
]) + if_android([
clean_dep("//tensorflow/core:android_tensorflow_lib"),
]),
copts = tf_copts(),
alwayslink = 1,
visibility = [clean_dep("//tensorflow:internal")],
)
# Generates a Python library target wrapping the ops registered in "deps".
#
# Args:
# name: used as the name of the generated target and as a name component of
# the intermediate files.
# out: name of the python file created by this rule. If None, then
# "ops/gen_{name}.py" is used.
# hidden: Optional list of ops names to make private in the Python module.
# It is invalid to specify both "hidden" and "op_whitelist".
# visibility: passed to py_library.
# deps: list of dependencies for the intermediate tool used to generate the
# python target. NOTE these `deps` are not applied to the final python
# library target itself.
# require_shape_functions: Unused. Leave this as False.
# hidden_file: optional file that contains a list of op names to make private
# in the generated Python module. Each op name should be on a line by
# itself. Lines that start with characters that are invalid op name
# starting characters are treated as comments and ignored.
# generated_target_name: name of the generated target (overrides the
# "name" arg)
# op_whitelist: if not empty, only op names in this list will be wrapped. It
# is invalid to specify both "hidden" and "op_whitelist".
# cc_linkopts: Optional linkopts to be added to tf_cc_binary that contains the
# specified ops.
def tf_gen_op_wrapper_py(
name,
out = None,
hidden = None,
visibility = None,
deps = [],
require_shape_functions = False,
hidden_file = None,
generated_target_name = None,
op_whitelist = [],
cc_linkopts = [],
api_def_srcs = []):
_ = require_shape_functions # Unused.
if (hidden or hidden_file) and op_whitelist:
fail("Cannot pass specify both hidden and op_whitelist.")
# Construct a cc_binary containing the specified ops.
tool_name = "gen_" + name + "_py_wrappers_cc"
if not deps:
deps = [str(Label("//tensorflow/core:" + name + "_op_lib"))]
tf_cc_binary(
name = tool_name,
copts = tf_copts(),
linkopts = if_not_windows(["-lm", "-Wl,-ldl"]) + cc_linkopts,
linkstatic = 1, # Faster to link this one-time-use binary dynamically
visibility = [clean_dep("//tensorflow:internal")],
deps = ([
clean_dep("//tensorflow/core:framework"),
clean_dep("//tensorflow/python:python_op_gen_main"),
] + deps),
)
# Invoke the previous cc_binary to generate a python file.
if not out:
out = "ops/gen_" + name + ".py"
if hidden:
op_list_arg = ",".join(hidden)
op_list_is_whitelist = False
elif op_whitelist:
op_list_arg = ",".join(op_whitelist)
op_list_is_whitelist = True
else:
op_list_arg = "''"
op_list_is_whitelist = False
# Prepare ApiDef directories to pass to the genrule.
if not api_def_srcs:
api_def_args_str = ","
else:
api_def_args = []
for api_def_src in api_def_srcs:
# Add directory of the first ApiDef source to args.
# We are assuming all ApiDefs in a single api_def_src are in the
# same directory.
api_def_args.append(
"$$(dirname $$(echo $(locations " + api_def_src +
") | cut -d\" \" -f1))",
)
api_def_args_str = ",".join(api_def_args)
if hidden_file:
# `hidden_file` is file containing a list of op names to be hidden in the
# generated module.
native.genrule(
name = name + "_pygenrule",
outs = [out],
srcs = api_def_srcs + [hidden_file],
tools = [tool_name] + tf_binary_additional_srcs(),
cmd = ("$(location " + tool_name + ") " + api_def_args_str +
" @$(location " + hidden_file + ") > $@"),
)
else:
native.genrule(
name = name + "_pygenrule",
outs = [out],
srcs = api_def_srcs,
tools = [tool_name] + tf_binary_additional_srcs(),
cmd = ("$(location " + tool_name + ") " + api_def_args_str + " " +
op_list_arg + " " +
("1" if op_list_is_whitelist else "0") + " > $@"),
)
# Make a py_library out of the generated python file.
if not generated_target_name:
generated_target_name = name
native.py_library(
name = generated_target_name,
srcs = [out],
srcs_version = "PY2AND3",
visibility = visibility,
deps = [
clean_dep("//tensorflow/python:framework_for_generated_wrappers_v2"),
],
# Instruct build_cleaner to try to avoid using this rule; typically ops
# creators will provide their own tf_custom_op_py_library based target
# that wraps this one.
tags = ["avoid_dep"],
)
# Define a bazel macro that creates cc_test for tensorflow.
#
# Links in the framework shared object
# (//third_party/tensorflow:libtensorflow_framework.so) when not building
# statically. Also adds linker options (rpaths) so that the framework shared
# object can be found.
#
# TODO(opensource): we need to enable this to work around the hidden symbol
# __cudaRegisterFatBinary error. Need more investigations.
def tf_cc_test(
name,
srcs,
deps,
data = [],
linkstatic = 0,
extra_copts = [],
suffix = "",
linkopts = [],
kernels = [],
**kwargs):
native.cc_test(
name = "%s%s" % (name, suffix),
srcs = srcs + tf_binary_additional_srcs(),
copts = tf_copts() + extra_copts,
linkopts = select({
clean_dep("//tensorflow:android"): [
"-pie",
],
clean_dep("//tensorflow:windows"): [],
clean_dep("//tensorflow:macos"): [
"-lm",
],
"//conditions:default": [
"-lpthread",