blob: 3a7999fbd65cde41f8fa9c61ef65130db01dae01 [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
Shanqing Cai71445712018-03-12 19:33:52 -070021import argparse
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070022import errno
23import os
24import platform
25import re
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070026import subprocess
27import sys
28
Andrew Sellec9885ea2017-11-06 09:37:03 -080029# pylint: disable=g-import-not-at-top
Jonathan Hseu008910f2017-08-25 14:01:05 -070030try:
31 from shutil import which
32except ImportError:
33 from distutils.spawn import find_executable as which
Andrew Sellec9885ea2017-11-06 09:37:03 -080034# pylint: enable=g-import-not-at-top
Jonathan Hseu008910f2017-08-25 14:01:05 -070035
Dandelion Man?90e42f32017-12-15 18:15:07 -080036_DEFAULT_CUDA_VERSION = '9.0'
37_DEFAULT_CUDNN_VERSION = '7'
Smit Hinsufe7d1d92018-07-14 13:16:58 -070038_DEFAULT_CUDA_COMPUTE_CAPABILITIES = '3.5,7.0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070039_DEFAULT_CUDA_PATH = '/usr/local/cuda'
40_DEFAULT_CUDA_PATH_LINUX = '/opt/cuda'
41_DEFAULT_CUDA_PATH_WIN = ('C:/Program Files/NVIDIA GPU Computing '
42 'Toolkit/CUDA/v%s' % _DEFAULT_CUDA_VERSION)
43_TF_OPENCL_VERSION = '1.2'
44_DEFAULT_COMPUTECPP_TOOLKIT_PATH = '/usr/local/computecpp'
Yifei Fengb1d8c592017-11-22 13:42:21 -080045_DEFAULT_TRISYCL_INCLUDE_DIR = '/usr/local/triSYCL/include'
A. Unique TensorFlower82820ef2018-11-12 13:22:13 -080046_SUPPORTED_ANDROID_NDK_VERSIONS = [10, 11, 12, 13, 14, 15, 16, 17, 18]
Austin Anderson6afface2017-12-05 11:59:17 -080047
48_DEFAULT_PROMPT_ASK_ATTEMPTS = 10
49
Shanqing Cai71445712018-03-12 19:33:52 -070050_TF_BAZELRC_FILENAME = '.tf_configure.bazelrc'
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -070051_TF_WORKSPACE_ROOT = ''
52_TF_BAZELRC = ''
Shanqing Cai71445712018-03-12 19:33:52 -070053
Jason Furmanek7c234152018-09-26 04:44:12 +000054NCCL_LIB_PATHS = [
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -070055 'lib64/', 'lib/powerpc64le-linux-gnu/', 'lib/x86_64-linux-gnu/', ''
Jason Furmanek7c234152018-09-26 04:44:12 +000056]
Austin Anderson6afface2017-12-05 11:59:17 -080057
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -070058if platform.machine() == 'ppc64le':
59 _DEFAULT_TENSORRT_PATH_LINUX = '/usr/lib/powerpc64le-linux-gnu/'
60else:
61 _DEFAULT_TENSORRT_PATH_LINUX = '/usr/lib/%s-linux-gnu' % platform.machine()
62
Austin Anderson6afface2017-12-05 11:59:17 -080063
64class UserInputError(Exception):
65 pass
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070066
67
68def is_windows():
69 return platform.system() == 'Windows'
70
71
72def is_linux():
73 return platform.system() == 'Linux'
74
75
76def is_macos():
77 return platform.system() == 'Darwin'
78
79
80def is_ppc64le():
81 return platform.machine() == 'ppc64le'
82
83
Jonathan Hseu008910f2017-08-25 14:01:05 -070084def is_cygwin():
85 return platform.system().startswith('CYGWIN_NT')
86
87
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070088def get_input(question):
89 try:
90 try:
91 answer = raw_input(question)
92 except NameError:
93 answer = input(question) # pylint: disable=bad-builtin
94 except EOFError:
95 answer = ''
96 return answer
97
98
99def symlink_force(target, link_name):
100 """Force symlink, equivalent of 'ln -sf'.
101
102 Args:
103 target: items to link to.
104 link_name: name of the link.
105 """
106 try:
107 os.symlink(target, link_name)
108 except OSError as e:
109 if e.errno == errno.EEXIST:
110 os.remove(link_name)
111 os.symlink(target, link_name)
112 else:
113 raise e
114
115
116def sed_in_place(filename, old, new):
117 """Replace old string with new string in file.
118
119 Args:
120 filename: string for filename.
121 old: string to replace.
122 new: new string to replace to.
123 """
124 with open(filename, 'r') as f:
125 filedata = f.read()
126 newdata = filedata.replace(old, new)
127 with open(filename, 'w') as f:
128 f.write(newdata)
129
130
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700131def write_to_bazelrc(line):
132 with open(_TF_BAZELRC, 'a') as f:
133 f.write(line + '\n')
134
135
136def write_action_env_to_bazelrc(var_name, var):
137 write_to_bazelrc('build --action_env %s="%s"' % (var_name, str(var)))
138
139
Jonathan Hseu008910f2017-08-25 14:01:05 -0700140def run_shell(cmd, allow_non_zero=False):
141 if allow_non_zero:
142 try:
143 output = subprocess.check_output(cmd)
144 except subprocess.CalledProcessError as e:
145 output = e.output
146 else:
147 output = subprocess.check_output(cmd)
148 return output.decode('UTF-8').strip()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700149
150
151def cygpath(path):
152 """Convert path from posix to windows."""
Martin Wicked57572e2017-09-02 19:21:45 -0700153 return os.path.abspath(path).replace('\\', '/')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700154
155
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700156def get_python_path(environ_cp, python_bin_path):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700157 """Get the python site package paths."""
158 python_paths = []
159 if environ_cp.get('PYTHONPATH'):
160 python_paths = environ_cp.get('PYTHONPATH').split(':')
161 try:
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700162 library_paths = run_shell([
163 python_bin_path, '-c',
164 'import site; print("\\n".join(site.getsitepackages()))'
165 ]).split('\n')
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700166 except subprocess.CalledProcessError:
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700167 library_paths = [
168 run_shell([
169 python_bin_path, '-c',
170 'from distutils.sysconfig import get_python_lib;'
171 'print(get_python_lib())'
172 ])
173 ]
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700174
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700175 all_paths = set(python_paths + library_paths)
176
177 paths = []
178 for path in all_paths:
179 if os.path.isdir(path):
180 paths.append(path)
181 return paths
182
183
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700184def get_python_major_version(python_bin_path):
185 """Get the python major version."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700186 return run_shell([python_bin_path, '-c', 'import sys; print(sys.version[0])'])
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700187
188
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700189def setup_python(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700190 """Setup python related env variables."""
191 # Get PYTHON_BIN_PATH, default is the current running python.
192 default_python_bin_path = sys.executable
193 ask_python_bin_path = ('Please specify the location of python. [Default is '
194 '%s]: ') % default_python_bin_path
195 while True:
196 python_bin_path = get_from_env_or_user_or_default(
197 environ_cp, 'PYTHON_BIN_PATH', ask_python_bin_path,
198 default_python_bin_path)
199 # Check if the path is valid
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700200 if os.path.isfile(python_bin_path) and os.access(python_bin_path, os.X_OK):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700201 break
202 elif not os.path.exists(python_bin_path):
203 print('Invalid python path: %s cannot be found.' % python_bin_path)
204 else:
205 print('%s is not executable. Is it the python binary?' % python_bin_path)
206 environ_cp['PYTHON_BIN_PATH'] = ''
207
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700208 # Convert python path to Windows style before checking lib and version
Martin Wicked57572e2017-09-02 19:21:45 -0700209 if is_windows() or is_cygwin():
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700210 python_bin_path = cygpath(python_bin_path)
211
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700212 # Get PYTHON_LIB_PATH
213 python_lib_path = environ_cp.get('PYTHON_LIB_PATH')
214 if not python_lib_path:
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700215 python_lib_paths = get_python_path(environ_cp, python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700216 if environ_cp.get('USE_DEFAULT_PYTHON_LIB_PATH') == '1':
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700217 python_lib_path = python_lib_paths[0]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700218 else:
Jonathan Hseu008910f2017-08-25 14:01:05 -0700219 print('Found possible Python library paths:\n %s' %
220 '\n '.join(python_lib_paths))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700221 default_python_lib_path = python_lib_paths[0]
222 python_lib_path = get_input(
Jonathan Hseu008910f2017-08-25 14:01:05 -0700223 'Please input the desired Python library path to use. '
224 'Default is [%s]\n' % python_lib_paths[0])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700225 if not python_lib_path:
226 python_lib_path = default_python_lib_path
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700227 environ_cp['PYTHON_LIB_PATH'] = python_lib_path
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700228
TensorFlower Gardener61a87202018-10-01 12:25:39 -0700229 _ = get_python_major_version(python_bin_path)
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700230
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700231 # Convert python path to Windows style before writing into bazel.rc
Martin Wicked57572e2017-09-02 19:21:45 -0700232 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700233 python_lib_path = cygpath(python_lib_path)
234
235 # Set-up env variables used by python_configure.bzl
236 write_action_env_to_bazelrc('PYTHON_BIN_PATH', python_bin_path)
237 write_action_env_to_bazelrc('PYTHON_LIB_PATH', python_lib_path)
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700238 write_to_bazelrc('build --python_path=\"%s"' % python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700239 environ_cp['PYTHON_BIN_PATH'] = python_bin_path
240
William D. Ironsdcc76a52018-11-20 10:35:18 -0600241 # If choosen python_lib_path is from a path specified in the PYTHONPATH
242 # variable, need to tell bazel to include PYTHONPATH
243 if environ_cp.get('PYTHONPATH'):
244 python_paths = environ_cp.get('PYTHONPATH').split(':')
245 if python_lib_path in python_paths:
TensorFlower Gardener968cd182018-11-28 11:33:16 -0800246 write_action_env_to_bazelrc('PYTHONPATH', environ_cp.get('PYTHONPATH'))
William D. Ironsdcc76a52018-11-20 10:35:18 -0600247
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700248 # Write tools/python_bin_path.sh
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700249 with open(
250 os.path.join(_TF_WORKSPACE_ROOT, 'tools', 'python_bin_path.sh'),
251 'w') as f:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700252 f.write('export PYTHON_BIN_PATH="%s"' % python_bin_path)
253
254
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -0700255def reset_tf_configure_bazelrc():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700256 """Reset file that contains customized config settings."""
257 open(_TF_BAZELRC, 'w').close()
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -0700258 bazelrc_path = os.path.join(_TF_WORKSPACE_ROOT, '.bazelrc')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700259
Shanqing Cai71445712018-03-12 19:33:52 -0700260 data = []
261 if os.path.exists(bazelrc_path):
262 with open(bazelrc_path, 'r') as f:
263 data = f.read().splitlines()
264 with open(bazelrc_path, 'w') as f:
265 for l in data:
266 if _TF_BAZELRC_FILENAME in l:
267 continue
268 f.write('%s\n' % l)
Jason Zamand3f6b722018-08-04 14:28:02 +0800269 f.write('import %%workspace%%/%s\n' % _TF_BAZELRC_FILENAME)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700270
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700271def cleanup_makefile():
272 """Delete any leftover BUILD files from the Makefile build.
273
274 These files could interfere with Bazel parsing.
275 """
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700276 makefile_download_dir = os.path.join(_TF_WORKSPACE_ROOT, 'tensorflow',
277 'contrib', 'makefile', 'downloads')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700278 if os.path.isdir(makefile_download_dir):
279 for root, _, filenames in os.walk(makefile_download_dir):
280 for f in filenames:
281 if f.endswith('BUILD'):
282 os.remove(os.path.join(root, f))
283
284
285def get_var(environ_cp,
286 var_name,
287 query_item,
288 enabled_by_default,
289 question=None,
290 yes_reply=None,
291 no_reply=None):
292 """Get boolean input from user.
293
294 If var_name is not set in env, ask user to enable query_item or not. If the
295 response is empty, use the default.
296
297 Args:
298 environ_cp: copy of the os.environ.
299 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
300 query_item: string for feature related to the variable, e.g. "Hadoop File
301 System".
302 enabled_by_default: boolean for default behavior.
303 question: optional string for how to ask for user input.
Michael Cased90054e2018-02-07 14:36:00 -0800304 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700305 no_reply: optional string for reply when feature is disabled.
306
307 Returns:
308 boolean value of the variable.
Frank Chenc4ef9272018-01-10 11:36:52 -0800309
310 Raises:
311 UserInputError: if an environment variable is set, but it cannot be
312 interpreted as a boolean indicator, assume that the user has made a
313 scripting error, and will continue to provide invalid input.
314 Raise the error to avoid infinitely looping.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700315 """
316 if not question:
317 question = 'Do you wish to build TensorFlow with %s support?' % query_item
318 if not yes_reply:
319 yes_reply = '%s support will be enabled for TensorFlow.' % query_item
320 if not no_reply:
321 no_reply = 'No %s' % yes_reply
322
323 yes_reply += '\n'
324 no_reply += '\n'
325
326 if enabled_by_default:
327 question += ' [Y/n]: '
328 else:
329 question += ' [y/N]: '
330
331 var = environ_cp.get(var_name)
Frank Chenc4ef9272018-01-10 11:36:52 -0800332 if var is not None:
333 var_content = var.strip().lower()
334 true_strings = ('1', 't', 'true', 'y', 'yes')
335 false_strings = ('0', 'f', 'false', 'n', 'no')
336 if var_content in true_strings:
337 var = True
338 elif var_content in false_strings:
339 var = False
340 else:
341 raise UserInputError(
342 'Environment variable %s must be set as a boolean indicator.\n'
343 'The following are accepted as TRUE : %s.\n'
344 'The following are accepted as FALSE: %s.\n'
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700345 'Current value is %s.' % (var_name, ', '.join(true_strings),
346 ', '.join(false_strings), var))
Frank Chenc4ef9272018-01-10 11:36:52 -0800347
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700348 while var is None:
349 user_input_origin = get_input(question)
350 user_input = user_input_origin.strip().lower()
351 if user_input == 'y':
352 print(yes_reply)
353 var = True
354 elif user_input == 'n':
355 print(no_reply)
356 var = False
357 elif not user_input:
358 if enabled_by_default:
359 print(yes_reply)
360 var = True
361 else:
362 print(no_reply)
363 var = False
364 else:
365 print('Invalid selection: %s' % user_input_origin)
366 return var
367
368
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700369def set_build_var(environ_cp,
370 var_name,
371 query_item,
372 option_name,
373 enabled_by_default,
374 bazel_config_name=None):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700375 """Set if query_item will be enabled for the build.
376
377 Ask user if query_item will be enabled. Default is used if no input is given.
378 Set subprocess environment variable and write to .bazelrc if enabled.
379
380 Args:
381 environ_cp: copy of the os.environ.
382 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
383 query_item: string for feature related to the variable, e.g. "Hadoop File
384 System".
385 option_name: string for option to define in .bazelrc.
386 enabled_by_default: boolean for default behavior.
Michael Case98850a52017-09-14 13:35:57 -0700387 bazel_config_name: Name for Bazel --config argument to enable build feature.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700388 """
389
390 var = str(int(get_var(environ_cp, var_name, query_item, enabled_by_default)))
391 environ_cp[var_name] = var
392 if var == '1':
Yifei Fengec451f52018-10-05 12:53:50 -0700393 write_to_bazelrc(
394 'build:%s --define %s=true' % (bazel_config_name, option_name))
395 write_to_bazelrc('build --config=%s' % bazel_config_name)
Michael Case98850a52017-09-14 13:35:57 -0700396 elif bazel_config_name is not None:
397 # TODO(mikecase): Migrate all users of configure.py to use --config Bazel
398 # options and not to set build configs through environment variables.
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700399 write_to_bazelrc(
400 'build:%s --define %s=true' % (bazel_config_name, option_name))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700401
402
403def set_action_env_var(environ_cp,
404 var_name,
405 query_item,
406 enabled_by_default,
407 question=None,
408 yes_reply=None,
409 no_reply=None):
410 """Set boolean action_env variable.
411
412 Ask user if query_item will be enabled. Default is used if no input is given.
413 Set environment variable and write to .bazelrc.
414
415 Args:
416 environ_cp: copy of the os.environ.
417 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
418 query_item: string for feature related to the variable, e.g. "Hadoop File
419 System".
420 enabled_by_default: boolean for default behavior.
421 question: optional string for how to ask for user input.
Michael Cased90054e2018-02-07 14:36:00 -0800422 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700423 no_reply: optional string for reply when feature is disabled.
424 """
425 var = int(
426 get_var(environ_cp, var_name, query_item, enabled_by_default, question,
427 yes_reply, no_reply))
428
429 write_action_env_to_bazelrc(var_name, var)
430 environ_cp[var_name] = str(var)
431
432
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700433def convert_version_to_int(version):
434 """Convert a version number to a integer that can be used to compare.
435
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700436 Version strings of the form X.YZ and X.Y.Z-xxxxx are supported. The
437 'xxxxx' part, for instance 'homebrew' on OS/X, is ignored.
438
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700439 Args:
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700440 version: a version to be converted
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700441
442 Returns:
443 An integer if converted successfully, otherwise return None.
444 """
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700445 version = version.split('-')[0]
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700446 version_segments = version.split('.')
447 for seg in version_segments:
448 if not seg.isdigit():
449 return None
450
451 version_str = ''.join(['%03d' % int(seg) for seg in version_segments])
452 return int(version_str)
453
454
Mihai Maruseace7a123f2018-11-30 13:33:25 -0800455def check_bazel_version(min_version, max_version):
456 """Check installed bazel version is between min_version and max_version.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700457
458 Args:
459 min_version: string for minimum bazel version.
Mihai Maruseace7a123f2018-11-30 13:33:25 -0800460 max_version: string for maximum bazel version.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700461
462 Returns:
463 The bazel version detected.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700464 """
Jonathan Hseu008910f2017-08-25 14:01:05 -0700465 if which('bazel') is None:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700466 print('Cannot find bazel. Please install bazel.')
467 sys.exit(0)
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700468 curr_version = run_shell(
469 ['bazel', '--batch', '--bazelrc=/dev/null', 'version'])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700470
471 for line in curr_version.split('\n'):
472 if 'Build label: ' in line:
473 curr_version = line.split('Build label: ')[1]
474 break
475
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700476 min_version_int = convert_version_to_int(min_version)
477 curr_version_int = convert_version_to_int(curr_version)
Mihai Maruseace7a123f2018-11-30 13:33:25 -0800478 max_version_int = convert_version_to_int(max_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700479
480 # Check if current bazel version can be detected properly.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700481 if not curr_version_int:
482 print('WARNING: current bazel installation is not a release version.')
483 print('Make sure you are running at least bazel %s' % min_version)
484 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700485
Michael Cased94271a2017-08-22 17:26:52 -0700486 print('You have bazel %s installed.' % curr_version)
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700487
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700488 if curr_version_int < min_version_int:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700489 print('Please upgrade your bazel installation to version %s or higher to '
490 'build TensorFlow!' % min_version)
491 sys.exit(0)
Mihai Maruseace7a123f2018-11-30 13:33:25 -0800492 if curr_version_int > max_version_int:
493 print('Please downgrade your bazel installation to version %s or lower to '
Mihai Maruseac3360c722018-12-03 10:41:16 -0800494 'build TensorFlow!' % max_version)
Mihai Maruseace7a123f2018-11-30 13:33:25 -0800495 sys.exit(0)
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700496 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700497
498
499def set_cc_opt_flags(environ_cp):
500 """Set up architecture-dependent optimization flags.
501
502 Also append CC optimization flags to bazel.rc..
503
504 Args:
505 environ_cp: copy of the os.environ.
506 """
507 if is_ppc64le():
508 # gcc on ppc64le does not support -march, use mcpu instead
509 default_cc_opt_flags = '-mcpu=native'
A. Unique TensorFlower1bba94a2018-04-04 15:45:20 -0700510 elif is_windows():
511 default_cc_opt_flags = '/arch:AVX'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700512 else:
Justin Lebar9ef04f52018-10-10 18:52:45 -0700513 default_cc_opt_flags = '-march=native -Wno-sign-compare'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700514 question = ('Please specify optimization flags to use during compilation when'
515 ' bazel option "--config=opt" is specified [Default is %s]: '
516 ) % default_cc_opt_flags
517 cc_opt_flags = get_from_env_or_user_or_default(environ_cp, 'CC_OPT_FLAGS',
518 question, default_cc_opt_flags)
519 for opt in cc_opt_flags.split():
Michael Case00177422017-11-10 13:14:03 -0800520 write_to_bazelrc('build:opt --copt=%s' % opt)
521 # It should be safe on the same build host.
A. Unique TensorFlower1bba94a2018-04-04 15:45:20 -0700522 if not is_ppc64le() and not is_windows():
Shanqing Cai71445712018-03-12 19:33:52 -0700523 write_to_bazelrc('build:opt --host_copt=-march=native')
Michael Casebb3355d2017-11-09 08:46:31 -0800524 write_to_bazelrc('build:opt --define with_default_optimizations=true')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700525
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700526
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700527def set_tf_cuda_clang(environ_cp):
528 """set TF_CUDA_CLANG action_env.
529
530 Args:
531 environ_cp: copy of the os.environ.
532 """
533 question = 'Do you want to use clang as CUDA compiler?'
534 yes_reply = 'Clang will be used as CUDA compiler.'
535 no_reply = 'nvcc will be used as CUDA compiler.'
536 set_action_env_var(
537 environ_cp,
538 'TF_CUDA_CLANG',
539 None,
540 False,
541 question=question,
542 yes_reply=yes_reply,
543 no_reply=no_reply)
544
545
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800546def set_tf_download_clang(environ_cp):
547 """Set TF_DOWNLOAD_CLANG action_env."""
Ilya Biryukov9e651e42018-03-22 05:33:42 -0700548 question = 'Do you wish to download a fresh release of clang? (Experimental)'
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800549 yes_reply = 'Clang will be downloaded and used to compile tensorflow.'
550 no_reply = 'Clang will not be downloaded.'
551 set_action_env_var(
552 environ_cp,
553 'TF_DOWNLOAD_CLANG',
554 None,
555 False,
556 question=question,
557 yes_reply=yes_reply,
558 no_reply=no_reply)
559
560
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700561def get_from_env_or_user_or_default(environ_cp, var_name, ask_for_var,
562 var_default):
563 """Get var_name either from env, or user or default.
564
565 If var_name has been set as environment variable, use the preset value, else
566 ask for user input. If no input is provided, the default is used.
567
568 Args:
569 environ_cp: copy of the os.environ.
570 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
571 ask_for_var: string for how to ask for user input.
572 var_default: default value string.
573
574 Returns:
575 string value for var_name
576 """
577 var = environ_cp.get(var_name)
578 if not var:
579 var = get_input(ask_for_var)
Michael Cased94271a2017-08-22 17:26:52 -0700580 print('\n')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700581 if not var:
582 var = var_default
583 return var
584
585
586def set_clang_cuda_compiler_path(environ_cp):
587 """Set CLANG_CUDA_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700588 default_clang_path = which('clang') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700589 ask_clang_path = ('Please specify which clang should be used as device and '
590 'host compiler. [Default is %s]: ') % default_clang_path
591
592 while True:
593 clang_cuda_compiler_path = get_from_env_or_user_or_default(
594 environ_cp, 'CLANG_CUDA_COMPILER_PATH', ask_clang_path,
595 default_clang_path)
596 if os.path.exists(clang_cuda_compiler_path):
597 break
598
599 # Reset and retry
600 print('Invalid clang path: %s cannot be found.' % clang_cuda_compiler_path)
601 environ_cp['CLANG_CUDA_COMPILER_PATH'] = ''
602
603 # Set CLANG_CUDA_COMPILER_PATH
604 environ_cp['CLANG_CUDA_COMPILER_PATH'] = clang_cuda_compiler_path
605 write_action_env_to_bazelrc('CLANG_CUDA_COMPILER_PATH',
606 clang_cuda_compiler_path)
607
608
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700609def prompt_loop_or_load_from_env(environ_cp,
610 var_name,
611 var_default,
612 ask_for_var,
613 check_success,
614 error_msg,
615 suppress_default_error=False,
616 n_ask_attempts=_DEFAULT_PROMPT_ASK_ATTEMPTS):
Austin Anderson6afface2017-12-05 11:59:17 -0800617 """Loop over user prompts for an ENV param until receiving a valid response.
618
619 For the env param var_name, read from the environment or verify user input
620 until receiving valid input. When done, set var_name in the environ_cp to its
621 new value.
622
623 Args:
624 environ_cp: (Dict) copy of the os.environ.
625 var_name: (String) string for name of environment variable, e.g. "TF_MYVAR".
626 var_default: (String) default value string.
627 ask_for_var: (String) string for how to ask for user input.
628 check_success: (Function) function that takes one argument and returns a
629 boolean. Should return True if the value provided is considered valid. May
630 contain a complex error message if error_msg does not provide enough
631 information. In that case, set suppress_default_error to True.
632 error_msg: (String) String with one and only one '%s'. Formatted with each
633 invalid response upon check_success(input) failure.
634 suppress_default_error: (Bool) Suppress the above error message in favor of
635 one from the check_success function.
636 n_ask_attempts: (Integer) Number of times to query for valid input before
637 raising an error and quitting.
638
639 Returns:
640 [String] The value of var_name after querying for input.
641
642 Raises:
643 UserInputError: if a query has been attempted n_ask_attempts times without
Frank Chenc4ef9272018-01-10 11:36:52 -0800644 success, assume that the user has made a scripting error, and will
645 continue to provide invalid input. Raise the error to avoid infinitely
646 looping.
Austin Anderson6afface2017-12-05 11:59:17 -0800647 """
648 default = environ_cp.get(var_name) or var_default
649 full_query = '%s [Default is %s]: ' % (
650 ask_for_var,
651 default,
652 )
653
654 for _ in range(n_ask_attempts):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700655 val = get_from_env_or_user_or_default(environ_cp, var_name, full_query,
Austin Anderson6afface2017-12-05 11:59:17 -0800656 default)
657 if check_success(val):
658 break
659 if not suppress_default_error:
660 print(error_msg % val)
661 environ_cp[var_name] = ''
662 else:
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700663 raise UserInputError(
664 'Invalid %s setting was provided %d times in a row. '
665 'Assuming to be a scripting mistake.' % (var_name, n_ask_attempts))
Austin Anderson6afface2017-12-05 11:59:17 -0800666
667 environ_cp[var_name] = val
668 return val
669
670
671def create_android_ndk_rule(environ_cp):
672 """Set ANDROID_NDK_HOME and write Android NDK WORKSPACE rule."""
673 if is_windows() or is_cygwin():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700674 default_ndk_path = cygpath(
675 '%s/Android/Sdk/ndk-bundle' % environ_cp['APPDATA'])
Austin Anderson6afface2017-12-05 11:59:17 -0800676 elif is_macos():
677 default_ndk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
678 else:
679 default_ndk_path = '%s/Android/Sdk/ndk-bundle' % environ_cp['HOME']
680
681 def valid_ndk_path(path):
682 return (os.path.exists(path) and
683 os.path.exists(os.path.join(path, 'source.properties')))
684
685 android_ndk_home_path = prompt_loop_or_load_from_env(
686 environ_cp,
687 var_name='ANDROID_NDK_HOME',
688 var_default=default_ndk_path,
689 ask_for_var='Please specify the home path of the Android NDK to use.',
690 check_success=valid_ndk_path,
691 error_msg=('The path %s or its child file "source.properties" '
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700692 'does not exist.'))
Michael Case51053502018-06-05 17:47:19 -0700693 write_action_env_to_bazelrc('ANDROID_NDK_HOME', android_ndk_home_path)
694 write_action_env_to_bazelrc('ANDROID_NDK_API_LEVEL',
695 check_ndk_level(android_ndk_home_path))
Austin Anderson6afface2017-12-05 11:59:17 -0800696
697
698def create_android_sdk_rule(environ_cp):
699 """Set Android variables and write Android SDK WORKSPACE rule."""
700 if is_windows() or is_cygwin():
701 default_sdk_path = cygpath('%s/Android/Sdk' % environ_cp['APPDATA'])
702 elif is_macos():
Shashi Shekharc0ff0cc2018-07-17 09:00:24 -0700703 default_sdk_path = '%s/library/Android/Sdk' % environ_cp['HOME']
Austin Anderson6afface2017-12-05 11:59:17 -0800704 else:
705 default_sdk_path = '%s/Android/Sdk' % environ_cp['HOME']
706
707 def valid_sdk_path(path):
708 return (os.path.exists(path) and
709 os.path.exists(os.path.join(path, 'platforms')) and
710 os.path.exists(os.path.join(path, 'build-tools')))
711
712 android_sdk_home_path = prompt_loop_or_load_from_env(
713 environ_cp,
714 var_name='ANDROID_SDK_HOME',
715 var_default=default_sdk_path,
716 ask_for_var='Please specify the home path of the Android SDK to use.',
717 check_success=valid_sdk_path,
718 error_msg=('Either %s does not exist, or it does not contain the '
719 'subdirectories "platforms" and "build-tools".'))
720
721 platforms = os.path.join(android_sdk_home_path, 'platforms')
722 api_levels = sorted(os.listdir(platforms))
723 api_levels = [x.replace('android-', '') for x in api_levels]
724
725 def valid_api_level(api_level):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700726 return os.path.exists(
727 os.path.join(android_sdk_home_path, 'platforms',
728 'android-' + api_level))
Austin Anderson6afface2017-12-05 11:59:17 -0800729
730 android_api_level = prompt_loop_or_load_from_env(
731 environ_cp,
732 var_name='ANDROID_API_LEVEL',
733 var_default=api_levels[-1],
734 ask_for_var=('Please specify the Android SDK API level to use. '
735 '[Available levels: %s]') % api_levels,
736 check_success=valid_api_level,
737 error_msg='Android-%s is not present in the SDK path.')
738
739 build_tools = os.path.join(android_sdk_home_path, 'build-tools')
740 versions = sorted(os.listdir(build_tools))
741
742 def valid_build_tools(version):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700743 return os.path.exists(
744 os.path.join(android_sdk_home_path, 'build-tools', version))
Austin Anderson6afface2017-12-05 11:59:17 -0800745
746 android_build_tools_version = prompt_loop_or_load_from_env(
747 environ_cp,
748 var_name='ANDROID_BUILD_TOOLS_VERSION',
749 var_default=versions[-1],
750 ask_for_var=('Please specify an Android build tools version to use. '
751 '[Available versions: %s]') % versions,
752 check_success=valid_build_tools,
753 error_msg=('The selected SDK does not have build-tools version %s '
754 'available.'))
755
Michael Case51053502018-06-05 17:47:19 -0700756 write_action_env_to_bazelrc('ANDROID_BUILD_TOOLS_VERSION',
757 android_build_tools_version)
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700758 write_action_env_to_bazelrc('ANDROID_SDK_API_LEVEL', android_api_level)
759 write_action_env_to_bazelrc('ANDROID_SDK_HOME', android_sdk_home_path)
Austin Anderson6afface2017-12-05 11:59:17 -0800760
761
762def check_ndk_level(android_ndk_home_path):
763 """Check the revision number of an Android NDK path."""
764 properties_path = '%s/source.properties' % android_ndk_home_path
765 if is_windows() or is_cygwin():
766 properties_path = cygpath(properties_path)
767 with open(properties_path, 'r') as f:
768 filedata = f.read()
769
770 revision = re.search(r'Pkg.Revision = (\d+)', filedata)
771 if revision:
Michael Case51053502018-06-05 17:47:19 -0700772 ndk_api_level = revision.group(1)
773 else:
774 raise Exception('Unable to parse NDK revision.')
775 if int(ndk_api_level) not in _SUPPORTED_ANDROID_NDK_VERSIONS:
776 print('WARNING: The API level of the NDK in %s is %s, which is not '
777 'supported by Bazel (officially supported versions: %s). Please use '
778 'another version. Compiling Android targets may result in confusing '
779 'errors.\n' % (android_ndk_home_path, ndk_api_level,
780 _SUPPORTED_ANDROID_NDK_VERSIONS))
781 return ndk_api_level
Austin Anderson6afface2017-12-05 11:59:17 -0800782
783
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700784def set_gcc_host_compiler_path(environ_cp):
785 """Set GCC_HOST_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700786 default_gcc_host_compiler_path = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700787 cuda_bin_symlink = '%s/bin/gcc' % environ_cp.get('CUDA_TOOLKIT_PATH')
788
789 if os.path.islink(cuda_bin_symlink):
790 # os.readlink is only available in linux
Jonathan Hseu008910f2017-08-25 14:01:05 -0700791 default_gcc_host_compiler_path = os.path.realpath(cuda_bin_symlink)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700792
Austin Anderson6afface2017-12-05 11:59:17 -0800793 gcc_host_compiler_path = prompt_loop_or_load_from_env(
794 environ_cp,
795 var_name='GCC_HOST_COMPILER_PATH',
796 var_default=default_gcc_host_compiler_path,
797 ask_for_var=
798 'Please specify which gcc should be used by nvcc as the host compiler.',
799 check_success=os.path.exists,
800 error_msg='Invalid gcc path. %s cannot be found.',
801 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700802
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700803 write_action_env_to_bazelrc('GCC_HOST_COMPILER_PATH', gcc_host_compiler_path)
804
805
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800806def reformat_version_sequence(version_str, sequence_count):
807 """Reformat the version string to have the given number of sequences.
808
809 For example:
810 Given (7, 2) -> 7.0
811 (7.0.1, 2) -> 7.0
812 (5, 1) -> 5
813 (5.0.3.2, 1) -> 5
814
815 Args:
816 version_str: String, the version string.
817 sequence_count: int, an integer.
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700818
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800819 Returns:
820 string, reformatted version string.
821 """
822 v = version_str.split('.')
823 if len(v) < sequence_count:
824 v = v + (['0'] * (sequence_count - len(v)))
825
826 return '.'.join(v[:sequence_count])
827
828
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700829def set_tf_cuda_version(environ_cp):
830 """Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION."""
831 ask_cuda_version = (
A. Unique TensorFlowerb15500b2018-05-08 12:04:38 -0700832 'Please specify the CUDA SDK version you want to use. '
833 '[Leave empty to default to CUDA %s]: ') % _DEFAULT_CUDA_VERSION
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700834
Austin Andersonf9a88f82017-12-13 11:49:40 -0800835 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700836 # Configure the Cuda SDK version to use.
837 tf_cuda_version = get_from_env_or_user_or_default(
838 environ_cp, 'TF_CUDA_VERSION', ask_cuda_version, _DEFAULT_CUDA_VERSION)
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800839 tf_cuda_version = reformat_version_sequence(str(tf_cuda_version), 2)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700840
841 # Find out where the CUDA toolkit is installed
842 default_cuda_path = _DEFAULT_CUDA_PATH
Martin Wicked57572e2017-09-02 19:21:45 -0700843 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700844 default_cuda_path = cygpath(
845 environ_cp.get('CUDA_PATH', _DEFAULT_CUDA_PATH_WIN))
846 elif is_linux():
847 # If the default doesn't exist, try an alternative default.
848 if (not os.path.exists(default_cuda_path)
849 ) and os.path.exists(_DEFAULT_CUDA_PATH_LINUX):
850 default_cuda_path = _DEFAULT_CUDA_PATH_LINUX
851 ask_cuda_path = ('Please specify the location where CUDA %s toolkit is'
852 ' installed. Refer to README.md for more details. '
853 '[Default is %s]: ') % (tf_cuda_version, default_cuda_path)
854 cuda_toolkit_path = get_from_env_or_user_or_default(
855 environ_cp, 'CUDA_TOOLKIT_PATH', ask_cuda_path, default_cuda_path)
A. Unique TensorFlower02f17fe2018-07-07 06:59:19 -0700856 if is_windows() or is_cygwin():
857 cuda_toolkit_path = cygpath(cuda_toolkit_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700858
859 if is_windows():
Niall Moranb7d97e82018-08-09 00:29:49 +0100860 cuda_rt_lib_paths = ['lib/x64/cudart.lib']
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700861 elif is_linux():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700862 cuda_rt_lib_paths = [
863 '%s/libcudart.so.%s' % (x, tf_cuda_version) for x in [
864 'lib64',
865 'lib/powerpc64le-linux-gnu',
866 'lib/x86_64-linux-gnu',
867 ]
868 ]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700869 elif is_macos():
Niall Moranb7d97e82018-08-09 00:29:49 +0100870 cuda_rt_lib_paths = ['lib/libcudart.%s.dylib' % tf_cuda_version]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700871
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700872 cuda_toolkit_paths_full = [
873 os.path.join(cuda_toolkit_path, x) for x in cuda_rt_lib_paths
874 ]
Sergei Lebedev95d7bbb2018-11-21 10:40:10 -0800875 if any(os.path.exists(x) for x in cuda_toolkit_paths_full):
Yifei Feng5198cb82018-08-17 13:53:06 -0700876 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700877
878 # Reset and retry
879 print('Invalid path to CUDA %s toolkit. %s cannot be found' %
hellcom9a13fc32018-09-12 10:58:24 +0300880 (tf_cuda_version, cuda_toolkit_paths_full))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700881 environ_cp['TF_CUDA_VERSION'] = ''
882 environ_cp['CUDA_TOOLKIT_PATH'] = ''
883
Austin Andersonf9a88f82017-12-13 11:49:40 -0800884 else:
885 raise UserInputError('Invalid TF_CUDA_SETTING setting was provided %d '
886 'times in a row. Assuming to be a scripting mistake.' %
887 _DEFAULT_PROMPT_ASK_ATTEMPTS)
888
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700889 # Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION
890 environ_cp['CUDA_TOOLKIT_PATH'] = cuda_toolkit_path
891 write_action_env_to_bazelrc('CUDA_TOOLKIT_PATH', cuda_toolkit_path)
892 environ_cp['TF_CUDA_VERSION'] = tf_cuda_version
893 write_action_env_to_bazelrc('TF_CUDA_VERSION', tf_cuda_version)
894
895
Yifei Fengb1d8c592017-11-22 13:42:21 -0800896def set_tf_cudnn_version(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700897 """Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION."""
898 ask_cudnn_version = (
Jonathan Hseu008910f2017-08-25 14:01:05 -0700899 'Please specify the cuDNN version you want to use. '
A. Unique TensorFlower44acd832018-10-01 13:42:40 -0700900 '[Leave empty to default to cuDNN %s]: ') % _DEFAULT_CUDNN_VERSION
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700901
Austin Andersonf9a88f82017-12-13 11:49:40 -0800902 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700903 tf_cudnn_version = get_from_env_or_user_or_default(
904 environ_cp, 'TF_CUDNN_VERSION', ask_cudnn_version,
905 _DEFAULT_CUDNN_VERSION)
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800906 tf_cudnn_version = reformat_version_sequence(str(tf_cudnn_version), 1)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700907
908 default_cudnn_path = environ_cp.get('CUDA_TOOLKIT_PATH')
909 ask_cudnn_path = (r'Please specify the location where cuDNN %s library is '
910 'installed. Refer to README.md for more details. [Default'
A. Unique TensorFlower1b212352018-07-19 13:48:50 -0700911 ' is %s]: ') % (tf_cudnn_version, default_cudnn_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700912 cudnn_install_path = get_from_env_or_user_or_default(
913 environ_cp, 'CUDNN_INSTALL_PATH', ask_cudnn_path, default_cudnn_path)
914
915 # Result returned from "read" will be used unexpanded. That make "~"
916 # unusable. Going through one more level of expansion to handle that.
917 cudnn_install_path = os.path.realpath(
918 os.path.expanduser(cudnn_install_path))
Martin Wicked57572e2017-09-02 19:21:45 -0700919 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700920 cudnn_install_path = cygpath(cudnn_install_path)
921
922 if is_windows():
923 cuda_dnn_lib_path = 'lib/x64/cudnn.lib'
924 cuda_dnn_lib_alt_path = 'lib/x64/cudnn.lib'
925 elif is_linux():
926 cuda_dnn_lib_path = 'lib64/libcudnn.so.%s' % tf_cudnn_version
927 cuda_dnn_lib_alt_path = 'libcudnn.so.%s' % tf_cudnn_version
928 elif is_macos():
929 cuda_dnn_lib_path = 'lib/libcudnn.%s.dylib' % tf_cudnn_version
930 cuda_dnn_lib_alt_path = 'libcudnn.%s.dylib' % tf_cudnn_version
931
932 cuda_dnn_lib_path_full = os.path.join(cudnn_install_path, cuda_dnn_lib_path)
933 cuda_dnn_lib_alt_path_full = os.path.join(cudnn_install_path,
934 cuda_dnn_lib_alt_path)
935 if os.path.exists(cuda_dnn_lib_path_full) or os.path.exists(
936 cuda_dnn_lib_alt_path_full):
937 break
938
939 # Try another alternative for Linux
940 if is_linux():
Jonathan Hseu008910f2017-08-25 14:01:05 -0700941 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
942 cudnn_path_from_ldconfig = run_shell([ldconfig_bin, '-p'])
943 cudnn_path_from_ldconfig = re.search('.*libcudnn.so .* => (.*)',
A. Unique TensorFlowere7223582017-09-06 17:57:04 -0700944 cudnn_path_from_ldconfig)
945 if cudnn_path_from_ldconfig:
946 cudnn_path_from_ldconfig = cudnn_path_from_ldconfig.group(1)
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700947 if os.path.exists(
948 '%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version)):
A. Unique TensorFlowere7223582017-09-06 17:57:04 -0700949 cudnn_install_path = os.path.dirname(cudnn_path_from_ldconfig)
950 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700951
952 # Reset and Retry
953 print(
954 'Invalid path to cuDNN %s toolkit. None of the following files can be '
955 'found:' % tf_cudnn_version)
956 print(cuda_dnn_lib_path_full)
957 print(cuda_dnn_lib_alt_path_full)
958 if is_linux():
959 print('%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version))
960
961 environ_cp['TF_CUDNN_VERSION'] = ''
Austin Andersonf9a88f82017-12-13 11:49:40 -0800962 else:
963 raise UserInputError('Invalid TF_CUDNN setting was provided %d '
964 'times in a row. Assuming to be a scripting mistake.' %
965 _DEFAULT_PROMPT_ASK_ATTEMPTS)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700966
967 # Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION
968 environ_cp['CUDNN_INSTALL_PATH'] = cudnn_install_path
969 write_action_env_to_bazelrc('CUDNN_INSTALL_PATH', cudnn_install_path)
970 environ_cp['TF_CUDNN_VERSION'] = tf_cudnn_version
971 write_action_env_to_bazelrc('TF_CUDNN_VERSION', tf_cudnn_version)
972
973
Mingxing Tan1e7b0e42018-06-28 19:13:20 -0700974def is_cuda_compatible(lib, cuda_ver, cudnn_ver):
975 """Check compatibility between given library and cudnn/cudart libraries."""
976 ldd_bin = which('ldd') or '/usr/bin/ldd'
977 ldd_out = run_shell([ldd_bin, lib], True)
978 ldd_out = ldd_out.split(os.linesep)
979 cudnn_pattern = re.compile('.*libcudnn.so\\.?(.*) =>.*$')
980 cuda_pattern = re.compile('.*libcudart.so\\.?(.*) =>.*$')
981 cudnn = None
982 cudart = None
983 cudnn_ok = True # assume no cudnn dependency by default
984 cuda_ok = True # assume no cuda dependency by default
985 for line in ldd_out:
986 if 'libcudnn.so' in line:
987 cudnn = cudnn_pattern.search(line)
988 cudnn_ok = False
989 elif 'libcudart.so' in line:
990 cudart = cuda_pattern.search(line)
991 cuda_ok = False
992 if cudnn and len(cudnn.group(1)):
993 cudnn = convert_version_to_int(cudnn.group(1))
994 if cudart and len(cudart.group(1)):
995 cudart = convert_version_to_int(cudart.group(1))
996 if cudnn is not None:
997 cudnn_ok = (cudnn == cudnn_ver)
998 if cudart is not None:
999 cuda_ok = (cudart == cuda_ver)
1000 return cudnn_ok and cuda_ok
1001
1002
Guangda Lai76f69382018-01-25 23:59:19 -08001003def set_tf_tensorrt_install_path(environ_cp):
1004 """Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION.
1005
1006 Adapted from code contributed by Sami Kama (https://github.com/samikama).
1007
1008 Args:
1009 environ_cp: copy of the os.environ.
1010
1011 Raises:
1012 ValueError: if this method was called under non-Linux platform.
1013 UserInputError: if user has provided invalid input multiple times.
1014 """
1015 if not is_linux():
1016 raise ValueError('Currently TensorRT is only supported on Linux platform.')
1017
1018 # Ask user whether to add TensorRT support.
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001019 if str(int(get_var(environ_cp, 'TF_NEED_TENSORRT', 'TensorRT',
1020 False))) != '1':
Guangda Lai76f69382018-01-25 23:59:19 -08001021 return
1022
1023 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
1024 ask_tensorrt_path = (r'Please specify the location where TensorRT is '
1025 'installed. [Default is %s]:') % (
1026 _DEFAULT_TENSORRT_PATH_LINUX)
1027 trt_install_path = get_from_env_or_user_or_default(
1028 environ_cp, 'TENSORRT_INSTALL_PATH', ask_tensorrt_path,
1029 _DEFAULT_TENSORRT_PATH_LINUX)
1030
1031 # Result returned from "read" will be used unexpanded. That make "~"
1032 # unusable. Going through one more level of expansion to handle that.
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001033 trt_install_path = os.path.realpath(os.path.expanduser(trt_install_path))
Guangda Lai76f69382018-01-25 23:59:19 -08001034
1035 def find_libs(search_path):
1036 """Search for libnvinfer.so in "search_path"."""
1037 fl = set()
1038 if os.path.exists(search_path) and os.path.isdir(search_path):
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001039 fl.update([
1040 os.path.realpath(os.path.join(search_path, x))
1041 for x in os.listdir(search_path)
1042 if 'libnvinfer.so' in x
1043 ])
Guangda Lai76f69382018-01-25 23:59:19 -08001044 return fl
1045
1046 possible_files = find_libs(trt_install_path)
1047 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib')))
1048 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib64')))
Guangda Lai76f69382018-01-25 23:59:19 -08001049 cuda_ver = convert_version_to_int(environ_cp['TF_CUDA_VERSION'])
1050 cudnn_ver = convert_version_to_int(environ_cp['TF_CUDNN_VERSION'])
1051 nvinfer_pattern = re.compile('.*libnvinfer.so.?(.*)$')
1052 highest_ver = [0, None, None]
1053
1054 for lib_file in possible_files:
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001055 if is_cuda_compatible(lib_file, cuda_ver, cudnn_ver):
Jacques Pienaar2d0531d2018-03-21 12:07:51 -07001056 matches = nvinfer_pattern.search(lib_file)
TensorFlower Gardener61a87202018-10-01 12:25:39 -07001057 if not matches.groups():
Jacques Pienaar2d0531d2018-03-21 12:07:51 -07001058 continue
1059 ver_str = matches.group(1)
Guangda Lai76f69382018-01-25 23:59:19 -08001060 ver = convert_version_to_int(ver_str) if len(ver_str) else 0
1061 if ver > highest_ver[0]:
1062 highest_ver = [ver, ver_str, lib_file]
1063 if highest_ver[1] is not None:
1064 trt_install_path = os.path.dirname(highest_ver[2])
1065 tf_tensorrt_version = highest_ver[1]
1066 break
1067
1068 # Try another alternative from ldconfig.
1069 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
1070 ldconfig_output = run_shell([ldconfig_bin, '-p'])
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001071 search_result = re.search('.*libnvinfer.so\\.?([0-9.]*).* => (.*)',
1072 ldconfig_output)
Guangda Lai76f69382018-01-25 23:59:19 -08001073 if search_result:
1074 libnvinfer_path_from_ldconfig = search_result.group(2)
1075 if os.path.exists(libnvinfer_path_from_ldconfig):
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001076 if is_cuda_compatible(libnvinfer_path_from_ldconfig, cuda_ver,
1077 cudnn_ver):
Guangda Lai76f69382018-01-25 23:59:19 -08001078 trt_install_path = os.path.dirname(libnvinfer_path_from_ldconfig)
1079 tf_tensorrt_version = search_result.group(1)
1080 break
1081
1082 # Reset and Retry
Yifei Fengdce9a492018-02-22 14:24:57 -08001083 if possible_files:
1084 print('TensorRT libraries found in one the following directories',
1085 'are not compatible with selected cuda and cudnn installations')
1086 print(trt_install_path)
1087 print(os.path.join(trt_install_path, 'lib'))
1088 print(os.path.join(trt_install_path, 'lib64'))
1089 if search_result:
1090 print(libnvinfer_path_from_ldconfig)
1091 else:
1092 print(
1093 'Invalid path to TensorRT. None of the following files can be found:')
1094 print(trt_install_path)
1095 print(os.path.join(trt_install_path, 'lib'))
1096 print(os.path.join(trt_install_path, 'lib64'))
1097 if search_result:
1098 print(libnvinfer_path_from_ldconfig)
Guangda Lai76f69382018-01-25 23:59:19 -08001099
1100 else:
1101 raise UserInputError('Invalid TF_TENSORRT setting was provided %d '
1102 'times in a row. Assuming to be a scripting mistake.' %
1103 _DEFAULT_PROMPT_ASK_ATTEMPTS)
1104
1105 # Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION
1106 environ_cp['TENSORRT_INSTALL_PATH'] = trt_install_path
1107 write_action_env_to_bazelrc('TENSORRT_INSTALL_PATH', trt_install_path)
1108 environ_cp['TF_TENSORRT_VERSION'] = tf_tensorrt_version
1109 write_action_env_to_bazelrc('TF_TENSORRT_VERSION', tf_tensorrt_version)
1110
1111
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001112def set_tf_nccl_install_path(environ_cp):
Jason Furmanek7c234152018-09-26 04:44:12 +00001113 """Set NCCL_INSTALL_PATH, NCCL_HDR_PATH and TF_NCCL_VERSION.
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001114
1115 Args:
1116 environ_cp: copy of the os.environ.
1117
1118 Raises:
1119 ValueError: if this method was called under non-Linux platform.
1120 UserInputError: if user has provided invalid input multiple times.
1121 """
1122 if not is_linux():
1123 raise ValueError('Currently NCCL is only supported on Linux platforms.')
1124
1125 ask_nccl_version = (
A. Unique TensorFlower53faa312018-10-05 08:46:54 -07001126 'Please specify the locally installed NCCL version you want to use. '
1127 '[Default is to use https://github.com/nvidia/nccl]: ')
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001128
1129 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
1130 tf_nccl_version = get_from_env_or_user_or_default(
A. Unique TensorFlower53faa312018-10-05 08:46:54 -07001131 environ_cp, 'TF_NCCL_VERSION', ask_nccl_version, '')
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001132
A. Unique TensorFlower53faa312018-10-05 08:46:54 -07001133 if not tf_nccl_version:
1134 break # No need to get install path, building the open source code.
1135
1136 tf_nccl_version = reformat_version_sequence(str(tf_nccl_version), 1)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001137
Jason Furmanek7c234152018-09-26 04:44:12 +00001138 # Look with ldconfig first if we can find the library in paths
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001139 # like /usr/lib/x86_64-linux-gnu and the header file in the corresponding
1140 # include directory. This is where the NCCL .deb packages install them.
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001141
Jason Furmanek7c234152018-09-26 04:44:12 +00001142 # First check to see if NCCL is in the ldconfig.
1143 # If its found, use that location.
1144 if is_linux():
1145 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
1146 nccl2_path_from_ldconfig = run_shell([ldconfig_bin, '-p'])
1147 nccl2_path_from_ldconfig = re.search('.*libnccl.so .* => (.*)',
1148 nccl2_path_from_ldconfig)
1149 if nccl2_path_from_ldconfig:
1150 nccl2_path_from_ldconfig = nccl2_path_from_ldconfig.group(1)
1151 if os.path.exists('%s.%s' % (nccl2_path_from_ldconfig, tf_nccl_version)):
1152 nccl_install_path = os.path.dirname(nccl2_path_from_ldconfig)
1153 print('NCCL libraries found in ' + nccl2_path_from_ldconfig)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001154
Jason Furmanek7c234152018-09-26 04:44:12 +00001155 # Check if this is the main system lib location
1156 if re.search('.*linux-gnu', nccl_install_path):
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001157 trunc_nccl_install_path = '/usr'
1158 print('This looks like a system path.')
Jason Furmanek7c234152018-09-26 04:44:12 +00001159 else:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001160 trunc_nccl_install_path = nccl_install_path + '/..'
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001161
Jason Furmanek7c234152018-09-26 04:44:12 +00001162 # Look for header
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001163 nccl_hdr_path = trunc_nccl_install_path + '/include'
1164 print('Assuming NCCL header path is ' + nccl_hdr_path)
1165 if os.path.exists(nccl_hdr_path + '/nccl.h'):
Jason Furmanek7c234152018-09-26 04:44:12 +00001166 # Set NCCL_INSTALL_PATH
1167 environ_cp['NCCL_INSTALL_PATH'] = nccl_install_path
1168 write_action_env_to_bazelrc('NCCL_INSTALL_PATH', nccl_install_path)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001169
Jason Furmanek7c234152018-09-26 04:44:12 +00001170 # Set NCCL_HDR_PATH
1171 environ_cp['NCCL_HDR_PATH'] = nccl_hdr_path
1172 write_action_env_to_bazelrc('NCCL_HDR_PATH', nccl_hdr_path)
1173 break
1174 else:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001175 print(
1176 'The header for NCCL2 cannot be found. Please install the libnccl-dev package.'
1177 )
Jason Furmanek7c234152018-09-26 04:44:12 +00001178 else:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001179 print('NCCL2 is listed by ldconfig but the library is not found. '
1180 'Your ldconfig is out of date. Please run sudo ldconfig.')
Jason Furmanek7c234152018-09-26 04:44:12 +00001181 else:
1182 # NCCL is not found in ldconfig. Ask the user for the location.
1183 default_nccl_path = environ_cp.get('CUDA_TOOLKIT_PATH')
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001184 ask_nccl_path = (
1185 r'Please specify the location where NCCL %s library is '
1186 'installed. Refer to README.md for more details. [Default '
1187 'is %s]:') % (tf_nccl_version, default_nccl_path)
Jason Furmanek7c234152018-09-26 04:44:12 +00001188 nccl_install_path = get_from_env_or_user_or_default(
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001189 environ_cp, 'NCCL_INSTALL_PATH', ask_nccl_path, default_nccl_path)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001190
Jason Furmanek7c234152018-09-26 04:44:12 +00001191 # Result returned from "read" will be used unexpanded. That make "~"
1192 # unusable. Going through one more level of expansion to handle that.
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001193 nccl_install_path = os.path.realpath(
1194 os.path.expanduser(nccl_install_path))
Jason Furmanek7c234152018-09-26 04:44:12 +00001195 if is_windows() or is_cygwin():
1196 nccl_install_path = cygpath(nccl_install_path)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001197
Guangda Lai62ebf622018-10-23 07:44:13 -07001198 nccl_lib_path = ''
Jason Furmanek7c234152018-09-26 04:44:12 +00001199 if is_windows():
1200 nccl_lib_path = 'lib/x64/nccl.lib'
1201 elif is_linux():
1202 nccl_lib_filename = 'libnccl.so.%s' % tf_nccl_version
1203 nccl_lpath = '%s/lib/%s' % (nccl_install_path, nccl_lib_filename)
1204 if not os.path.exists(nccl_lpath):
1205 for relative_path in NCCL_LIB_PATHS:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001206 path = '%s/%s%s' % (nccl_install_path, relative_path,
1207 nccl_lib_filename)
Jason Furmanek7c234152018-09-26 04:44:12 +00001208 if os.path.exists(path):
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001209 print('NCCL found at ' + path)
Jason Furmanek7c234152018-09-26 04:44:12 +00001210 nccl_lib_path = path
1211 break
1212 else:
1213 nccl_lib_path = nccl_lpath
1214 elif is_macos():
1215 nccl_lib_path = 'lib/libnccl.%s.dylib' % tf_nccl_version
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001216
Jason Furmanek7c234152018-09-26 04:44:12 +00001217 nccl_lib_path = os.path.join(nccl_install_path, nccl_lib_path)
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001218 nccl_hdr_path = os.path.join(
1219 os.path.dirname(nccl_lib_path), '../include/nccl.h')
1220 print('Assuming NCCL header path is ' + nccl_hdr_path)
Jason Furmanek7c234152018-09-26 04:44:12 +00001221 if os.path.exists(nccl_lib_path) and os.path.exists(nccl_hdr_path):
1222 # Set NCCL_INSTALL_PATH
1223 environ_cp['NCCL_INSTALL_PATH'] = os.path.dirname(nccl_lib_path)
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001224 write_action_env_to_bazelrc('NCCL_INSTALL_PATH',
1225 os.path.dirname(nccl_lib_path))
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001226
Jason Furmanek7c234152018-09-26 04:44:12 +00001227 # Set NCCL_HDR_PATH
1228 environ_cp['NCCL_HDR_PATH'] = os.path.dirname(nccl_hdr_path)
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001229 write_action_env_to_bazelrc('NCCL_HDR_PATH',
1230 os.path.dirname(nccl_hdr_path))
Jason Furmanek7c234152018-09-26 04:44:12 +00001231 break
1232
1233 # Reset and Retry
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001234 print(
1235 'Invalid path to NCCL %s toolkit, %s or %s not found. Please use the '
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001236 'O/S agnostic package of NCCL 2' % (tf_nccl_version, nccl_lib_path,
1237 nccl_hdr_path))
1238
Jason Furmanek7c234152018-09-26 04:44:12 +00001239 environ_cp['TF_NCCL_VERSION'] = ''
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001240 else:
1241 raise UserInputError('Invalid TF_NCCL setting was provided %d '
1242 'times in a row. Assuming to be a scripting mistake.' %
1243 _DEFAULT_PROMPT_ASK_ATTEMPTS)
1244
1245 # Set TF_NCCL_VERSION
1246 environ_cp['TF_NCCL_VERSION'] = tf_nccl_version
1247 write_action_env_to_bazelrc('TF_NCCL_VERSION', tf_nccl_version)
1248
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001249def get_native_cuda_compute_capabilities(environ_cp):
1250 """Get native cuda compute capabilities.
1251
1252 Args:
1253 environ_cp: copy of the os.environ.
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001254
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001255 Returns:
1256 string of native cuda compute capabilities, separated by comma.
1257 """
1258 device_query_bin = os.path.join(
1259 environ_cp.get('CUDA_TOOLKIT_PATH'), 'extras/demo_suite/deviceQuery')
Jonathan Hseu008910f2017-08-25 14:01:05 -07001260 if os.path.isfile(device_query_bin) and os.access(device_query_bin, os.X_OK):
1261 try:
1262 output = run_shell(device_query_bin).split('\n')
1263 pattern = re.compile('[0-9]*\\.[0-9]*')
1264 output = [pattern.search(x) for x in output if 'Capability' in x]
1265 output = ','.join(x.group() for x in output if x is not None)
1266 except subprocess.CalledProcessError:
1267 output = ''
1268 else:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001269 output = ''
1270 return output
1271
1272
1273def set_tf_cuda_compute_capabilities(environ_cp):
1274 """Set TF_CUDA_COMPUTE_CAPABILITIES."""
1275 while True:
1276 native_cuda_compute_capabilities = get_native_cuda_compute_capabilities(
1277 environ_cp)
1278 if not native_cuda_compute_capabilities:
1279 default_cuda_compute_capabilities = _DEFAULT_CUDA_COMPUTE_CAPABILITIES
1280 else:
1281 default_cuda_compute_capabilities = native_cuda_compute_capabilities
1282
1283 ask_cuda_compute_capabilities = (
1284 'Please specify a list of comma-separated '
1285 'Cuda compute capabilities you want to '
1286 'build with.\nYou can find the compute '
1287 'capability of your device at: '
1288 'https://developer.nvidia.com/cuda-gpus.\nPlease'
1289 ' note that each additional compute '
1290 'capability significantly increases your '
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001291 'build time and binary size. [Default is: %s]: ' %
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001292 default_cuda_compute_capabilities)
1293 tf_cuda_compute_capabilities = get_from_env_or_user_or_default(
1294 environ_cp, 'TF_CUDA_COMPUTE_CAPABILITIES',
1295 ask_cuda_compute_capabilities, default_cuda_compute_capabilities)
1296 # Check whether all capabilities from the input is valid
1297 all_valid = True
Maciejd0f5bc12018-04-30 22:30:58 -05001298 # Remove all whitespace characters before splitting the string
Michael Case51053502018-06-05 17:47:19 -07001299 # that users may insert by accident, as this will result in error
Maciejd0f5bc12018-04-30 22:30:58 -05001300 tf_cuda_compute_capabilities = ''.join(tf_cuda_compute_capabilities.split())
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001301 for compute_capability in tf_cuda_compute_capabilities.split(','):
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001302 m = re.match('[0-9]+.[0-9]+', compute_capability)
1303 if not m:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001304 print('Invalid compute capability: ' % compute_capability)
1305 all_valid = False
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001306 else:
1307 ver = int(m.group(0).split('.')[0])
1308 if ver < 3:
1309 print('Only compute capabilities 3.0 or higher are supported.')
1310 all_valid = False
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001311
1312 if all_valid:
1313 break
1314
1315 # Reset and Retry
1316 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = ''
1317
1318 # Set TF_CUDA_COMPUTE_CAPABILITIES
1319 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = tf_cuda_compute_capabilities
1320 write_action_env_to_bazelrc('TF_CUDA_COMPUTE_CAPABILITIES',
1321 tf_cuda_compute_capabilities)
1322
1323
1324def set_other_cuda_vars(environ_cp):
1325 """Set other CUDA related variables."""
A. Unique TensorFlowerab391982018-07-11 04:52:49 -07001326 # If CUDA is enabled, always use GPU during build and test.
1327 if environ_cp.get('TF_CUDA_CLANG') == '1':
1328 write_to_bazelrc('build --config=cuda_clang')
1329 write_to_bazelrc('test --config=cuda_clang')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001330 else:
A. Unique TensorFlowerab391982018-07-11 04:52:49 -07001331 write_to_bazelrc('build --config=cuda')
1332 write_to_bazelrc('test --config=cuda')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001333
1334
1335def set_host_cxx_compiler(environ_cp):
1336 """Set HOST_CXX_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001337 default_cxx_host_compiler = which('g++') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001338
Austin Anderson6afface2017-12-05 11:59:17 -08001339 host_cxx_compiler = prompt_loop_or_load_from_env(
1340 environ_cp,
1341 var_name='HOST_CXX_COMPILER',
1342 var_default=default_cxx_host_compiler,
1343 ask_for_var=('Please specify which C++ compiler should be used as the '
1344 'host C++ compiler.'),
1345 check_success=os.path.exists,
1346 error_msg='Invalid C++ compiler path. %s cannot be found.',
1347 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001348
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001349 write_action_env_to_bazelrc('HOST_CXX_COMPILER', host_cxx_compiler)
1350
1351
1352def set_host_c_compiler(environ_cp):
1353 """Set HOST_C_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001354 default_c_host_compiler = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001355
Austin Anderson6afface2017-12-05 11:59:17 -08001356 host_c_compiler = prompt_loop_or_load_from_env(
1357 environ_cp,
1358 var_name='HOST_C_COMPILER',
1359 var_default=default_c_host_compiler,
Shanqing Cai71445712018-03-12 19:33:52 -07001360 ask_for_var=('Please specify which C compiler should be used as the host '
Austin Anderson6afface2017-12-05 11:59:17 -08001361 'C compiler.'),
1362 check_success=os.path.exists,
1363 error_msg='Invalid C compiler path. %s cannot be found.',
1364 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001365
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001366 write_action_env_to_bazelrc('HOST_C_COMPILER', host_c_compiler)
1367
1368
1369def set_computecpp_toolkit_path(environ_cp):
1370 """Set COMPUTECPP_TOOLKIT_PATH."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001371
Austin Anderson6afface2017-12-05 11:59:17 -08001372 def toolkit_exists(toolkit_path):
1373 """Check if a computecpp toolkit path is valid."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001374 if is_linux():
1375 sycl_rt_lib_path = 'lib/libComputeCpp.so'
1376 else:
1377 sycl_rt_lib_path = ''
1378
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001379 sycl_rt_lib_path_full = os.path.join(toolkit_path, sycl_rt_lib_path)
Austin Anderson6afface2017-12-05 11:59:17 -08001380 exists = os.path.exists(sycl_rt_lib_path_full)
1381 if not exists:
1382 print('Invalid SYCL %s library path. %s cannot be found' %
1383 (_TF_OPENCL_VERSION, sycl_rt_lib_path_full))
1384 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001385
Austin Anderson6afface2017-12-05 11:59:17 -08001386 computecpp_toolkit_path = prompt_loop_or_load_from_env(
1387 environ_cp,
1388 var_name='COMPUTECPP_TOOLKIT_PATH',
1389 var_default=_DEFAULT_COMPUTECPP_TOOLKIT_PATH,
1390 ask_for_var=(
1391 'Please specify the location where ComputeCpp for SYCL %s is '
1392 'installed.' % _TF_OPENCL_VERSION),
1393 check_success=toolkit_exists,
1394 error_msg='Invalid SYCL compiler path. %s cannot be found.',
1395 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001396
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001397 write_action_env_to_bazelrc('COMPUTECPP_TOOLKIT_PATH',
1398 computecpp_toolkit_path)
1399
Michael Cased31531a2018-01-05 14:09:41 -08001400
Dandelion Man?90e42f32017-12-15 18:15:07 -08001401def set_trisycl_include_dir(environ_cp):
Michael Cased31531a2018-01-05 14:09:41 -08001402 """Set TRISYCL_INCLUDE_DIR."""
Frank Chenc4ef9272018-01-10 11:36:52 -08001403
Dandelion Man?90e42f32017-12-15 18:15:07 -08001404 ask_trisycl_include_dir = ('Please specify the location of the triSYCL '
1405 'include directory. (Use --config=sycl_trisycl '
1406 'when building with Bazel) '
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001407 '[Default is %s]: ') % (
1408 _DEFAULT_TRISYCL_INCLUDE_DIR)
Frank Chenc4ef9272018-01-10 11:36:52 -08001409
Dandelion Man?90e42f32017-12-15 18:15:07 -08001410 while True:
1411 trisycl_include_dir = get_from_env_or_user_or_default(
Michael Cased31531a2018-01-05 14:09:41 -08001412 environ_cp, 'TRISYCL_INCLUDE_DIR', ask_trisycl_include_dir,
1413 _DEFAULT_TRISYCL_INCLUDE_DIR)
Dandelion Man?90e42f32017-12-15 18:15:07 -08001414 if os.path.exists(trisycl_include_dir):
1415 break
1416
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001417 print('Invalid triSYCL include directory, %s cannot be found' %
1418 (trisycl_include_dir))
Dandelion Man?90e42f32017-12-15 18:15:07 -08001419
1420 # Set TRISYCL_INCLUDE_DIR
1421 environ_cp['TRISYCL_INCLUDE_DIR'] = trisycl_include_dir
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001422 write_action_env_to_bazelrc('TRISYCL_INCLUDE_DIR', trisycl_include_dir)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001423
Yifei Fengb1d8c592017-11-22 13:42:21 -08001424
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001425def set_mpi_home(environ_cp):
1426 """Set MPI_HOME."""
Austin Anderson6afface2017-12-05 11:59:17 -08001427
Jonathan Hseu008910f2017-08-25 14:01:05 -07001428 default_mpi_home = which('mpirun') or which('mpiexec') or ''
1429 default_mpi_home = os.path.dirname(os.path.dirname(default_mpi_home))
1430
Austin Anderson6afface2017-12-05 11:59:17 -08001431 def valid_mpi_path(mpi_home):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001432 exists = (
1433 os.path.exists(os.path.join(mpi_home, 'include')) and
TensorFlower Gardenerf7c861f2018-11-01 11:29:40 -07001434 (os.path.exists(os.path.join(mpi_home, 'lib')) or
1435 os.path.exists(os.path.join(mpi_home, 'lib64')) or
1436 os.path.exists(os.path.join(mpi_home, 'lib32'))))
Austin Anderson6afface2017-12-05 11:59:17 -08001437 if not exists:
TensorFlower Gardenerf7c861f2018-11-01 11:29:40 -07001438 print(
1439 'Invalid path to the MPI Toolkit. %s or %s or %s or %s cannot be found'
1440 % (os.path.join(mpi_home, 'include'),
Christian Gollba95d092018-10-04 17:06:23 +02001441 os.path.exists(os.path.join(mpi_home, 'lib')),
1442 os.path.exists(os.path.join(mpi_home, 'lib64')),
1443 os.path.exists(os.path.join(mpi_home, 'lib32'))))
Austin Anderson6afface2017-12-05 11:59:17 -08001444 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001445
Austin Anderson6afface2017-12-05 11:59:17 -08001446 _ = prompt_loop_or_load_from_env(
1447 environ_cp,
1448 var_name='MPI_HOME',
1449 var_default=default_mpi_home,
1450 ask_for_var='Please specify the MPI toolkit folder.',
1451 check_success=valid_mpi_path,
1452 error_msg='',
1453 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001454
1455
1456def set_other_mpi_vars(environ_cp):
1457 """Set other MPI related variables."""
1458 # Link the MPI header files
1459 mpi_home = environ_cp.get('MPI_HOME')
1460 symlink_force('%s/include/mpi.h' % mpi_home, 'third_party/mpi/mpi.h')
1461
1462 # Determine if we use OpenMPI or MVAPICH, these require different header files
1463 # to be included here to make bazel dependency checker happy
1464 if os.path.exists(os.path.join(mpi_home, 'include/mpi_portable_platform.h')):
1465 symlink_force(
1466 os.path.join(mpi_home, 'include/mpi_portable_platform.h'),
1467 'third_party/mpi/mpi_portable_platform.h')
1468 # TODO(gunan): avoid editing files in configure
1469 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=False',
1470 'MPI_LIB_IS_OPENMPI=True')
1471 else:
1472 # MVAPICH / MPICH
1473 symlink_force(
1474 os.path.join(mpi_home, 'include/mpio.h'), 'third_party/mpi/mpio.h')
1475 symlink_force(
1476 os.path.join(mpi_home, 'include/mpicxx.h'), 'third_party/mpi/mpicxx.h')
1477 # TODO(gunan): avoid editing files in configure
1478 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=True',
1479 'MPI_LIB_IS_OPENMPI=False')
1480
1481 if os.path.exists(os.path.join(mpi_home, 'lib/libmpi.so')):
1482 symlink_force(
1483 os.path.join(mpi_home, 'lib/libmpi.so'), 'third_party/mpi/libmpi.so')
Christian Gollba95d092018-10-04 17:06:23 +02001484 elif os.path.exists(os.path.join(mpi_home, 'lib64/libmpi.so')):
1485 symlink_force(
1486 os.path.join(mpi_home, 'lib64/libmpi.so'), 'third_party/mpi/libmpi.so')
1487 elif os.path.exists(os.path.join(mpi_home, 'lib32/libmpi.so')):
1488 symlink_force(
1489 os.path.join(mpi_home, 'lib32/libmpi.so'), 'third_party/mpi/libmpi.so')
1490
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001491 else:
TensorFlower Gardenerf7c861f2018-11-01 11:29:40 -07001492 raise ValueError(
1493 'Cannot find the MPI library file in %s/lib or %s/lib64 or %s/lib32' %
1494 mpi_home, mpi_home, mpi_home)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001495
1496
Yifei Feng5198cb82018-08-17 13:53:06 -07001497def set_system_libs_flag(environ_cp):
1498 syslibs = environ_cp.get('TF_SYSTEM_LIBS', '')
TensorFlower Gardener61a87202018-10-01 12:25:39 -07001499 if syslibs:
Jason Zaman5fc39bd2018-09-16 01:38:55 +08001500 if ',' in syslibs:
1501 syslibs = ','.join(sorted(syslibs.split(',')))
1502 else:
1503 syslibs = ','.join(sorted(syslibs.split()))
Yifei Feng5198cb82018-08-17 13:53:06 -07001504 write_action_env_to_bazelrc('TF_SYSTEM_LIBS', syslibs)
1505
Jason Zaman5fc39bd2018-09-16 01:38:55 +08001506 if 'PREFIX' in environ_cp:
1507 write_to_bazelrc('build --define=PREFIX=%s' % environ_cp['PREFIX'])
1508 if 'LIBDIR' in environ_cp:
1509 write_to_bazelrc('build --define=LIBDIR=%s' % environ_cp['LIBDIR'])
1510 if 'INCLUDEDIR' in environ_cp:
1511 write_to_bazelrc('build --define=INCLUDEDIR=%s' % environ_cp['INCLUDEDIR'])
1512
Yifei Feng5198cb82018-08-17 13:53:06 -07001513
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001514def set_windows_build_flags(environ_cp):
1515 """Set Windows specific build options."""
1516 # The non-monolithic build is not supported yet
1517 write_to_bazelrc('build --config monolithic')
1518 # Suppress warning messages
1519 write_to_bazelrc('build --copt=-w --host_copt=-w')
1520 # Output more verbose information when something goes wrong
1521 write_to_bazelrc('build --verbose_failures')
1522 # The host and target platforms are the same in Windows build. So we don't
1523 # have to distinct them. This avoids building the same targets twice.
1524 write_to_bazelrc('build --distinct_host_configuration=false')
1525 # Enable short object file path to avoid long path issue on Windows.
1526 # TODO(pcloudy): Remove this flag when upgrading Bazel to 0.16.0
1527 # Short object file path will be enabled by default.
1528 write_to_bazelrc('build --experimental_shortened_obj_file_path=true')
1529
1530 if get_var(
1531 environ_cp, 'TF_OVERRIDE_EIGEN_STRONG_INLINE', 'Eigen strong inline',
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001532 True, ('Would you like to override eigen strong inline for some C++ '
1533 'compilation to reduce the compilation time?'),
1534 'Eigen strong inline overridden.', 'Not overriding eigen strong inline, '
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001535 'some compilations could take more than 20 mins.'):
1536 # Due to a known MSVC compiler issue
1537 # https://github.com/tensorflow/tensorflow/issues/10521
1538 # Overriding eigen strong inline speeds up the compiling of
1539 # conv_grad_ops_3d.cc and conv_ops_3d.cc by 20 minutes,
1540 # but this also hurts the performance. Let users decide what they want.
1541 write_to_bazelrc('build --define=override_eigen_strong_inline=true')
Dandelion Man?90e42f32017-12-15 18:15:07 -08001542
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001543
Michael Cased31531a2018-01-05 14:09:41 -08001544def config_info_line(name, help_text):
1545 """Helper function to print formatted help text for Bazel config options."""
1546 print('\t--config=%-12s\t# %s' % (name, help_text))
1547
1548
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001549def main():
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001550 global _TF_WORKSPACE_ROOT
1551 global _TF_BAZELRC
1552
Shanqing Cai71445712018-03-12 19:33:52 -07001553 parser = argparse.ArgumentParser()
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001554 parser.add_argument(
1555 '--workspace',
1556 type=str,
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001557 default=os.path.abspath(os.path.dirname(__file__)),
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001558 help='The absolute path to your active Bazel workspace.')
Shanqing Cai71445712018-03-12 19:33:52 -07001559 args = parser.parse_args()
1560
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001561 _TF_WORKSPACE_ROOT = args.workspace
1562 _TF_BAZELRC = os.path.join(_TF_WORKSPACE_ROOT, _TF_BAZELRC_FILENAME)
1563
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001564 # Make a copy of os.environ to be clear when functions and getting and setting
1565 # environment variables.
1566 environ_cp = dict(os.environ)
1567
Mihai Maruseace7a123f2018-11-30 13:33:25 -08001568 check_bazel_version('0.15.0', '0.19.2')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001569
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001570 reset_tf_configure_bazelrc()
Yun Peng03e63a22018-11-07 11:18:53 +01001571 # Explicitly import tools/bazel.rc, this is needed for Bazel 0.19.0 or later
1572 write_to_bazelrc('import %workspace%/tools/bazel.rc')
1573
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001574 cleanup_makefile()
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -07001575 setup_python(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001576
1577 if is_windows():
Yifei Fengb1d8c592017-11-22 13:42:21 -08001578 environ_cp['TF_NEED_OPENCL_SYCL'] = '0'
1579 environ_cp['TF_NEED_COMPUTECPP'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001580 environ_cp['TF_NEED_OPENCL'] = '0'
1581 environ_cp['TF_CUDA_CLANG'] = '0'
Guangda Lai76f69382018-01-25 23:59:19 -08001582 environ_cp['TF_NEED_TENSORRT'] = '0'
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001583 # TODO(ibiryukov): Investigate using clang as a cpu or cuda compiler on
1584 # Windows.
1585 environ_cp['TF_DOWNLOAD_CLANG'] = '0'
A. Unique TensorFlower6e97fb32018-07-16 14:07:29 -07001586 environ_cp['TF_NEED_MPI'] = '0'
1587 environ_cp['TF_SET_ANDROID_WORKSPACE'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001588
1589 if is_macos():
Guangda Lai76f69382018-01-25 23:59:19 -08001590 environ_cp['TF_NEED_TENSORRT'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001591
Jon Triebenbach6896a742018-06-27 13:29:53 -05001592 # The numpy package on ppc64le uses OpenBLAS which has multi-threading
1593 # issues that lead to incorrect answers. Set OMP_NUM_THREADS=1 at
1594 # runtime to allow the Tensorflow testcases which compare numpy
1595 # results to Tensorflow results to succeed.
1596 if is_ppc64le():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001597 write_action_env_to_bazelrc('OMP_NUM_THREADS', 1)
Jon Triebenbach6896a742018-06-27 13:29:53 -05001598
Grzegorz Pawelczakec82efd2018-10-09 15:03:46 +01001599 xla_enabled_by_default = is_linux()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001600 set_build_var(environ_cp, 'TF_ENABLE_XLA', 'XLA JIT', 'with_xla_support',
Grzegorz Pawelczakec82efd2018-10-09 15:03:46 +01001601 xla_enabled_by_default, 'xla')
Gunhan Gulsoy3da0dff2018-09-26 11:55:50 -07001602
Yifei Fengb1d8c592017-11-22 13:42:21 -08001603 set_action_env_var(environ_cp, 'TF_NEED_OPENCL_SYCL', 'OpenCL SYCL', False)
1604 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001605 set_host_cxx_compiler(environ_cp)
1606 set_host_c_compiler(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001607 set_action_env_var(environ_cp, 'TF_NEED_COMPUTECPP', 'ComputeCPP', True)
1608 if environ_cp.get('TF_NEED_COMPUTECPP') == '1':
1609 set_computecpp_toolkit_path(environ_cp)
1610 else:
1611 set_trisycl_include_dir(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001612
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001613 set_action_env_var(environ_cp, 'TF_NEED_ROCM', 'ROCm', False)
1614 if (environ_cp.get('TF_NEED_ROCM') == '1' and
TensorFlower Gardener62e60162018-09-27 10:22:55 -07001615 'LD_LIBRARY_PATH' in environ_cp and
1616 environ_cp.get('LD_LIBRARY_PATH') != '1'):
1617 write_action_env_to_bazelrc('LD_LIBRARY_PATH',
1618 environ_cp.get('LD_LIBRARY_PATH'))
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001619
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001620 set_action_env_var(environ_cp, 'TF_NEED_CUDA', 'CUDA', False)
A. Unique TensorFlower24cbb2a2017-09-08 07:45:44 -07001621 if (environ_cp.get('TF_NEED_CUDA') == '1' and
1622 'TF_CUDA_CONFIG_REPO' not in environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001623 set_tf_cuda_version(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001624 set_tf_cudnn_version(environ_cp)
Guangda Lai76f69382018-01-25 23:59:19 -08001625 if is_linux():
1626 set_tf_tensorrt_install_path(environ_cp)
Michael Case0073d132018-04-11 09:34:44 -07001627 set_tf_nccl_install_path(environ_cp)
1628
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001629 set_tf_cuda_compute_capabilities(environ_cp)
Ankur Taly0e6f39d2018-02-16 18:22:55 -08001630 if 'LD_LIBRARY_PATH' in environ_cp and environ_cp.get(
1631 'LD_LIBRARY_PATH') != '1':
1632 write_action_env_to_bazelrc('LD_LIBRARY_PATH',
1633 environ_cp.get('LD_LIBRARY_PATH'))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001634
1635 set_tf_cuda_clang(environ_cp)
1636 if environ_cp.get('TF_CUDA_CLANG') == '1':
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001637 # Ask whether we should download the clang toolchain.
1638 set_tf_download_clang(environ_cp)
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -08001639 if environ_cp.get('TF_DOWNLOAD_CLANG') != '1':
1640 # Set up which clang we should use as the cuda / host compiler.
1641 set_clang_cuda_compiler_path(environ_cp)
Ilya Biryukov1c3d02e2018-09-04 03:09:52 -07001642 else:
1643 # Use downloaded LLD for linking.
1644 write_to_bazelrc('build:cuda_clang --config=download_clang_use_lld')
1645 write_to_bazelrc('test:cuda_clang --config=download_clang_use_lld')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001646 else:
1647 # Set up which gcc nvcc should use as the host compiler
1648 # No need to set this on Windows
1649 if not is_windows():
1650 set_gcc_host_compiler_path(environ_cp)
1651 set_other_cuda_vars(environ_cp)
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001652 else:
1653 # CUDA not required. Ask whether we should download the clang toolchain and
1654 # use it for the CPU build.
1655 set_tf_download_clang(environ_cp)
1656 if environ_cp.get('TF_DOWNLOAD_CLANG') == '1':
1657 write_to_bazelrc('build --config=download_clang')
1658 write_to_bazelrc('test --config=download_clang')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001659
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001660 # SYCL / ROCm / CUDA are mutually exclusive.
1661 # At most 1 GPU platform can be configured.
1662 gpu_platform_count = 0
1663 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
1664 gpu_platform_count += 1
1665 if environ_cp.get('TF_NEED_ROCM') == '1':
1666 gpu_platform_count += 1
1667 if environ_cp.get('TF_NEED_CUDA') == '1':
1668 gpu_platform_count += 1
1669 if gpu_platform_count >= 2:
1670 raise UserInputError('SYCL / CUDA / ROCm are mututally exclusive. '
1671 'At most 1 GPU platform can be configured.')
1672
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001673 set_build_var(environ_cp, 'TF_NEED_MPI', 'MPI', 'with_mpi_support', False)
1674 if environ_cp.get('TF_NEED_MPI') == '1':
1675 set_mpi_home(environ_cp)
1676 set_other_mpi_vars(environ_cp)
1677
1678 set_cc_opt_flags(environ_cp)
Yifei Feng5198cb82018-08-17 13:53:06 -07001679 set_system_libs_flag(environ_cp)
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001680 if is_windows():
1681 set_windows_build_flags(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001682
Anna Ra9a1d5a2018-09-14 12:44:31 -07001683 # Add a config option to build TensorFlow 2.0 API.
1684 write_to_bazelrc('build:v2 --define=tf_api_version=2')
1685
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001686 if get_var(environ_cp, 'TF_SET_ANDROID_WORKSPACE', 'android workspace', False,
1687 ('Would you like to interactively configure ./WORKSPACE for '
1688 'Android builds?'), 'Searching for NDK and SDK installations.',
1689 'Not configuring the WORKSPACE for Android builds.'):
Michael Case51053502018-06-05 17:47:19 -07001690 create_android_ndk_rule(environ_cp)
1691 create_android_sdk_rule(environ_cp)
Austin Anderson6afface2017-12-05 11:59:17 -08001692
Gunhan Gulsoy34370982018-10-12 15:26:01 -07001693 print('Preconfigured Bazel build configs. You can use any of the below by '
1694 'adding "--config=<>" to your build command. See .bazelrc for more '
1695 'details.')
1696 config_info_line('mkl', 'Build with MKL support.')
1697 config_info_line('monolithic', 'Config for mostly static monolithic build.')
1698 config_info_line('gdr', 'Build with GDR support.')
1699 config_info_line('verbs', 'Build with libverbs support.')
1700 config_info_line('ngraph', 'Build with Intel nGraph support.')
Gunhan Gulsoy594aae22018-10-18 14:48:00 -07001701 config_info_line('dynamic_kernels',
1702 '(Experimental) Build kernels into separate shared objects.')
Gunhan Gulsoy34370982018-10-12 15:26:01 -07001703
1704 print('Preconfigured Bazel build configs to DISABLE default on features:')
1705 config_info_line('noaws', 'Disable AWS S3 filesystem support.')
1706 config_info_line('nogcp', 'Disable GCP support.')
1707 config_info_line('nohdfs', 'Disable HDFS support.')
1708 config_info_line('noignite', 'Disable Apacha Ignite support.')
1709 config_info_line('nokafka', 'Disable Apache Kafka support.')
Gunhan Gulsoyeea81682018-11-26 16:51:23 -08001710 config_info_line('nonccl', 'Disable NVIDIA NCCL support.')
Austin Anderson6afface2017-12-05 11:59:17 -08001711
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001712
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001713if __name__ == '__main__':
1714 main()