blob: 6b1fa7f1a863dd75984a70f07bc9c2ff1ec042ba [file] [log] [blame]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ==============================================================================
15"""configure script to get build parameters from user."""
16
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import print_function
20
21import errno
22import os
23import platform
24import re
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070025import subprocess
26import sys
27
Andrew Sellec9885ea2017-11-06 09:37:03 -080028# pylint: disable=g-import-not-at-top
Jonathan Hseu008910f2017-08-25 14:01:05 -070029try:
30 from shutil import which
31except ImportError:
32 from distutils.spawn import find_executable as which
Andrew Sellec9885ea2017-11-06 09:37:03 -080033# pylint: enable=g-import-not-at-top
Jonathan Hseu008910f2017-08-25 14:01:05 -070034
Michael Casefe2c8d82017-10-02 13:54:34 -070035_TF_BAZELRC = os.path.join(os.path.dirname(os.path.abspath(__file__)),
36 '.tf_configure.bazelrc')
Austin Anderson6afface2017-12-05 11:59:17 -080037_TF_WORKSPACE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
38 'WORKSPACE')
Dandelion Man?90e42f32017-12-15 18:15:07 -080039_DEFAULT_CUDA_VERSION = '9.0'
40_DEFAULT_CUDNN_VERSION = '7'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070041_DEFAULT_CUDA_COMPUTE_CAPABILITIES = '3.5,5.2'
42_DEFAULT_CUDA_PATH = '/usr/local/cuda'
43_DEFAULT_CUDA_PATH_LINUX = '/opt/cuda'
44_DEFAULT_CUDA_PATH_WIN = ('C:/Program Files/NVIDIA GPU Computing '
45 'Toolkit/CUDA/v%s' % _DEFAULT_CUDA_VERSION)
Guangda Lai76f69382018-01-25 23:59:19 -080046_DEFAULT_TENSORRT_PATH_LINUX = '/usr/lib/x86_64-linux-gnu'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070047_TF_OPENCL_VERSION = '1.2'
48_DEFAULT_COMPUTECPP_TOOLKIT_PATH = '/usr/local/computecpp'
Yifei Fengb1d8c592017-11-22 13:42:21 -080049_DEFAULT_TRISYCL_INCLUDE_DIR = '/usr/local/triSYCL/include'
Austin Anderson6afface2017-12-05 11:59:17 -080050_SUPPORTED_ANDROID_NDK_VERSIONS = [10, 11, 12, 13, 14, 15]
51
52_DEFAULT_PROMPT_ASK_ATTEMPTS = 10
53
54
55class UserInputError(Exception):
56 pass
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070057
58
59def is_windows():
60 return platform.system() == 'Windows'
61
62
63def is_linux():
64 return platform.system() == 'Linux'
65
66
67def is_macos():
68 return platform.system() == 'Darwin'
69
70
71def is_ppc64le():
72 return platform.machine() == 'ppc64le'
73
74
Jonathan Hseu008910f2017-08-25 14:01:05 -070075def is_cygwin():
76 return platform.system().startswith('CYGWIN_NT')
77
78
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070079def get_input(question):
80 try:
81 try:
82 answer = raw_input(question)
83 except NameError:
84 answer = input(question) # pylint: disable=bad-builtin
85 except EOFError:
86 answer = ''
87 return answer
88
89
90def symlink_force(target, link_name):
91 """Force symlink, equivalent of 'ln -sf'.
92
93 Args:
94 target: items to link to.
95 link_name: name of the link.
96 """
97 try:
98 os.symlink(target, link_name)
99 except OSError as e:
100 if e.errno == errno.EEXIST:
101 os.remove(link_name)
102 os.symlink(target, link_name)
103 else:
104 raise e
105
106
107def sed_in_place(filename, old, new):
108 """Replace old string with new string in file.
109
110 Args:
111 filename: string for filename.
112 old: string to replace.
113 new: new string to replace to.
114 """
115 with open(filename, 'r') as f:
116 filedata = f.read()
117 newdata = filedata.replace(old, new)
118 with open(filename, 'w') as f:
119 f.write(newdata)
120
121
122def remove_line_with(filename, token):
123 """Remove lines that contain token from file.
124
125 Args:
126 filename: string for filename.
127 token: string token to check if to remove a line from file or not.
128 """
129 with open(filename, 'r') as f:
130 filedata = f.read()
131
132 with open(filename, 'w') as f:
133 for line in filedata.strip().split('\n'):
134 if token not in line:
135 f.write(line + '\n')
136
137
138def write_to_bazelrc(line):
139 with open(_TF_BAZELRC, 'a') as f:
140 f.write(line + '\n')
141
142
143def write_action_env_to_bazelrc(var_name, var):
144 write_to_bazelrc('build --action_env %s="%s"' % (var_name, str(var)))
145
146
Jonathan Hseu008910f2017-08-25 14:01:05 -0700147def run_shell(cmd, allow_non_zero=False):
148 if allow_non_zero:
149 try:
150 output = subprocess.check_output(cmd)
151 except subprocess.CalledProcessError as e:
152 output = e.output
153 else:
154 output = subprocess.check_output(cmd)
155 return output.decode('UTF-8').strip()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700156
157
158def cygpath(path):
159 """Convert path from posix to windows."""
Martin Wicked57572e2017-09-02 19:21:45 -0700160 return os.path.abspath(path).replace('\\', '/')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700161
162
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700163def get_python_path(environ_cp, python_bin_path):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700164 """Get the python site package paths."""
165 python_paths = []
166 if environ_cp.get('PYTHONPATH'):
167 python_paths = environ_cp.get('PYTHONPATH').split(':')
168 try:
Jonathan Hseu008910f2017-08-25 14:01:05 -0700169 library_paths = run_shell(
170 [python_bin_path, '-c',
Austin Anderson6afface2017-12-05 11:59:17 -0800171 'import site; print("\\n".join(site.getsitepackages()))']).split('\n')
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700172 except subprocess.CalledProcessError:
Jonathan Hseu008910f2017-08-25 14:01:05 -0700173 library_paths = [run_shell(
174 [python_bin_path, '-c',
175 'from distutils.sysconfig import get_python_lib;'
176 'print(get_python_lib())'])]
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700177
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700178 all_paths = set(python_paths + library_paths)
179
180 paths = []
181 for path in all_paths:
182 if os.path.isdir(path):
183 paths.append(path)
184 return paths
185
186
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700187def get_python_major_version(python_bin_path):
188 """Get the python major version."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700189 return run_shell([python_bin_path, '-c', 'import sys; print(sys.version[0])'])
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700190
191
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700192def setup_python(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700193 """Setup python related env variables."""
194 # Get PYTHON_BIN_PATH, default is the current running python.
195 default_python_bin_path = sys.executable
196 ask_python_bin_path = ('Please specify the location of python. [Default is '
197 '%s]: ') % default_python_bin_path
198 while True:
199 python_bin_path = get_from_env_or_user_or_default(
200 environ_cp, 'PYTHON_BIN_PATH', ask_python_bin_path,
201 default_python_bin_path)
202 # Check if the path is valid
Jonathan Hseu008910f2017-08-25 14:01:05 -0700203 if os.path.isfile(python_bin_path) and os.access(
204 python_bin_path, os.X_OK):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700205 break
206 elif not os.path.exists(python_bin_path):
207 print('Invalid python path: %s cannot be found.' % python_bin_path)
208 else:
209 print('%s is not executable. Is it the python binary?' % python_bin_path)
210 environ_cp['PYTHON_BIN_PATH'] = ''
211
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700212 # Convert python path to Windows style before checking lib and version
Martin Wicked57572e2017-09-02 19:21:45 -0700213 if is_windows() or is_cygwin():
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700214 python_bin_path = cygpath(python_bin_path)
215
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700216 # Get PYTHON_LIB_PATH
217 python_lib_path = environ_cp.get('PYTHON_LIB_PATH')
218 if not python_lib_path:
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700219 python_lib_paths = get_python_path(environ_cp, python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700220 if environ_cp.get('USE_DEFAULT_PYTHON_LIB_PATH') == '1':
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700221 python_lib_path = python_lib_paths[0]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700222 else:
Jonathan Hseu008910f2017-08-25 14:01:05 -0700223 print('Found possible Python library paths:\n %s' %
224 '\n '.join(python_lib_paths))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700225 default_python_lib_path = python_lib_paths[0]
226 python_lib_path = get_input(
Jonathan Hseu008910f2017-08-25 14:01:05 -0700227 'Please input the desired Python library path to use. '
228 'Default is [%s]\n' % python_lib_paths[0])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700229 if not python_lib_path:
230 python_lib_path = default_python_lib_path
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700231 environ_cp['PYTHON_LIB_PATH'] = python_lib_path
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700232
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700233 python_major_version = get_python_major_version(python_bin_path)
234
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700235 # Convert python path to Windows style before writing into bazel.rc
Martin Wicked57572e2017-09-02 19:21:45 -0700236 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700237 python_lib_path = cygpath(python_lib_path)
238
239 # Set-up env variables used by python_configure.bzl
240 write_action_env_to_bazelrc('PYTHON_BIN_PATH', python_bin_path)
241 write_action_env_to_bazelrc('PYTHON_LIB_PATH', python_lib_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700242 write_to_bazelrc('build --force_python=py%s' % python_major_version)
243 write_to_bazelrc('build --host_force_python=py%s' % python_major_version)
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700244 write_to_bazelrc('build --python_path=\"%s"' % python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700245 environ_cp['PYTHON_BIN_PATH'] = python_bin_path
246
247 # Write tools/python_bin_path.sh
248 with open('tools/python_bin_path.sh', 'w') as f:
249 f.write('export PYTHON_BIN_PATH="%s"' % python_bin_path)
250
251
252def reset_tf_configure_bazelrc():
253 """Reset file that contains customized config settings."""
254 open(_TF_BAZELRC, 'w').close()
255
256 home = os.path.expanduser('~')
257 if not os.path.exists('.bazelrc'):
258 if os.path.exists(os.path.join(home, '.bazelrc')):
259 with open('.bazelrc', 'a') as f:
Shanqing Caie2e3a942017-09-25 19:35:53 -0700260 f.write('import %s/.bazelrc\n' % home.replace('\\', '/'))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700261 else:
262 open('.bazelrc', 'w').close()
263
264 remove_line_with('.bazelrc', 'tf_configure')
265 with open('.bazelrc', 'a') as f:
266 f.write('import %workspace%/.tf_configure.bazelrc\n')
267
268
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700269def cleanup_makefile():
270 """Delete any leftover BUILD files from the Makefile build.
271
272 These files could interfere with Bazel parsing.
273 """
274 makefile_download_dir = 'tensorflow/contrib/makefile/downloads'
275 if os.path.isdir(makefile_download_dir):
276 for root, _, filenames in os.walk(makefile_download_dir):
277 for f in filenames:
278 if f.endswith('BUILD'):
279 os.remove(os.path.join(root, f))
280
281
282def get_var(environ_cp,
283 var_name,
284 query_item,
285 enabled_by_default,
286 question=None,
287 yes_reply=None,
288 no_reply=None):
289 """Get boolean input from user.
290
291 If var_name is not set in env, ask user to enable query_item or not. If the
292 response is empty, use the default.
293
294 Args:
295 environ_cp: copy of the os.environ.
296 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
297 query_item: string for feature related to the variable, e.g. "Hadoop File
298 System".
299 enabled_by_default: boolean for default behavior.
300 question: optional string for how to ask for user input.
Michael Cased90054e2018-02-07 14:36:00 -0800301 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700302 no_reply: optional string for reply when feature is disabled.
303
304 Returns:
305 boolean value of the variable.
Frank Chenc4ef9272018-01-10 11:36:52 -0800306
307 Raises:
308 UserInputError: if an environment variable is set, but it cannot be
309 interpreted as a boolean indicator, assume that the user has made a
310 scripting error, and will continue to provide invalid input.
311 Raise the error to avoid infinitely looping.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700312 """
313 if not question:
314 question = 'Do you wish to build TensorFlow with %s support?' % query_item
315 if not yes_reply:
316 yes_reply = '%s support will be enabled for TensorFlow.' % query_item
317 if not no_reply:
318 no_reply = 'No %s' % yes_reply
319
320 yes_reply += '\n'
321 no_reply += '\n'
322
323 if enabled_by_default:
324 question += ' [Y/n]: '
325 else:
326 question += ' [y/N]: '
327
328 var = environ_cp.get(var_name)
Frank Chenc4ef9272018-01-10 11:36:52 -0800329 if var is not None:
330 var_content = var.strip().lower()
331 true_strings = ('1', 't', 'true', 'y', 'yes')
332 false_strings = ('0', 'f', 'false', 'n', 'no')
333 if var_content in true_strings:
334 var = True
335 elif var_content in false_strings:
336 var = False
337 else:
338 raise UserInputError(
339 'Environment variable %s must be set as a boolean indicator.\n'
340 'The following are accepted as TRUE : %s.\n'
341 'The following are accepted as FALSE: %s.\n'
342 'Current value is %s.' % (
343 var_name, ', '.join(true_strings), ', '.join(false_strings),
344 var))
345
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700346 while var is None:
347 user_input_origin = get_input(question)
348 user_input = user_input_origin.strip().lower()
349 if user_input == 'y':
350 print(yes_reply)
351 var = True
352 elif user_input == 'n':
353 print(no_reply)
354 var = False
355 elif not user_input:
356 if enabled_by_default:
357 print(yes_reply)
358 var = True
359 else:
360 print(no_reply)
361 var = False
362 else:
363 print('Invalid selection: %s' % user_input_origin)
364 return var
365
366
367def set_build_var(environ_cp, var_name, query_item, option_name,
Michael Case98850a52017-09-14 13:35:57 -0700368 enabled_by_default, bazel_config_name=None):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700369 """Set if query_item will be enabled for the build.
370
371 Ask user if query_item will be enabled. Default is used if no input is given.
372 Set subprocess environment variable and write to .bazelrc if enabled.
373
374 Args:
375 environ_cp: copy of the os.environ.
376 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
377 query_item: string for feature related to the variable, e.g. "Hadoop File
378 System".
379 option_name: string for option to define in .bazelrc.
380 enabled_by_default: boolean for default behavior.
Michael Case98850a52017-09-14 13:35:57 -0700381 bazel_config_name: Name for Bazel --config argument to enable build feature.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700382 """
383
384 var = str(int(get_var(environ_cp, var_name, query_item, enabled_by_default)))
385 environ_cp[var_name] = var
386 if var == '1':
387 write_to_bazelrc('build --define %s=true' % option_name)
Michael Case98850a52017-09-14 13:35:57 -0700388 elif bazel_config_name is not None:
389 # TODO(mikecase): Migrate all users of configure.py to use --config Bazel
390 # options and not to set build configs through environment variables.
391 write_to_bazelrc('build:%s --define %s=true'
392 % (bazel_config_name, option_name))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700393
394
395def set_action_env_var(environ_cp,
396 var_name,
397 query_item,
398 enabled_by_default,
399 question=None,
400 yes_reply=None,
401 no_reply=None):
402 """Set boolean action_env variable.
403
404 Ask user if query_item will be enabled. Default is used if no input is given.
405 Set environment variable and write to .bazelrc.
406
407 Args:
408 environ_cp: copy of the os.environ.
409 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
410 query_item: string for feature related to the variable, e.g. "Hadoop File
411 System".
412 enabled_by_default: boolean for default behavior.
413 question: optional string for how to ask for user input.
Michael Cased90054e2018-02-07 14:36:00 -0800414 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700415 no_reply: optional string for reply when feature is disabled.
416 """
417 var = int(
418 get_var(environ_cp, var_name, query_item, enabled_by_default, question,
419 yes_reply, no_reply))
420
421 write_action_env_to_bazelrc(var_name, var)
422 environ_cp[var_name] = str(var)
423
424
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700425def convert_version_to_int(version):
426 """Convert a version number to a integer that can be used to compare.
427
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700428 Version strings of the form X.YZ and X.Y.Z-xxxxx are supported. The
429 'xxxxx' part, for instance 'homebrew' on OS/X, is ignored.
430
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700431 Args:
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700432 version: a version to be converted
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700433
434 Returns:
435 An integer if converted successfully, otherwise return None.
436 """
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700437 version = version.split('-')[0]
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700438 version_segments = version.split('.')
439 for seg in version_segments:
440 if not seg.isdigit():
441 return None
442
443 version_str = ''.join(['%03d' % int(seg) for seg in version_segments])
444 return int(version_str)
445
446
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700447def check_bazel_version(min_version):
448 """Check installed bezel version is at least min_version.
449
450 Args:
451 min_version: string for minimum bazel version.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700452
453 Returns:
454 The bazel version detected.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700455 """
Jonathan Hseu008910f2017-08-25 14:01:05 -0700456 if which('bazel') is None:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700457 print('Cannot find bazel. Please install bazel.')
458 sys.exit(0)
Jonathan Hseu008910f2017-08-25 14:01:05 -0700459 curr_version = run_shell(['bazel', '--batch', 'version'])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700460
461 for line in curr_version.split('\n'):
462 if 'Build label: ' in line:
463 curr_version = line.split('Build label: ')[1]
464 break
465
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700466 min_version_int = convert_version_to_int(min_version)
467 curr_version_int = convert_version_to_int(curr_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700468
469 # Check if current bazel version can be detected properly.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700470 if not curr_version_int:
471 print('WARNING: current bazel installation is not a release version.')
472 print('Make sure you are running at least bazel %s' % min_version)
473 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700474
Michael Cased94271a2017-08-22 17:26:52 -0700475 print('You have bazel %s installed.' % curr_version)
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700476
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700477 if curr_version_int < min_version_int:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700478 print('Please upgrade your bazel installation to version %s or higher to '
479 'build TensorFlow!' % min_version)
480 sys.exit(0)
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700481 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700482
483
484def set_cc_opt_flags(environ_cp):
485 """Set up architecture-dependent optimization flags.
486
487 Also append CC optimization flags to bazel.rc..
488
489 Args:
490 environ_cp: copy of the os.environ.
491 """
492 if is_ppc64le():
493 # gcc on ppc64le does not support -march, use mcpu instead
494 default_cc_opt_flags = '-mcpu=native'
495 else:
496 default_cc_opt_flags = '-march=native'
497 question = ('Please specify optimization flags to use during compilation when'
498 ' bazel option "--config=opt" is specified [Default is %s]: '
499 ) % default_cc_opt_flags
500 cc_opt_flags = get_from_env_or_user_or_default(environ_cp, 'CC_OPT_FLAGS',
501 question, default_cc_opt_flags)
502 for opt in cc_opt_flags.split():
Michael Case00177422017-11-10 13:14:03 -0800503 write_to_bazelrc('build:opt --copt=%s' % opt)
504 # It should be safe on the same build host.
505 write_to_bazelrc('build:opt --host_copt=-march=native')
Michael Casebb3355d2017-11-09 08:46:31 -0800506 write_to_bazelrc('build:opt --define with_default_optimizations=true')
Michael Case00177422017-11-10 13:14:03 -0800507 # TODO(mikecase): Remove these default defines once we are able to get
508 # TF Lite targets building without them.
Andrew Selle0b154392017-11-10 10:35:35 -0800509 write_to_bazelrc('build --copt=-DGEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK')
510 write_to_bazelrc('build --host_copt=-DGEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700511
512
513def set_tf_cuda_clang(environ_cp):
514 """set TF_CUDA_CLANG action_env.
515
516 Args:
517 environ_cp: copy of the os.environ.
518 """
519 question = 'Do you want to use clang as CUDA compiler?'
520 yes_reply = 'Clang will be used as CUDA compiler.'
521 no_reply = 'nvcc will be used as CUDA compiler.'
522 set_action_env_var(
523 environ_cp,
524 'TF_CUDA_CLANG',
525 None,
526 False,
527 question=question,
528 yes_reply=yes_reply,
529 no_reply=no_reply)
530
531
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800532def set_tf_download_clang(environ_cp):
533 """Set TF_DOWNLOAD_CLANG action_env."""
534 question = 'Do you want to download a fresh release of clang? (Experimental)'
535 yes_reply = 'Clang will be downloaded and used to compile tensorflow.'
536 no_reply = 'Clang will not be downloaded.'
537 set_action_env_var(
538 environ_cp,
539 'TF_DOWNLOAD_CLANG',
540 None,
541 False,
542 question=question,
543 yes_reply=yes_reply,
544 no_reply=no_reply)
545
546
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700547def get_from_env_or_user_or_default(environ_cp, var_name, ask_for_var,
548 var_default):
549 """Get var_name either from env, or user or default.
550
551 If var_name has been set as environment variable, use the preset value, else
552 ask for user input. If no input is provided, the default is used.
553
554 Args:
555 environ_cp: copy of the os.environ.
556 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
557 ask_for_var: string for how to ask for user input.
558 var_default: default value string.
559
560 Returns:
561 string value for var_name
562 """
563 var = environ_cp.get(var_name)
564 if not var:
565 var = get_input(ask_for_var)
Michael Cased94271a2017-08-22 17:26:52 -0700566 print('\n')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700567 if not var:
568 var = var_default
569 return var
570
571
572def set_clang_cuda_compiler_path(environ_cp):
573 """Set CLANG_CUDA_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700574 default_clang_path = which('clang') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700575 ask_clang_path = ('Please specify which clang should be used as device and '
576 'host compiler. [Default is %s]: ') % default_clang_path
577
578 while True:
579 clang_cuda_compiler_path = get_from_env_or_user_or_default(
580 environ_cp, 'CLANG_CUDA_COMPILER_PATH', ask_clang_path,
581 default_clang_path)
582 if os.path.exists(clang_cuda_compiler_path):
583 break
584
585 # Reset and retry
586 print('Invalid clang path: %s cannot be found.' % clang_cuda_compiler_path)
587 environ_cp['CLANG_CUDA_COMPILER_PATH'] = ''
588
589 # Set CLANG_CUDA_COMPILER_PATH
590 environ_cp['CLANG_CUDA_COMPILER_PATH'] = clang_cuda_compiler_path
591 write_action_env_to_bazelrc('CLANG_CUDA_COMPILER_PATH',
592 clang_cuda_compiler_path)
593
594
Austin Anderson6afface2017-12-05 11:59:17 -0800595def prompt_loop_or_load_from_env(
596 environ_cp,
597 var_name,
598 var_default,
599 ask_for_var,
600 check_success,
601 error_msg,
602 suppress_default_error=False,
603 n_ask_attempts=_DEFAULT_PROMPT_ASK_ATTEMPTS
604):
605 """Loop over user prompts for an ENV param until receiving a valid response.
606
607 For the env param var_name, read from the environment or verify user input
608 until receiving valid input. When done, set var_name in the environ_cp to its
609 new value.
610
611 Args:
612 environ_cp: (Dict) copy of the os.environ.
613 var_name: (String) string for name of environment variable, e.g. "TF_MYVAR".
614 var_default: (String) default value string.
615 ask_for_var: (String) string for how to ask for user input.
616 check_success: (Function) function that takes one argument and returns a
617 boolean. Should return True if the value provided is considered valid. May
618 contain a complex error message if error_msg does not provide enough
619 information. In that case, set suppress_default_error to True.
620 error_msg: (String) String with one and only one '%s'. Formatted with each
621 invalid response upon check_success(input) failure.
622 suppress_default_error: (Bool) Suppress the above error message in favor of
623 one from the check_success function.
624 n_ask_attempts: (Integer) Number of times to query for valid input before
625 raising an error and quitting.
626
627 Returns:
628 [String] The value of var_name after querying for input.
629
630 Raises:
631 UserInputError: if a query has been attempted n_ask_attempts times without
Frank Chenc4ef9272018-01-10 11:36:52 -0800632 success, assume that the user has made a scripting error, and will
633 continue to provide invalid input. Raise the error to avoid infinitely
634 looping.
Austin Anderson6afface2017-12-05 11:59:17 -0800635 """
636 default = environ_cp.get(var_name) or var_default
637 full_query = '%s [Default is %s]: ' % (
638 ask_for_var,
639 default,
640 )
641
642 for _ in range(n_ask_attempts):
643 val = get_from_env_or_user_or_default(environ_cp,
644 var_name,
645 full_query,
646 default)
647 if check_success(val):
648 break
649 if not suppress_default_error:
650 print(error_msg % val)
651 environ_cp[var_name] = ''
652 else:
653 raise UserInputError('Invalid %s setting was provided %d times in a row. '
654 'Assuming to be a scripting mistake.' %
655 (var_name, n_ask_attempts))
656
657 environ_cp[var_name] = val
658 return val
659
660
661def create_android_ndk_rule(environ_cp):
662 """Set ANDROID_NDK_HOME and write Android NDK WORKSPACE rule."""
663 if is_windows() or is_cygwin():
664 default_ndk_path = cygpath('%s/Android/Sdk/ndk-bundle' %
665 environ_cp['APPDATA'])
666 elif is_macos():
667 default_ndk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
668 else:
669 default_ndk_path = '%s/Android/Sdk/ndk-bundle' % environ_cp['HOME']
670
671 def valid_ndk_path(path):
672 return (os.path.exists(path) and
673 os.path.exists(os.path.join(path, 'source.properties')))
674
675 android_ndk_home_path = prompt_loop_or_load_from_env(
676 environ_cp,
677 var_name='ANDROID_NDK_HOME',
678 var_default=default_ndk_path,
679 ask_for_var='Please specify the home path of the Android NDK to use.',
680 check_success=valid_ndk_path,
681 error_msg=('The path %s or its child file "source.properties" '
682 'does not exist.')
683 )
684
685 write_android_ndk_workspace_rule(android_ndk_home_path)
686
687
688def create_android_sdk_rule(environ_cp):
689 """Set Android variables and write Android SDK WORKSPACE rule."""
690 if is_windows() or is_cygwin():
691 default_sdk_path = cygpath('%s/Android/Sdk' % environ_cp['APPDATA'])
692 elif is_macos():
693 default_sdk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
694 else:
695 default_sdk_path = '%s/Android/Sdk' % environ_cp['HOME']
696
697 def valid_sdk_path(path):
698 return (os.path.exists(path) and
699 os.path.exists(os.path.join(path, 'platforms')) and
700 os.path.exists(os.path.join(path, 'build-tools')))
701
702 android_sdk_home_path = prompt_loop_or_load_from_env(
703 environ_cp,
704 var_name='ANDROID_SDK_HOME',
705 var_default=default_sdk_path,
706 ask_for_var='Please specify the home path of the Android SDK to use.',
707 check_success=valid_sdk_path,
708 error_msg=('Either %s does not exist, or it does not contain the '
709 'subdirectories "platforms" and "build-tools".'))
710
711 platforms = os.path.join(android_sdk_home_path, 'platforms')
712 api_levels = sorted(os.listdir(platforms))
713 api_levels = [x.replace('android-', '') for x in api_levels]
714
715 def valid_api_level(api_level):
716 return os.path.exists(os.path.join(android_sdk_home_path,
717 'platforms',
718 'android-' + api_level))
719
720 android_api_level = prompt_loop_or_load_from_env(
721 environ_cp,
722 var_name='ANDROID_API_LEVEL',
723 var_default=api_levels[-1],
724 ask_for_var=('Please specify the Android SDK API level to use. '
725 '[Available levels: %s]') % api_levels,
726 check_success=valid_api_level,
727 error_msg='Android-%s is not present in the SDK path.')
728
729 build_tools = os.path.join(android_sdk_home_path, 'build-tools')
730 versions = sorted(os.listdir(build_tools))
731
732 def valid_build_tools(version):
733 return os.path.exists(os.path.join(android_sdk_home_path,
734 'build-tools',
735 version))
736
737 android_build_tools_version = prompt_loop_or_load_from_env(
738 environ_cp,
739 var_name='ANDROID_BUILD_TOOLS_VERSION',
740 var_default=versions[-1],
741 ask_for_var=('Please specify an Android build tools version to use. '
742 '[Available versions: %s]') % versions,
743 check_success=valid_build_tools,
744 error_msg=('The selected SDK does not have build-tools version %s '
745 'available.'))
746
747 write_android_sdk_workspace_rule(android_sdk_home_path,
748 android_build_tools_version,
749 android_api_level)
750
751
752def write_android_sdk_workspace_rule(android_sdk_home_path,
753 android_build_tools_version,
754 android_api_level):
755 print('Writing android_sdk_workspace rule.\n')
756 with open(_TF_WORKSPACE, 'a') as f:
757 f.write("""
758android_sdk_repository(
759 name="androidsdk",
760 api_level=%s,
761 path="%s",
762 build_tools_version="%s")\n
763""" % (android_api_level, android_sdk_home_path, android_build_tools_version))
764
765
766def write_android_ndk_workspace_rule(android_ndk_home_path):
767 print('Writing android_ndk_workspace rule.')
768 ndk_api_level = check_ndk_level(android_ndk_home_path)
769 if int(ndk_api_level) not in _SUPPORTED_ANDROID_NDK_VERSIONS:
770 print('WARNING: The API level of the NDK in %s is %s, which is not '
771 'supported by Bazel (officially supported versions: %s). Please use '
772 'another version. Compiling Android targets may result in confusing '
773 'errors.\n' % (android_ndk_home_path, ndk_api_level,
774 _SUPPORTED_ANDROID_NDK_VERSIONS))
775 with open(_TF_WORKSPACE, 'a') as f:
776 f.write("""
777android_ndk_repository(
778 name="androidndk",
779 path="%s",
780 api_level=%s)\n
781""" % (android_ndk_home_path, ndk_api_level))
782
783
784def check_ndk_level(android_ndk_home_path):
785 """Check the revision number of an Android NDK path."""
786 properties_path = '%s/source.properties' % android_ndk_home_path
787 if is_windows() or is_cygwin():
788 properties_path = cygpath(properties_path)
789 with open(properties_path, 'r') as f:
790 filedata = f.read()
791
792 revision = re.search(r'Pkg.Revision = (\d+)', filedata)
793 if revision:
794 return revision.group(1)
795 return None
796
797
798def workspace_has_any_android_rule():
799 """Check the WORKSPACE for existing android_*_repository rules."""
800 with open(_TF_WORKSPACE, 'r') as f:
801 workspace = f.read()
802 has_any_rule = re.search(r'^android_[ns]dk_repository',
803 workspace,
804 re.MULTILINE)
805 return has_any_rule
806
807
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700808def set_gcc_host_compiler_path(environ_cp):
809 """Set GCC_HOST_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700810 default_gcc_host_compiler_path = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700811 cuda_bin_symlink = '%s/bin/gcc' % environ_cp.get('CUDA_TOOLKIT_PATH')
812
813 if os.path.islink(cuda_bin_symlink):
814 # os.readlink is only available in linux
Jonathan Hseu008910f2017-08-25 14:01:05 -0700815 default_gcc_host_compiler_path = os.path.realpath(cuda_bin_symlink)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700816
Austin Anderson6afface2017-12-05 11:59:17 -0800817 gcc_host_compiler_path = prompt_loop_or_load_from_env(
818 environ_cp,
819 var_name='GCC_HOST_COMPILER_PATH',
820 var_default=default_gcc_host_compiler_path,
821 ask_for_var=
822 'Please specify which gcc should be used by nvcc as the host compiler.',
823 check_success=os.path.exists,
824 error_msg='Invalid gcc path. %s cannot be found.',
825 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700826
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700827 write_action_env_to_bazelrc('GCC_HOST_COMPILER_PATH', gcc_host_compiler_path)
828
829
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800830def reformat_version_sequence(version_str, sequence_count):
831 """Reformat the version string to have the given number of sequences.
832
833 For example:
834 Given (7, 2) -> 7.0
835 (7.0.1, 2) -> 7.0
836 (5, 1) -> 5
837 (5.0.3.2, 1) -> 5
838
839 Args:
840 version_str: String, the version string.
841 sequence_count: int, an integer.
842 Returns:
843 string, reformatted version string.
844 """
845 v = version_str.split('.')
846 if len(v) < sequence_count:
847 v = v + (['0'] * (sequence_count - len(v)))
848
849 return '.'.join(v[:sequence_count])
850
851
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700852def set_tf_cuda_version(environ_cp):
853 """Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION."""
854 ask_cuda_version = (
855 'Please specify the CUDA SDK version you want to use, '
856 'e.g. 7.0. [Leave empty to default to CUDA %s]: ') % _DEFAULT_CUDA_VERSION
857
Austin Andersonf9a88f82017-12-13 11:49:40 -0800858 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700859 # Configure the Cuda SDK version to use.
860 tf_cuda_version = get_from_env_or_user_or_default(
861 environ_cp, 'TF_CUDA_VERSION', ask_cuda_version, _DEFAULT_CUDA_VERSION)
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800862 tf_cuda_version = reformat_version_sequence(str(tf_cuda_version), 2)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700863
864 # Find out where the CUDA toolkit is installed
865 default_cuda_path = _DEFAULT_CUDA_PATH
Martin Wicked57572e2017-09-02 19:21:45 -0700866 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700867 default_cuda_path = cygpath(
868 environ_cp.get('CUDA_PATH', _DEFAULT_CUDA_PATH_WIN))
869 elif is_linux():
870 # If the default doesn't exist, try an alternative default.
871 if (not os.path.exists(default_cuda_path)
872 ) and os.path.exists(_DEFAULT_CUDA_PATH_LINUX):
873 default_cuda_path = _DEFAULT_CUDA_PATH_LINUX
874 ask_cuda_path = ('Please specify the location where CUDA %s toolkit is'
875 ' installed. Refer to README.md for more details. '
876 '[Default is %s]: ') % (tf_cuda_version, default_cuda_path)
877 cuda_toolkit_path = get_from_env_or_user_or_default(
878 environ_cp, 'CUDA_TOOLKIT_PATH', ask_cuda_path, default_cuda_path)
879
880 if is_windows():
881 cuda_rt_lib_path = 'lib/x64/cudart.lib'
882 elif is_linux():
883 cuda_rt_lib_path = 'lib64/libcudart.so.%s' % tf_cuda_version
884 elif is_macos():
885 cuda_rt_lib_path = 'lib/libcudart.%s.dylib' % tf_cuda_version
886
887 cuda_toolkit_path_full = os.path.join(cuda_toolkit_path, cuda_rt_lib_path)
888 if os.path.exists(cuda_toolkit_path_full):
889 break
890
891 # Reset and retry
892 print('Invalid path to CUDA %s toolkit. %s cannot be found' %
893 (tf_cuda_version, cuda_toolkit_path_full))
894 environ_cp['TF_CUDA_VERSION'] = ''
895 environ_cp['CUDA_TOOLKIT_PATH'] = ''
896
Austin Andersonf9a88f82017-12-13 11:49:40 -0800897 else:
898 raise UserInputError('Invalid TF_CUDA_SETTING setting was provided %d '
899 'times in a row. Assuming to be a scripting mistake.' %
900 _DEFAULT_PROMPT_ASK_ATTEMPTS)
901
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700902 # Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION
903 environ_cp['CUDA_TOOLKIT_PATH'] = cuda_toolkit_path
904 write_action_env_to_bazelrc('CUDA_TOOLKIT_PATH', cuda_toolkit_path)
905 environ_cp['TF_CUDA_VERSION'] = tf_cuda_version
906 write_action_env_to_bazelrc('TF_CUDA_VERSION', tf_cuda_version)
907
908
Yifei Fengb1d8c592017-11-22 13:42:21 -0800909def set_tf_cudnn_version(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700910 """Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION."""
911 ask_cudnn_version = (
Jonathan Hseu008910f2017-08-25 14:01:05 -0700912 'Please specify the cuDNN version you want to use. '
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700913 '[Leave empty to default to cuDNN %s.0]: ') % _DEFAULT_CUDNN_VERSION
914
Austin Andersonf9a88f82017-12-13 11:49:40 -0800915 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700916 tf_cudnn_version = get_from_env_or_user_or_default(
917 environ_cp, 'TF_CUDNN_VERSION', ask_cudnn_version,
918 _DEFAULT_CUDNN_VERSION)
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800919 tf_cudnn_version = reformat_version_sequence(str(tf_cudnn_version), 1)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700920
921 default_cudnn_path = environ_cp.get('CUDA_TOOLKIT_PATH')
922 ask_cudnn_path = (r'Please specify the location where cuDNN %s library is '
923 'installed. Refer to README.md for more details. [Default'
924 ' is %s]:') % (tf_cudnn_version, default_cudnn_path)
925 cudnn_install_path = get_from_env_or_user_or_default(
926 environ_cp, 'CUDNN_INSTALL_PATH', ask_cudnn_path, default_cudnn_path)
927
928 # Result returned from "read" will be used unexpanded. That make "~"
929 # unusable. Going through one more level of expansion to handle that.
930 cudnn_install_path = os.path.realpath(
931 os.path.expanduser(cudnn_install_path))
Martin Wicked57572e2017-09-02 19:21:45 -0700932 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700933 cudnn_install_path = cygpath(cudnn_install_path)
934
935 if is_windows():
936 cuda_dnn_lib_path = 'lib/x64/cudnn.lib'
937 cuda_dnn_lib_alt_path = 'lib/x64/cudnn.lib'
938 elif is_linux():
939 cuda_dnn_lib_path = 'lib64/libcudnn.so.%s' % tf_cudnn_version
940 cuda_dnn_lib_alt_path = 'libcudnn.so.%s' % tf_cudnn_version
941 elif is_macos():
942 cuda_dnn_lib_path = 'lib/libcudnn.%s.dylib' % tf_cudnn_version
943 cuda_dnn_lib_alt_path = 'libcudnn.%s.dylib' % tf_cudnn_version
944
945 cuda_dnn_lib_path_full = os.path.join(cudnn_install_path, cuda_dnn_lib_path)
946 cuda_dnn_lib_alt_path_full = os.path.join(cudnn_install_path,
947 cuda_dnn_lib_alt_path)
948 if os.path.exists(cuda_dnn_lib_path_full) or os.path.exists(
949 cuda_dnn_lib_alt_path_full):
950 break
951
952 # Try another alternative for Linux
953 if is_linux():
Jonathan Hseu008910f2017-08-25 14:01:05 -0700954 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
955 cudnn_path_from_ldconfig = run_shell([ldconfig_bin, '-p'])
956 cudnn_path_from_ldconfig = re.search('.*libcudnn.so .* => (.*)',
A. Unique TensorFlowere7223582017-09-06 17:57:04 -0700957 cudnn_path_from_ldconfig)
958 if cudnn_path_from_ldconfig:
959 cudnn_path_from_ldconfig = cudnn_path_from_ldconfig.group(1)
960 if os.path.exists('%s.%s' % (cudnn_path_from_ldconfig,
961 tf_cudnn_version)):
962 cudnn_install_path = os.path.dirname(cudnn_path_from_ldconfig)
963 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700964
965 # Reset and Retry
966 print(
967 'Invalid path to cuDNN %s toolkit. None of the following files can be '
968 'found:' % tf_cudnn_version)
969 print(cuda_dnn_lib_path_full)
970 print(cuda_dnn_lib_alt_path_full)
971 if is_linux():
972 print('%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version))
973
974 environ_cp['TF_CUDNN_VERSION'] = ''
Austin Andersonf9a88f82017-12-13 11:49:40 -0800975 else:
976 raise UserInputError('Invalid TF_CUDNN setting was provided %d '
977 'times in a row. Assuming to be a scripting mistake.' %
978 _DEFAULT_PROMPT_ASK_ATTEMPTS)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700979
980 # Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION
981 environ_cp['CUDNN_INSTALL_PATH'] = cudnn_install_path
982 write_action_env_to_bazelrc('CUDNN_INSTALL_PATH', cudnn_install_path)
983 environ_cp['TF_CUDNN_VERSION'] = tf_cudnn_version
984 write_action_env_to_bazelrc('TF_CUDNN_VERSION', tf_cudnn_version)
985
986
Guangda Lai76f69382018-01-25 23:59:19 -0800987def set_tf_tensorrt_install_path(environ_cp):
988 """Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION.
989
990 Adapted from code contributed by Sami Kama (https://github.com/samikama).
991
992 Args:
993 environ_cp: copy of the os.environ.
994
995 Raises:
996 ValueError: if this method was called under non-Linux platform.
997 UserInputError: if user has provided invalid input multiple times.
998 """
999 if not is_linux():
1000 raise ValueError('Currently TensorRT is only supported on Linux platform.')
1001
1002 # Ask user whether to add TensorRT support.
1003 if str(int(get_var(
1004 environ_cp, 'TF_NEED_TENSORRT', 'TensorRT', False))) != '1':
1005 return
1006
1007 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
1008 ask_tensorrt_path = (r'Please specify the location where TensorRT is '
1009 'installed. [Default is %s]:') % (
1010 _DEFAULT_TENSORRT_PATH_LINUX)
1011 trt_install_path = get_from_env_or_user_or_default(
1012 environ_cp, 'TENSORRT_INSTALL_PATH', ask_tensorrt_path,
1013 _DEFAULT_TENSORRT_PATH_LINUX)
1014
1015 # Result returned from "read" will be used unexpanded. That make "~"
1016 # unusable. Going through one more level of expansion to handle that.
1017 trt_install_path = os.path.realpath(
1018 os.path.expanduser(trt_install_path))
1019
1020 def find_libs(search_path):
1021 """Search for libnvinfer.so in "search_path"."""
1022 fl = set()
1023 if os.path.exists(search_path) and os.path.isdir(search_path):
1024 fl.update([os.path.realpath(os.path.join(search_path, x))
1025 for x in os.listdir(search_path) if 'libnvinfer.so' in x])
1026 return fl
1027
1028 possible_files = find_libs(trt_install_path)
1029 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib')))
1030 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib64')))
1031
1032 def is_compatible(tensorrt_lib, cuda_ver, cudnn_ver):
1033 """Check the compatibility between tensorrt and cudnn/cudart libraries."""
1034 ldd_bin = which('ldd') or '/usr/bin/ldd'
1035 ldd_out = run_shell([ldd_bin, tensorrt_lib]).split(os.linesep)
1036 cudnn_pattern = re.compile('.*libcudnn.so\\.?(.*) =>.*$')
1037 cuda_pattern = re.compile('.*libcudart.so\\.?(.*) =>.*$')
1038 cudnn = None
1039 cudart = None
1040 for line in ldd_out:
1041 if 'libcudnn.so' in line:
1042 cudnn = cudnn_pattern.search(line)
1043 elif 'libcudart.so' in line:
1044 cudart = cuda_pattern.search(line)
1045 if cudnn and len(cudnn.group(1)):
1046 cudnn = convert_version_to_int(cudnn.group(1))
1047 if cudart and len(cudart.group(1)):
1048 cudart = convert_version_to_int(cudart.group(1))
1049 return (cudnn == cudnn_ver) and (cudart == cuda_ver)
1050
1051 cuda_ver = convert_version_to_int(environ_cp['TF_CUDA_VERSION'])
1052 cudnn_ver = convert_version_to_int(environ_cp['TF_CUDNN_VERSION'])
1053 nvinfer_pattern = re.compile('.*libnvinfer.so.?(.*)$')
1054 highest_ver = [0, None, None]
1055
1056 for lib_file in possible_files:
1057 if is_compatible(lib_file, cuda_ver, cudnn_ver):
1058 ver_str = nvinfer_pattern.search(lib_file).group(1)
1059 ver = convert_version_to_int(ver_str) if len(ver_str) else 0
1060 if ver > highest_ver[0]:
1061 highest_ver = [ver, ver_str, lib_file]
1062 if highest_ver[1] is not None:
1063 trt_install_path = os.path.dirname(highest_ver[2])
1064 tf_tensorrt_version = highest_ver[1]
1065 break
1066
1067 # Try another alternative from ldconfig.
1068 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
1069 ldconfig_output = run_shell([ldconfig_bin, '-p'])
1070 search_result = re.search(
1071 '.*libnvinfer.so\\.?([0-9.]*).* => (.*)', ldconfig_output)
1072 if search_result:
1073 libnvinfer_path_from_ldconfig = search_result.group(2)
1074 if os.path.exists(libnvinfer_path_from_ldconfig):
1075 if is_compatible(libnvinfer_path_from_ldconfig, cuda_ver, cudnn_ver):
1076 trt_install_path = os.path.dirname(libnvinfer_path_from_ldconfig)
1077 tf_tensorrt_version = search_result.group(1)
1078 break
1079
1080 # Reset and Retry
1081 print('Invalid path to TensorRT. None of the following files can be found:')
1082 print(trt_install_path)
1083 print(os.path.join(trt_install_path, 'lib'))
1084 print(os.path.join(trt_install_path, 'lib64'))
1085 if search_result:
1086 print(libnvinfer_path_from_ldconfig)
1087
1088 else:
1089 raise UserInputError('Invalid TF_TENSORRT setting was provided %d '
1090 'times in a row. Assuming to be a scripting mistake.' %
1091 _DEFAULT_PROMPT_ASK_ATTEMPTS)
1092
1093 # Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION
1094 environ_cp['TENSORRT_INSTALL_PATH'] = trt_install_path
1095 write_action_env_to_bazelrc('TENSORRT_INSTALL_PATH', trt_install_path)
1096 environ_cp['TF_TENSORRT_VERSION'] = tf_tensorrt_version
1097 write_action_env_to_bazelrc('TF_TENSORRT_VERSION', tf_tensorrt_version)
1098
1099
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001100def get_native_cuda_compute_capabilities(environ_cp):
1101 """Get native cuda compute capabilities.
1102
1103 Args:
1104 environ_cp: copy of the os.environ.
1105 Returns:
1106 string of native cuda compute capabilities, separated by comma.
1107 """
1108 device_query_bin = os.path.join(
1109 environ_cp.get('CUDA_TOOLKIT_PATH'), 'extras/demo_suite/deviceQuery')
Jonathan Hseu008910f2017-08-25 14:01:05 -07001110 if os.path.isfile(device_query_bin) and os.access(device_query_bin, os.X_OK):
1111 try:
1112 output = run_shell(device_query_bin).split('\n')
1113 pattern = re.compile('[0-9]*\\.[0-9]*')
1114 output = [pattern.search(x) for x in output if 'Capability' in x]
1115 output = ','.join(x.group() for x in output if x is not None)
1116 except subprocess.CalledProcessError:
1117 output = ''
1118 else:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001119 output = ''
1120 return output
1121
1122
1123def set_tf_cuda_compute_capabilities(environ_cp):
1124 """Set TF_CUDA_COMPUTE_CAPABILITIES."""
1125 while True:
1126 native_cuda_compute_capabilities = get_native_cuda_compute_capabilities(
1127 environ_cp)
1128 if not native_cuda_compute_capabilities:
1129 default_cuda_compute_capabilities = _DEFAULT_CUDA_COMPUTE_CAPABILITIES
1130 else:
1131 default_cuda_compute_capabilities = native_cuda_compute_capabilities
1132
1133 ask_cuda_compute_capabilities = (
1134 'Please specify a list of comma-separated '
1135 'Cuda compute capabilities you want to '
1136 'build with.\nYou can find the compute '
1137 'capability of your device at: '
1138 'https://developer.nvidia.com/cuda-gpus.\nPlease'
1139 ' note that each additional compute '
1140 'capability significantly increases your '
1141 'build time and binary size. [Default is: %s]' %
1142 default_cuda_compute_capabilities)
1143 tf_cuda_compute_capabilities = get_from_env_or_user_or_default(
1144 environ_cp, 'TF_CUDA_COMPUTE_CAPABILITIES',
1145 ask_cuda_compute_capabilities, default_cuda_compute_capabilities)
1146 # Check whether all capabilities from the input is valid
1147 all_valid = True
1148 for compute_capability in tf_cuda_compute_capabilities.split(','):
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001149 m = re.match('[0-9]+.[0-9]+', compute_capability)
1150 if not m:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001151 print('Invalid compute capability: ' % compute_capability)
1152 all_valid = False
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001153 else:
1154 ver = int(m.group(0).split('.')[0])
1155 if ver < 3:
1156 print('Only compute capabilities 3.0 or higher are supported.')
1157 all_valid = False
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001158
1159 if all_valid:
1160 break
1161
1162 # Reset and Retry
1163 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = ''
1164
1165 # Set TF_CUDA_COMPUTE_CAPABILITIES
1166 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = tf_cuda_compute_capabilities
1167 write_action_env_to_bazelrc('TF_CUDA_COMPUTE_CAPABILITIES',
1168 tf_cuda_compute_capabilities)
1169
1170
1171def set_other_cuda_vars(environ_cp):
1172 """Set other CUDA related variables."""
1173 if is_windows():
1174 # The following three variables are needed for MSVC toolchain configuration
1175 # in Bazel
1176 environ_cp['CUDA_PATH'] = environ_cp.get('CUDA_TOOLKIT_PATH')
1177 environ_cp['CUDA_COMPUTE_CAPABILITIES'] = environ_cp.get(
1178 'TF_CUDA_COMPUTE_CAPABILITIES')
1179 environ_cp['NO_WHOLE_ARCHIVE_OPTION'] = 1
1180 write_action_env_to_bazelrc('CUDA_PATH', environ_cp.get('CUDA_PATH'))
1181 write_action_env_to_bazelrc('CUDA_COMPUTE_CAPABILITIE',
1182 environ_cp.get('CUDA_COMPUTE_CAPABILITIE'))
1183 write_action_env_to_bazelrc('NO_WHOLE_ARCHIVE_OPTION',
1184 environ_cp.get('NO_WHOLE_ARCHIVE_OPTION'))
1185 write_to_bazelrc('build --config=win-cuda')
1186 write_to_bazelrc('test --config=win-cuda')
1187 else:
1188 # If CUDA is enabled, always use GPU during build and test.
1189 if environ_cp.get('TF_CUDA_CLANG') == '1':
1190 write_to_bazelrc('build --config=cuda_clang')
1191 write_to_bazelrc('test --config=cuda_clang')
1192 else:
1193 write_to_bazelrc('build --config=cuda')
1194 write_to_bazelrc('test --config=cuda')
1195
1196
1197def set_host_cxx_compiler(environ_cp):
1198 """Set HOST_CXX_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001199 default_cxx_host_compiler = which('g++') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001200
Austin Anderson6afface2017-12-05 11:59:17 -08001201 host_cxx_compiler = prompt_loop_or_load_from_env(
1202 environ_cp,
1203 var_name='HOST_CXX_COMPILER',
1204 var_default=default_cxx_host_compiler,
1205 ask_for_var=('Please specify which C++ compiler should be used as the '
1206 'host C++ compiler.'),
1207 check_success=os.path.exists,
1208 error_msg='Invalid C++ compiler path. %s cannot be found.',
1209 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001210
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001211 write_action_env_to_bazelrc('HOST_CXX_COMPILER', host_cxx_compiler)
1212
1213
1214def set_host_c_compiler(environ_cp):
1215 """Set HOST_C_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001216 default_c_host_compiler = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001217
Austin Anderson6afface2017-12-05 11:59:17 -08001218 host_c_compiler = prompt_loop_or_load_from_env(
1219 environ_cp,
1220 var_name='HOST_C_COMPILER',
1221 var_default=default_c_host_compiler,
1222 ask_for_var=('Please specify which C compiler should be used as the host'
1223 'C compiler.'),
1224 check_success=os.path.exists,
1225 error_msg='Invalid C compiler path. %s cannot be found.',
1226 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001227
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001228 write_action_env_to_bazelrc('HOST_C_COMPILER', host_c_compiler)
1229
1230
1231def set_computecpp_toolkit_path(environ_cp):
1232 """Set COMPUTECPP_TOOLKIT_PATH."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001233
Austin Anderson6afface2017-12-05 11:59:17 -08001234 def toolkit_exists(toolkit_path):
1235 """Check if a computecpp toolkit path is valid."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001236 if is_linux():
1237 sycl_rt_lib_path = 'lib/libComputeCpp.so'
1238 else:
1239 sycl_rt_lib_path = ''
1240
Austin Anderson6afface2017-12-05 11:59:17 -08001241 sycl_rt_lib_path_full = os.path.join(toolkit_path,
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001242 sycl_rt_lib_path)
Austin Anderson6afface2017-12-05 11:59:17 -08001243 exists = os.path.exists(sycl_rt_lib_path_full)
1244 if not exists:
1245 print('Invalid SYCL %s library path. %s cannot be found' %
1246 (_TF_OPENCL_VERSION, sycl_rt_lib_path_full))
1247 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001248
Austin Anderson6afface2017-12-05 11:59:17 -08001249 computecpp_toolkit_path = prompt_loop_or_load_from_env(
1250 environ_cp,
1251 var_name='COMPUTECPP_TOOLKIT_PATH',
1252 var_default=_DEFAULT_COMPUTECPP_TOOLKIT_PATH,
1253 ask_for_var=(
1254 'Please specify the location where ComputeCpp for SYCL %s is '
1255 'installed.' % _TF_OPENCL_VERSION),
1256 check_success=toolkit_exists,
1257 error_msg='Invalid SYCL compiler path. %s cannot be found.',
1258 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001259
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001260 write_action_env_to_bazelrc('COMPUTECPP_TOOLKIT_PATH',
1261 computecpp_toolkit_path)
1262
Michael Cased31531a2018-01-05 14:09:41 -08001263
Dandelion Man?90e42f32017-12-15 18:15:07 -08001264def set_trisycl_include_dir(environ_cp):
Michael Cased31531a2018-01-05 14:09:41 -08001265 """Set TRISYCL_INCLUDE_DIR."""
Frank Chenc4ef9272018-01-10 11:36:52 -08001266
Dandelion Man?90e42f32017-12-15 18:15:07 -08001267 ask_trisycl_include_dir = ('Please specify the location of the triSYCL '
1268 'include directory. (Use --config=sycl_trisycl '
1269 'when building with Bazel) '
1270 '[Default is %s]: '
Michael Cased31531a2018-01-05 14:09:41 -08001271 ) % (_DEFAULT_TRISYCL_INCLUDE_DIR)
Frank Chenc4ef9272018-01-10 11:36:52 -08001272
Dandelion Man?90e42f32017-12-15 18:15:07 -08001273 while True:
1274 trisycl_include_dir = get_from_env_or_user_or_default(
Michael Cased31531a2018-01-05 14:09:41 -08001275 environ_cp, 'TRISYCL_INCLUDE_DIR', ask_trisycl_include_dir,
1276 _DEFAULT_TRISYCL_INCLUDE_DIR)
Dandelion Man?90e42f32017-12-15 18:15:07 -08001277 if os.path.exists(trisycl_include_dir):
1278 break
1279
1280 print('Invalid triSYCL include directory, %s cannot be found'
1281 % (trisycl_include_dir))
1282
1283 # Set TRISYCL_INCLUDE_DIR
1284 environ_cp['TRISYCL_INCLUDE_DIR'] = trisycl_include_dir
1285 write_action_env_to_bazelrc('TRISYCL_INCLUDE_DIR',
1286 trisycl_include_dir)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001287
Yifei Fengb1d8c592017-11-22 13:42:21 -08001288
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001289def set_mpi_home(environ_cp):
1290 """Set MPI_HOME."""
Austin Anderson6afface2017-12-05 11:59:17 -08001291
Jonathan Hseu008910f2017-08-25 14:01:05 -07001292 default_mpi_home = which('mpirun') or which('mpiexec') or ''
1293 default_mpi_home = os.path.dirname(os.path.dirname(default_mpi_home))
1294
Austin Anderson6afface2017-12-05 11:59:17 -08001295 def valid_mpi_path(mpi_home):
1296 exists = (os.path.exists(os.path.join(mpi_home, 'include')) and
1297 os.path.exists(os.path.join(mpi_home, 'lib')))
1298 if not exists:
1299 print('Invalid path to the MPI Toolkit. %s or %s cannot be found' %
1300 (os.path.join(mpi_home, 'include'),
1301 os.path.exists(os.path.join(mpi_home, 'lib'))))
1302 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001303
Austin Anderson6afface2017-12-05 11:59:17 -08001304 _ = prompt_loop_or_load_from_env(
1305 environ_cp,
1306 var_name='MPI_HOME',
1307 var_default=default_mpi_home,
1308 ask_for_var='Please specify the MPI toolkit folder.',
1309 check_success=valid_mpi_path,
1310 error_msg='',
1311 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001312
1313
1314def set_other_mpi_vars(environ_cp):
1315 """Set other MPI related variables."""
1316 # Link the MPI header files
1317 mpi_home = environ_cp.get('MPI_HOME')
1318 symlink_force('%s/include/mpi.h' % mpi_home, 'third_party/mpi/mpi.h')
1319
1320 # Determine if we use OpenMPI or MVAPICH, these require different header files
1321 # to be included here to make bazel dependency checker happy
1322 if os.path.exists(os.path.join(mpi_home, 'include/mpi_portable_platform.h')):
1323 symlink_force(
1324 os.path.join(mpi_home, 'include/mpi_portable_platform.h'),
1325 'third_party/mpi/mpi_portable_platform.h')
1326 # TODO(gunan): avoid editing files in configure
1327 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=False',
1328 'MPI_LIB_IS_OPENMPI=True')
1329 else:
1330 # MVAPICH / MPICH
1331 symlink_force(
1332 os.path.join(mpi_home, 'include/mpio.h'), 'third_party/mpi/mpio.h')
1333 symlink_force(
1334 os.path.join(mpi_home, 'include/mpicxx.h'), 'third_party/mpi/mpicxx.h')
1335 # TODO(gunan): avoid editing files in configure
1336 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=True',
1337 'MPI_LIB_IS_OPENMPI=False')
1338
1339 if os.path.exists(os.path.join(mpi_home, 'lib/libmpi.so')):
1340 symlink_force(
1341 os.path.join(mpi_home, 'lib/libmpi.so'), 'third_party/mpi/libmpi.so')
1342 else:
1343 raise ValueError('Cannot find the MPI library file in %s/lib' % mpi_home)
1344
1345
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001346def set_grpc_build_flags():
1347 write_to_bazelrc('build --define grpc_no_ares=true')
1348
Michael Cased31531a2018-01-05 14:09:41 -08001349
Dandelion Man?90e42f32017-12-15 18:15:07 -08001350def set_windows_build_flags():
1351 if is_windows():
1352 # The non-monolithic build is not supported yet
1353 write_to_bazelrc('build --config monolithic')
1354 # Suppress warning messages
1355 write_to_bazelrc('build --copt=-w --host_copt=-w')
1356 # Output more verbose information when something goes wrong
1357 write_to_bazelrc('build --verbose_failures')
1358
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001359
Michael Cased31531a2018-01-05 14:09:41 -08001360def config_info_line(name, help_text):
1361 """Helper function to print formatted help text for Bazel config options."""
1362 print('\t--config=%-12s\t# %s' % (name, help_text))
1363
1364
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001365def main():
1366 # Make a copy of os.environ to be clear when functions and getting and setting
1367 # environment variables.
1368 environ_cp = dict(os.environ)
1369
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -07001370 check_bazel_version('0.5.4')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001371
1372 reset_tf_configure_bazelrc()
1373 cleanup_makefile()
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -07001374 setup_python(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001375
1376 if is_windows():
Benoit Steiner355e25e2017-10-24 19:47:46 -07001377 environ_cp['TF_NEED_S3'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001378 environ_cp['TF_NEED_GCP'] = '0'
1379 environ_cp['TF_NEED_HDFS'] = '0'
1380 environ_cp['TF_NEED_JEMALLOC'] = '0'
Michael Cased90054e2018-02-07 14:36:00 -08001381 environ_cp['TF_NEED_KAFKA'] = '0'
Yifei Fengb1d8c592017-11-22 13:42:21 -08001382 environ_cp['TF_NEED_OPENCL_SYCL'] = '0'
1383 environ_cp['TF_NEED_COMPUTECPP'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001384 environ_cp['TF_NEED_OPENCL'] = '0'
1385 environ_cp['TF_CUDA_CLANG'] = '0'
Guangda Lai76f69382018-01-25 23:59:19 -08001386 environ_cp['TF_NEED_TENSORRT'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001387
1388 if is_macos():
1389 environ_cp['TF_NEED_JEMALLOC'] = '0'
Guangda Lai76f69382018-01-25 23:59:19 -08001390 environ_cp['TF_NEED_TENSORRT'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001391
1392 set_build_var(environ_cp, 'TF_NEED_JEMALLOC', 'jemalloc as malloc',
1393 'with_jemalloc', True)
1394 set_build_var(environ_cp, 'TF_NEED_GCP', 'Google Cloud Platform',
Benoit Steiner355e25e2017-10-24 19:47:46 -07001395 'with_gcp_support', True, 'gcp')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001396 set_build_var(environ_cp, 'TF_NEED_HDFS', 'Hadoop File System',
Benoit Steiner355e25e2017-10-24 19:47:46 -07001397 'with_hdfs_support', True, 'hdfs')
Michael Case7e4e3362017-10-09 13:31:15 -07001398 set_build_var(environ_cp, 'TF_NEED_S3', 'Amazon S3 File System',
1399 'with_s3_support', True, 's3')
Michael Cased90054e2018-02-07 14:36:00 -08001400 set_build_var(environ_cp, 'TF_NEED_KAFKA', 'Apache Kafka Platform',
1401 'with_kafka_support', False, 'kafka')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001402 set_build_var(environ_cp, 'TF_ENABLE_XLA', 'XLA JIT', 'with_xla_support',
Michael Case98850a52017-09-14 13:35:57 -07001403 False, 'xla')
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -07001404 set_build_var(environ_cp, 'TF_NEED_GDR', 'GDR', 'with_gdr_support',
Michael Case98850a52017-09-14 13:35:57 -07001405 False, 'gdr')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001406 set_build_var(environ_cp, 'TF_NEED_VERBS', 'VERBS', 'with_verbs_support',
Michael Case98850a52017-09-14 13:35:57 -07001407 False, 'verbs')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001408
Yifei Fengb1d8c592017-11-22 13:42:21 -08001409 set_action_env_var(environ_cp, 'TF_NEED_OPENCL_SYCL', 'OpenCL SYCL', False)
1410 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001411 set_host_cxx_compiler(environ_cp)
1412 set_host_c_compiler(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001413 set_action_env_var(environ_cp, 'TF_NEED_COMPUTECPP', 'ComputeCPP', True)
1414 if environ_cp.get('TF_NEED_COMPUTECPP') == '1':
1415 set_computecpp_toolkit_path(environ_cp)
1416 else:
1417 set_trisycl_include_dir(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001418
1419 set_action_env_var(environ_cp, 'TF_NEED_CUDA', 'CUDA', False)
A. Unique TensorFlower24cbb2a2017-09-08 07:45:44 -07001420 if (environ_cp.get('TF_NEED_CUDA') == '1' and
1421 'TF_CUDA_CONFIG_REPO' not in environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001422 set_tf_cuda_version(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001423 set_tf_cudnn_version(environ_cp)
Guangda Lai76f69382018-01-25 23:59:19 -08001424 if is_linux():
1425 set_tf_tensorrt_install_path(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001426 set_tf_cuda_compute_capabilities(environ_cp)
Ankur Taly0e6f39d2018-02-16 18:22:55 -08001427 if 'LD_LIBRARY_PATH' in environ_cp and environ_cp.get(
1428 'LD_LIBRARY_PATH') != '1':
1429 write_action_env_to_bazelrc('LD_LIBRARY_PATH',
1430 environ_cp.get('LD_LIBRARY_PATH'))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001431
1432 set_tf_cuda_clang(environ_cp)
1433 if environ_cp.get('TF_CUDA_CLANG') == '1':
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -08001434 if not is_windows():
1435 # Ask if we want to download clang release while building.
1436 set_tf_download_clang(environ_cp)
1437 else:
1438 # We use bazel's generated crosstool on Windows and there is no
1439 # way to provide downloaded toolchain for that yet.
1440 # TODO(ibiryukov): Investigate using clang as a cuda compiler on
1441 # Windows.
1442 environ_cp['TF_DOWNLOAD_CLANG'] = '0'
1443
1444 if environ_cp.get('TF_DOWNLOAD_CLANG') != '1':
1445 # Set up which clang we should use as the cuda / host compiler.
1446 set_clang_cuda_compiler_path(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001447 else:
1448 # Set up which gcc nvcc should use as the host compiler
1449 # No need to set this on Windows
1450 if not is_windows():
1451 set_gcc_host_compiler_path(environ_cp)
1452 set_other_cuda_vars(environ_cp)
1453
1454 set_build_var(environ_cp, 'TF_NEED_MPI', 'MPI', 'with_mpi_support', False)
1455 if environ_cp.get('TF_NEED_MPI') == '1':
1456 set_mpi_home(environ_cp)
1457 set_other_mpi_vars(environ_cp)
1458
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001459 set_grpc_build_flags()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001460 set_cc_opt_flags(environ_cp)
Dandelion Man?90e42f32017-12-15 18:15:07 -08001461 set_windows_build_flags()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001462
Austin Anderson6afface2017-12-05 11:59:17 -08001463 if workspace_has_any_android_rule():
1464 print('The WORKSPACE file has at least one of ["android_sdk_repository", '
1465 '"android_ndk_repository"] already set. Will not ask to help '
1466 'configure the WORKSPACE. Please delete the existing rules to '
1467 'activate the helper.\n')
1468 else:
1469 if get_var(
1470 environ_cp, 'TF_SET_ANDROID_WORKSPACE', 'android workspace',
1471 False,
1472 ('Would you like to interactively configure ./WORKSPACE for '
1473 'Android builds?'),
1474 'Searching for NDK and SDK installations.',
1475 'Not configuring the WORKSPACE for Android builds.'):
1476 create_android_ndk_rule(environ_cp)
1477 create_android_sdk_rule(environ_cp)
1478
Michael Cased31531a2018-01-05 14:09:41 -08001479 print('Preconfigured Bazel build configs. You can use any of the below by '
1480 'adding "--config=<>" to your build command. See tools/bazel.rc for '
1481 'more details.')
1482 config_info_line('mkl', 'Build with MKL support.')
1483 config_info_line('monolithic', 'Config for mostly static monolithic build.')
Guangda Lai76f69382018-01-25 23:59:19 -08001484 config_info_line('tensorrt', 'Build with TensorRT support.')
Austin Anderson6afface2017-12-05 11:59:17 -08001485
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001486if __name__ == '__main__':
1487 main()