blob: 129d9c5fe7cf6015a0884ce7b49fe7af74f9ec4d [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 Hinsu63e6b9b2018-07-13 12:46:24 -070038_DEFAULT_NCCL_VERSION = '2.2'
Smit Hinsufe7d1d92018-07-14 13:16:58 -070039_DEFAULT_CUDA_COMPUTE_CAPABILITIES = '3.5,7.0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070040_DEFAULT_CUDA_PATH = '/usr/local/cuda'
41_DEFAULT_CUDA_PATH_LINUX = '/opt/cuda'
42_DEFAULT_CUDA_PATH_WIN = ('C:/Program Files/NVIDIA GPU Computing '
43 'Toolkit/CUDA/v%s' % _DEFAULT_CUDA_VERSION)
44_TF_OPENCL_VERSION = '1.2'
45_DEFAULT_COMPUTECPP_TOOLKIT_PATH = '/usr/local/computecpp'
Yifei Fengb1d8c592017-11-22 13:42:21 -080046_DEFAULT_TRISYCL_INCLUDE_DIR = '/usr/local/triSYCL/include'
A. Unique TensorFlowerd340f472018-08-30 14:00:41 -070047_SUPPORTED_ANDROID_NDK_VERSIONS = [10, 11, 12, 13, 14, 15, 16]
Austin Anderson6afface2017-12-05 11:59:17 -080048
49_DEFAULT_PROMPT_ASK_ATTEMPTS = 10
50
Shanqing Cai71445712018-03-12 19:33:52 -070051_TF_WORKSPACE_ROOT = os.path.abspath(os.path.dirname(__file__))
52_TF_BAZELRC_FILENAME = '.tf_configure.bazelrc'
53_TF_BAZELRC = os.path.join(_TF_WORKSPACE_ROOT, _TF_BAZELRC_FILENAME)
54_TF_WORKSPACE = os.path.join(_TF_WORKSPACE_ROOT, 'WORKSPACE')
55
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -070056if platform.machine() == 'ppc64le':
57 _DEFAULT_TENSORRT_PATH_LINUX = '/usr/lib/powerpc64le-linux-gnu/'
58else:
59 _DEFAULT_TENSORRT_PATH_LINUX = '/usr/lib/%s-linux-gnu' % platform.machine()
60
Austin Anderson6afface2017-12-05 11:59:17 -080061
62class UserInputError(Exception):
63 pass
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070064
65
66def is_windows():
67 return platform.system() == 'Windows'
68
69
70def is_linux():
71 return platform.system() == 'Linux'
72
73
74def is_macos():
75 return platform.system() == 'Darwin'
76
77
78def is_ppc64le():
79 return platform.machine() == 'ppc64le'
80
81
Jonathan Hseu008910f2017-08-25 14:01:05 -070082def is_cygwin():
83 return platform.system().startswith('CYGWIN_NT')
84
85
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070086def get_input(question):
87 try:
88 try:
89 answer = raw_input(question)
90 except NameError:
91 answer = input(question) # pylint: disable=bad-builtin
92 except EOFError:
93 answer = ''
94 return answer
95
96
97def symlink_force(target, link_name):
98 """Force symlink, equivalent of 'ln -sf'.
99
100 Args:
101 target: items to link to.
102 link_name: name of the link.
103 """
104 try:
105 os.symlink(target, link_name)
106 except OSError as e:
107 if e.errno == errno.EEXIST:
108 os.remove(link_name)
109 os.symlink(target, link_name)
110 else:
111 raise e
112
113
114def sed_in_place(filename, old, new):
115 """Replace old string with new string in file.
116
117 Args:
118 filename: string for filename.
119 old: string to replace.
120 new: new string to replace to.
121 """
122 with open(filename, 'r') as f:
123 filedata = f.read()
124 newdata = filedata.replace(old, new)
125 with open(filename, 'w') as f:
126 f.write(newdata)
127
128
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700129def write_to_bazelrc(line):
130 with open(_TF_BAZELRC, 'a') as f:
131 f.write(line + '\n')
132
133
134def write_action_env_to_bazelrc(var_name, var):
135 write_to_bazelrc('build --action_env %s="%s"' % (var_name, str(var)))
136
137
Jonathan Hseu008910f2017-08-25 14:01:05 -0700138def run_shell(cmd, allow_non_zero=False):
139 if allow_non_zero:
140 try:
141 output = subprocess.check_output(cmd)
142 except subprocess.CalledProcessError as e:
143 output = e.output
144 else:
145 output = subprocess.check_output(cmd)
146 return output.decode('UTF-8').strip()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700147
148
149def cygpath(path):
150 """Convert path from posix to windows."""
Martin Wicked57572e2017-09-02 19:21:45 -0700151 return os.path.abspath(path).replace('\\', '/')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700152
153
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700154def get_python_path(environ_cp, python_bin_path):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700155 """Get the python site package paths."""
156 python_paths = []
157 if environ_cp.get('PYTHONPATH'):
158 python_paths = environ_cp.get('PYTHONPATH').split(':')
159 try:
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700160 library_paths = run_shell([
161 python_bin_path, '-c',
162 'import site; print("\\n".join(site.getsitepackages()))'
163 ]).split('\n')
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700164 except subprocess.CalledProcessError:
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700165 library_paths = [
166 run_shell([
167 python_bin_path, '-c',
168 'from distutils.sysconfig import get_python_lib;'
169 'print(get_python_lib())'
170 ])
171 ]
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700172
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700173 all_paths = set(python_paths + library_paths)
174
175 paths = []
176 for path in all_paths:
177 if os.path.isdir(path):
178 paths.append(path)
179 return paths
180
181
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700182def get_python_major_version(python_bin_path):
183 """Get the python major version."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700184 return run_shell([python_bin_path, '-c', 'import sys; print(sys.version[0])'])
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700185
186
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700187def setup_python(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700188 """Setup python related env variables."""
189 # Get PYTHON_BIN_PATH, default is the current running python.
190 default_python_bin_path = sys.executable
191 ask_python_bin_path = ('Please specify the location of python. [Default is '
192 '%s]: ') % default_python_bin_path
193 while True:
194 python_bin_path = get_from_env_or_user_or_default(
195 environ_cp, 'PYTHON_BIN_PATH', ask_python_bin_path,
196 default_python_bin_path)
197 # Check if the path is valid
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700198 if os.path.isfile(python_bin_path) and os.access(python_bin_path, os.X_OK):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700199 break
200 elif not os.path.exists(python_bin_path):
201 print('Invalid python path: %s cannot be found.' % python_bin_path)
202 else:
203 print('%s is not executable. Is it the python binary?' % python_bin_path)
204 environ_cp['PYTHON_BIN_PATH'] = ''
205
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700206 # Convert python path to Windows style before checking lib and version
Martin Wicked57572e2017-09-02 19:21:45 -0700207 if is_windows() or is_cygwin():
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700208 python_bin_path = cygpath(python_bin_path)
209
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700210 # Get PYTHON_LIB_PATH
211 python_lib_path = environ_cp.get('PYTHON_LIB_PATH')
212 if not python_lib_path:
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700213 python_lib_paths = get_python_path(environ_cp, python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700214 if environ_cp.get('USE_DEFAULT_PYTHON_LIB_PATH') == '1':
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700215 python_lib_path = python_lib_paths[0]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700216 else:
Jonathan Hseu008910f2017-08-25 14:01:05 -0700217 print('Found possible Python library paths:\n %s' %
218 '\n '.join(python_lib_paths))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700219 default_python_lib_path = python_lib_paths[0]
220 python_lib_path = get_input(
Jonathan Hseu008910f2017-08-25 14:01:05 -0700221 'Please input the desired Python library path to use. '
222 'Default is [%s]\n' % python_lib_paths[0])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700223 if not python_lib_path:
224 python_lib_path = default_python_lib_path
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700225 environ_cp['PYTHON_LIB_PATH'] = python_lib_path
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700226
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700227 python_major_version = get_python_major_version(python_bin_path)
228
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700229 # Convert python path to Windows style before writing into bazel.rc
Martin Wicked57572e2017-09-02 19:21:45 -0700230 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700231 python_lib_path = cygpath(python_lib_path)
232
233 # Set-up env variables used by python_configure.bzl
234 write_action_env_to_bazelrc('PYTHON_BIN_PATH', python_bin_path)
235 write_action_env_to_bazelrc('PYTHON_LIB_PATH', python_lib_path)
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700236 write_to_bazelrc('build --python_path=\"%s"' % python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700237 environ_cp['PYTHON_BIN_PATH'] = python_bin_path
238
239 # Write tools/python_bin_path.sh
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700240 with open(
241 os.path.join(_TF_WORKSPACE_ROOT, 'tools', 'python_bin_path.sh'),
242 'w') as f:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700243 f.write('export PYTHON_BIN_PATH="%s"' % python_bin_path)
244
245
Shanqing Cai71445712018-03-12 19:33:52 -0700246def reset_tf_configure_bazelrc(workspace_path):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700247 """Reset file that contains customized config settings."""
248 open(_TF_BAZELRC, 'w').close()
Shanqing Cai71445712018-03-12 19:33:52 -0700249 bazelrc_path = os.path.join(workspace_path, '.bazelrc')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700250
Shanqing Cai71445712018-03-12 19:33:52 -0700251 data = []
252 if os.path.exists(bazelrc_path):
253 with open(bazelrc_path, 'r') as f:
254 data = f.read().splitlines()
255 with open(bazelrc_path, 'w') as f:
256 for l in data:
257 if _TF_BAZELRC_FILENAME in l:
258 continue
259 f.write('%s\n' % l)
Jason Zamand3f6b722018-08-04 14:28:02 +0800260 f.write('import %%workspace%%/%s\n' % _TF_BAZELRC_FILENAME)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700261
262
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700263def cleanup_makefile():
264 """Delete any leftover BUILD files from the Makefile build.
265
266 These files could interfere with Bazel parsing.
267 """
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700268 makefile_download_dir = os.path.join(_TF_WORKSPACE_ROOT, 'tensorflow',
269 'contrib', 'makefile', 'downloads')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700270 if os.path.isdir(makefile_download_dir):
271 for root, _, filenames in os.walk(makefile_download_dir):
272 for f in filenames:
273 if f.endswith('BUILD'):
274 os.remove(os.path.join(root, f))
275
276
277def get_var(environ_cp,
278 var_name,
279 query_item,
280 enabled_by_default,
281 question=None,
282 yes_reply=None,
283 no_reply=None):
284 """Get boolean input from user.
285
286 If var_name is not set in env, ask user to enable query_item or not. If the
287 response is empty, use the default.
288
289 Args:
290 environ_cp: copy of the os.environ.
291 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
292 query_item: string for feature related to the variable, e.g. "Hadoop File
293 System".
294 enabled_by_default: boolean for default behavior.
295 question: optional string for how to ask for user input.
Michael Cased90054e2018-02-07 14:36:00 -0800296 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700297 no_reply: optional string for reply when feature is disabled.
298
299 Returns:
300 boolean value of the variable.
Frank Chenc4ef9272018-01-10 11:36:52 -0800301
302 Raises:
303 UserInputError: if an environment variable is set, but it cannot be
304 interpreted as a boolean indicator, assume that the user has made a
305 scripting error, and will continue to provide invalid input.
306 Raise the error to avoid infinitely looping.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700307 """
308 if not question:
309 question = 'Do you wish to build TensorFlow with %s support?' % query_item
310 if not yes_reply:
311 yes_reply = '%s support will be enabled for TensorFlow.' % query_item
312 if not no_reply:
313 no_reply = 'No %s' % yes_reply
314
315 yes_reply += '\n'
316 no_reply += '\n'
317
318 if enabled_by_default:
319 question += ' [Y/n]: '
320 else:
321 question += ' [y/N]: '
322
323 var = environ_cp.get(var_name)
Frank Chenc4ef9272018-01-10 11:36:52 -0800324 if var is not None:
325 var_content = var.strip().lower()
326 true_strings = ('1', 't', 'true', 'y', 'yes')
327 false_strings = ('0', 'f', 'false', 'n', 'no')
328 if var_content in true_strings:
329 var = True
330 elif var_content in false_strings:
331 var = False
332 else:
333 raise UserInputError(
334 'Environment variable %s must be set as a boolean indicator.\n'
335 'The following are accepted as TRUE : %s.\n'
336 'The following are accepted as FALSE: %s.\n'
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700337 'Current value is %s.' % (var_name, ', '.join(true_strings),
338 ', '.join(false_strings), var))
Frank Chenc4ef9272018-01-10 11:36:52 -0800339
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700340 while var is None:
341 user_input_origin = get_input(question)
342 user_input = user_input_origin.strip().lower()
343 if user_input == 'y':
344 print(yes_reply)
345 var = True
346 elif user_input == 'n':
347 print(no_reply)
348 var = False
349 elif not user_input:
350 if enabled_by_default:
351 print(yes_reply)
352 var = True
353 else:
354 print(no_reply)
355 var = False
356 else:
357 print('Invalid selection: %s' % user_input_origin)
358 return var
359
360
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700361def set_build_var(environ_cp,
362 var_name,
363 query_item,
364 option_name,
365 enabled_by_default,
366 bazel_config_name=None):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700367 """Set if query_item will be enabled for the build.
368
369 Ask user if query_item will be enabled. Default is used if no input is given.
370 Set subprocess environment variable and write to .bazelrc if enabled.
371
372 Args:
373 environ_cp: copy of the os.environ.
374 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
375 query_item: string for feature related to the variable, e.g. "Hadoop File
376 System".
377 option_name: string for option to define in .bazelrc.
378 enabled_by_default: boolean for default behavior.
Michael Case98850a52017-09-14 13:35:57 -0700379 bazel_config_name: Name for Bazel --config argument to enable build feature.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700380 """
381
382 var = str(int(get_var(environ_cp, var_name, query_item, enabled_by_default)))
383 environ_cp[var_name] = var
384 if var == '1':
385 write_to_bazelrc('build --define %s=true' % option_name)
Michael Case98850a52017-09-14 13:35:57 -0700386 elif bazel_config_name is not None:
387 # TODO(mikecase): Migrate all users of configure.py to use --config Bazel
388 # options and not to set build configs through environment variables.
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700389 write_to_bazelrc(
390 'build:%s --define %s=true' % (bazel_config_name, option_name))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700391
392
393def set_action_env_var(environ_cp,
394 var_name,
395 query_item,
396 enabled_by_default,
397 question=None,
398 yes_reply=None,
399 no_reply=None):
400 """Set boolean action_env variable.
401
402 Ask user if query_item will be enabled. Default is used if no input is given.
403 Set environment variable and write to .bazelrc.
404
405 Args:
406 environ_cp: copy of the os.environ.
407 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
408 query_item: string for feature related to the variable, e.g. "Hadoop File
409 System".
410 enabled_by_default: boolean for default behavior.
411 question: optional string for how to ask for user input.
Michael Cased90054e2018-02-07 14:36:00 -0800412 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700413 no_reply: optional string for reply when feature is disabled.
414 """
415 var = int(
416 get_var(environ_cp, var_name, query_item, enabled_by_default, question,
417 yes_reply, no_reply))
418
419 write_action_env_to_bazelrc(var_name, var)
420 environ_cp[var_name] = str(var)
421
422
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700423def convert_version_to_int(version):
424 """Convert a version number to a integer that can be used to compare.
425
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700426 Version strings of the form X.YZ and X.Y.Z-xxxxx are supported. The
427 'xxxxx' part, for instance 'homebrew' on OS/X, is ignored.
428
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700429 Args:
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700430 version: a version to be converted
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700431
432 Returns:
433 An integer if converted successfully, otherwise return None.
434 """
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700435 version = version.split('-')[0]
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700436 version_segments = version.split('.')
437 for seg in version_segments:
438 if not seg.isdigit():
439 return None
440
441 version_str = ''.join(['%03d' % int(seg) for seg in version_segments])
442 return int(version_str)
443
444
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700445def check_bazel_version(min_version):
Yifei Fengdce9a492018-02-22 14:24:57 -0800446 """Check installed bazel version is at least min_version.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700447
448 Args:
449 min_version: string for minimum bazel version.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700450
451 Returns:
452 The bazel version detected.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700453 """
Jonathan Hseu008910f2017-08-25 14:01:05 -0700454 if which('bazel') is None:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700455 print('Cannot find bazel. Please install bazel.')
456 sys.exit(0)
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700457 curr_version = run_shell(
458 ['bazel', '--batch', '--bazelrc=/dev/null', 'version'])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700459
460 for line in curr_version.split('\n'):
461 if 'Build label: ' in line:
462 curr_version = line.split('Build label: ')[1]
463 break
464
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700465 min_version_int = convert_version_to_int(min_version)
466 curr_version_int = convert_version_to_int(curr_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700467
468 # Check if current bazel version can be detected properly.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700469 if not curr_version_int:
470 print('WARNING: current bazel installation is not a release version.')
471 print('Make sure you are running at least bazel %s' % min_version)
472 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700473
Michael Cased94271a2017-08-22 17:26:52 -0700474 print('You have bazel %s installed.' % curr_version)
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700475
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700476 if curr_version_int < min_version_int:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700477 print('Please upgrade your bazel installation to version %s or higher to '
478 'build TensorFlow!' % min_version)
479 sys.exit(0)
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700480 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700481
482
483def set_cc_opt_flags(environ_cp):
484 """Set up architecture-dependent optimization flags.
485
486 Also append CC optimization flags to bazel.rc..
487
488 Args:
489 environ_cp: copy of the os.environ.
490 """
491 if is_ppc64le():
492 # gcc on ppc64le does not support -march, use mcpu instead
493 default_cc_opt_flags = '-mcpu=native'
A. Unique TensorFlower1bba94a2018-04-04 15:45:20 -0700494 elif is_windows():
495 default_cc_opt_flags = '/arch:AVX'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700496 else:
497 default_cc_opt_flags = '-march=native'
498 question = ('Please specify optimization flags to use during compilation when'
499 ' bazel option "--config=opt" is specified [Default is %s]: '
500 ) % default_cc_opt_flags
501 cc_opt_flags = get_from_env_or_user_or_default(environ_cp, 'CC_OPT_FLAGS',
502 question, default_cc_opt_flags)
503 for opt in cc_opt_flags.split():
Michael Case00177422017-11-10 13:14:03 -0800504 write_to_bazelrc('build:opt --copt=%s' % opt)
505 # It should be safe on the same build host.
A. Unique TensorFlower1bba94a2018-04-04 15:45:20 -0700506 if not is_ppc64le() and not is_windows():
Shanqing Cai71445712018-03-12 19:33:52 -0700507 write_to_bazelrc('build:opt --host_copt=-march=native')
Michael Casebb3355d2017-11-09 08:46:31 -0800508 write_to_bazelrc('build:opt --define with_default_optimizations=true')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700509
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700510
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700511def set_tf_cuda_clang(environ_cp):
512 """set TF_CUDA_CLANG action_env.
513
514 Args:
515 environ_cp: copy of the os.environ.
516 """
517 question = 'Do you want to use clang as CUDA compiler?'
518 yes_reply = 'Clang will be used as CUDA compiler.'
519 no_reply = 'nvcc will be used as CUDA compiler.'
520 set_action_env_var(
521 environ_cp,
522 'TF_CUDA_CLANG',
523 None,
524 False,
525 question=question,
526 yes_reply=yes_reply,
527 no_reply=no_reply)
528
529
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800530def set_tf_download_clang(environ_cp):
531 """Set TF_DOWNLOAD_CLANG action_env."""
Ilya Biryukov9e651e42018-03-22 05:33:42 -0700532 question = 'Do you wish to download a fresh release of clang? (Experimental)'
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800533 yes_reply = 'Clang will be downloaded and used to compile tensorflow.'
534 no_reply = 'Clang will not be downloaded.'
535 set_action_env_var(
536 environ_cp,
537 'TF_DOWNLOAD_CLANG',
538 None,
539 False,
540 question=question,
541 yes_reply=yes_reply,
542 no_reply=no_reply)
543
544
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700545def get_from_env_or_user_or_default(environ_cp, var_name, ask_for_var,
546 var_default):
547 """Get var_name either from env, or user or default.
548
549 If var_name has been set as environment variable, use the preset value, else
550 ask for user input. If no input is provided, the default is used.
551
552 Args:
553 environ_cp: copy of the os.environ.
554 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
555 ask_for_var: string for how to ask for user input.
556 var_default: default value string.
557
558 Returns:
559 string value for var_name
560 """
561 var = environ_cp.get(var_name)
562 if not var:
563 var = get_input(ask_for_var)
Michael Cased94271a2017-08-22 17:26:52 -0700564 print('\n')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700565 if not var:
566 var = var_default
567 return var
568
569
570def set_clang_cuda_compiler_path(environ_cp):
571 """Set CLANG_CUDA_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700572 default_clang_path = which('clang') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700573 ask_clang_path = ('Please specify which clang should be used as device and '
574 'host compiler. [Default is %s]: ') % default_clang_path
575
576 while True:
577 clang_cuda_compiler_path = get_from_env_or_user_or_default(
578 environ_cp, 'CLANG_CUDA_COMPILER_PATH', ask_clang_path,
579 default_clang_path)
580 if os.path.exists(clang_cuda_compiler_path):
581 break
582
583 # Reset and retry
584 print('Invalid clang path: %s cannot be found.' % clang_cuda_compiler_path)
585 environ_cp['CLANG_CUDA_COMPILER_PATH'] = ''
586
587 # Set CLANG_CUDA_COMPILER_PATH
588 environ_cp['CLANG_CUDA_COMPILER_PATH'] = clang_cuda_compiler_path
589 write_action_env_to_bazelrc('CLANG_CUDA_COMPILER_PATH',
590 clang_cuda_compiler_path)
591
592
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700593def prompt_loop_or_load_from_env(environ_cp,
594 var_name,
595 var_default,
596 ask_for_var,
597 check_success,
598 error_msg,
599 suppress_default_error=False,
600 n_ask_attempts=_DEFAULT_PROMPT_ASK_ATTEMPTS):
Austin Anderson6afface2017-12-05 11:59:17 -0800601 """Loop over user prompts for an ENV param until receiving a valid response.
602
603 For the env param var_name, read from the environment or verify user input
604 until receiving valid input. When done, set var_name in the environ_cp to its
605 new value.
606
607 Args:
608 environ_cp: (Dict) copy of the os.environ.
609 var_name: (String) string for name of environment variable, e.g. "TF_MYVAR".
610 var_default: (String) default value string.
611 ask_for_var: (String) string for how to ask for user input.
612 check_success: (Function) function that takes one argument and returns a
613 boolean. Should return True if the value provided is considered valid. May
614 contain a complex error message if error_msg does not provide enough
615 information. In that case, set suppress_default_error to True.
616 error_msg: (String) String with one and only one '%s'. Formatted with each
617 invalid response upon check_success(input) failure.
618 suppress_default_error: (Bool) Suppress the above error message in favor of
619 one from the check_success function.
620 n_ask_attempts: (Integer) Number of times to query for valid input before
621 raising an error and quitting.
622
623 Returns:
624 [String] The value of var_name after querying for input.
625
626 Raises:
627 UserInputError: if a query has been attempted n_ask_attempts times without
Frank Chenc4ef9272018-01-10 11:36:52 -0800628 success, assume that the user has made a scripting error, and will
629 continue to provide invalid input. Raise the error to avoid infinitely
630 looping.
Austin Anderson6afface2017-12-05 11:59:17 -0800631 """
632 default = environ_cp.get(var_name) or var_default
633 full_query = '%s [Default is %s]: ' % (
634 ask_for_var,
635 default,
636 )
637
638 for _ in range(n_ask_attempts):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700639 val = get_from_env_or_user_or_default(environ_cp, var_name, full_query,
Austin Anderson6afface2017-12-05 11:59:17 -0800640 default)
641 if check_success(val):
642 break
643 if not suppress_default_error:
644 print(error_msg % val)
645 environ_cp[var_name] = ''
646 else:
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700647 raise UserInputError(
648 'Invalid %s setting was provided %d times in a row. '
649 'Assuming to be a scripting mistake.' % (var_name, n_ask_attempts))
Austin Anderson6afface2017-12-05 11:59:17 -0800650
651 environ_cp[var_name] = val
652 return val
653
654
655def create_android_ndk_rule(environ_cp):
656 """Set ANDROID_NDK_HOME and write Android NDK WORKSPACE rule."""
657 if is_windows() or is_cygwin():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700658 default_ndk_path = cygpath(
659 '%s/Android/Sdk/ndk-bundle' % environ_cp['APPDATA'])
Austin Anderson6afface2017-12-05 11:59:17 -0800660 elif is_macos():
661 default_ndk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
662 else:
663 default_ndk_path = '%s/Android/Sdk/ndk-bundle' % environ_cp['HOME']
664
665 def valid_ndk_path(path):
666 return (os.path.exists(path) and
667 os.path.exists(os.path.join(path, 'source.properties')))
668
669 android_ndk_home_path = prompt_loop_or_load_from_env(
670 environ_cp,
671 var_name='ANDROID_NDK_HOME',
672 var_default=default_ndk_path,
673 ask_for_var='Please specify the home path of the Android NDK to use.',
674 check_success=valid_ndk_path,
675 error_msg=('The path %s or its child file "source.properties" '
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700676 'does not exist.'))
Michael Case51053502018-06-05 17:47:19 -0700677 write_action_env_to_bazelrc('ANDROID_NDK_HOME', android_ndk_home_path)
678 write_action_env_to_bazelrc('ANDROID_NDK_API_LEVEL',
679 check_ndk_level(android_ndk_home_path))
Austin Anderson6afface2017-12-05 11:59:17 -0800680
681
682def create_android_sdk_rule(environ_cp):
683 """Set Android variables and write Android SDK WORKSPACE rule."""
684 if is_windows() or is_cygwin():
685 default_sdk_path = cygpath('%s/Android/Sdk' % environ_cp['APPDATA'])
686 elif is_macos():
Shashi Shekharc0ff0cc2018-07-17 09:00:24 -0700687 default_sdk_path = '%s/library/Android/Sdk' % environ_cp['HOME']
Austin Anderson6afface2017-12-05 11:59:17 -0800688 else:
689 default_sdk_path = '%s/Android/Sdk' % environ_cp['HOME']
690
691 def valid_sdk_path(path):
692 return (os.path.exists(path) and
693 os.path.exists(os.path.join(path, 'platforms')) and
694 os.path.exists(os.path.join(path, 'build-tools')))
695
696 android_sdk_home_path = prompt_loop_or_load_from_env(
697 environ_cp,
698 var_name='ANDROID_SDK_HOME',
699 var_default=default_sdk_path,
700 ask_for_var='Please specify the home path of the Android SDK to use.',
701 check_success=valid_sdk_path,
702 error_msg=('Either %s does not exist, or it does not contain the '
703 'subdirectories "platforms" and "build-tools".'))
704
705 platforms = os.path.join(android_sdk_home_path, 'platforms')
706 api_levels = sorted(os.listdir(platforms))
707 api_levels = [x.replace('android-', '') for x in api_levels]
708
709 def valid_api_level(api_level):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700710 return os.path.exists(
711 os.path.join(android_sdk_home_path, 'platforms',
712 'android-' + api_level))
Austin Anderson6afface2017-12-05 11:59:17 -0800713
714 android_api_level = prompt_loop_or_load_from_env(
715 environ_cp,
716 var_name='ANDROID_API_LEVEL',
717 var_default=api_levels[-1],
718 ask_for_var=('Please specify the Android SDK API level to use. '
719 '[Available levels: %s]') % api_levels,
720 check_success=valid_api_level,
721 error_msg='Android-%s is not present in the SDK path.')
722
723 build_tools = os.path.join(android_sdk_home_path, 'build-tools')
724 versions = sorted(os.listdir(build_tools))
725
726 def valid_build_tools(version):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700727 return os.path.exists(
728 os.path.join(android_sdk_home_path, 'build-tools', version))
Austin Anderson6afface2017-12-05 11:59:17 -0800729
730 android_build_tools_version = prompt_loop_or_load_from_env(
731 environ_cp,
732 var_name='ANDROID_BUILD_TOOLS_VERSION',
733 var_default=versions[-1],
734 ask_for_var=('Please specify an Android build tools version to use. '
735 '[Available versions: %s]') % versions,
736 check_success=valid_build_tools,
737 error_msg=('The selected SDK does not have build-tools version %s '
738 'available.'))
739
Michael Case51053502018-06-05 17:47:19 -0700740 write_action_env_to_bazelrc('ANDROID_BUILD_TOOLS_VERSION',
741 android_build_tools_version)
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700742 write_action_env_to_bazelrc('ANDROID_SDK_API_LEVEL', android_api_level)
743 write_action_env_to_bazelrc('ANDROID_SDK_HOME', android_sdk_home_path)
Austin Anderson6afface2017-12-05 11:59:17 -0800744
745
746def check_ndk_level(android_ndk_home_path):
747 """Check the revision number of an Android NDK path."""
748 properties_path = '%s/source.properties' % android_ndk_home_path
749 if is_windows() or is_cygwin():
750 properties_path = cygpath(properties_path)
751 with open(properties_path, 'r') as f:
752 filedata = f.read()
753
754 revision = re.search(r'Pkg.Revision = (\d+)', filedata)
755 if revision:
Michael Case51053502018-06-05 17:47:19 -0700756 ndk_api_level = revision.group(1)
757 else:
758 raise Exception('Unable to parse NDK revision.')
759 if int(ndk_api_level) not in _SUPPORTED_ANDROID_NDK_VERSIONS:
760 print('WARNING: The API level of the NDK in %s is %s, which is not '
761 'supported by Bazel (officially supported versions: %s). Please use '
762 'another version. Compiling Android targets may result in confusing '
763 'errors.\n' % (android_ndk_home_path, ndk_api_level,
764 _SUPPORTED_ANDROID_NDK_VERSIONS))
765 return ndk_api_level
Austin Anderson6afface2017-12-05 11:59:17 -0800766
767
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700768def set_gcc_host_compiler_path(environ_cp):
769 """Set GCC_HOST_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700770 default_gcc_host_compiler_path = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700771 cuda_bin_symlink = '%s/bin/gcc' % environ_cp.get('CUDA_TOOLKIT_PATH')
772
773 if os.path.islink(cuda_bin_symlink):
774 # os.readlink is only available in linux
Jonathan Hseu008910f2017-08-25 14:01:05 -0700775 default_gcc_host_compiler_path = os.path.realpath(cuda_bin_symlink)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700776
Austin Anderson6afface2017-12-05 11:59:17 -0800777 gcc_host_compiler_path = prompt_loop_or_load_from_env(
778 environ_cp,
779 var_name='GCC_HOST_COMPILER_PATH',
780 var_default=default_gcc_host_compiler_path,
781 ask_for_var=
782 'Please specify which gcc should be used by nvcc as the host compiler.',
783 check_success=os.path.exists,
784 error_msg='Invalid gcc path. %s cannot be found.',
785 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700786
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700787 write_action_env_to_bazelrc('GCC_HOST_COMPILER_PATH', gcc_host_compiler_path)
788
789
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800790def reformat_version_sequence(version_str, sequence_count):
791 """Reformat the version string to have the given number of sequences.
792
793 For example:
794 Given (7, 2) -> 7.0
795 (7.0.1, 2) -> 7.0
796 (5, 1) -> 5
797 (5.0.3.2, 1) -> 5
798
799 Args:
800 version_str: String, the version string.
801 sequence_count: int, an integer.
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700802
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800803 Returns:
804 string, reformatted version string.
805 """
806 v = version_str.split('.')
807 if len(v) < sequence_count:
808 v = v + (['0'] * (sequence_count - len(v)))
809
810 return '.'.join(v[:sequence_count])
811
812
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700813def set_tf_cuda_version(environ_cp):
814 """Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION."""
815 ask_cuda_version = (
A. Unique TensorFlowerb15500b2018-05-08 12:04:38 -0700816 'Please specify the CUDA SDK version you want to use. '
817 '[Leave empty to default to CUDA %s]: ') % _DEFAULT_CUDA_VERSION
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700818
Austin Andersonf9a88f82017-12-13 11:49:40 -0800819 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700820 # Configure the Cuda SDK version to use.
821 tf_cuda_version = get_from_env_or_user_or_default(
822 environ_cp, 'TF_CUDA_VERSION', ask_cuda_version, _DEFAULT_CUDA_VERSION)
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800823 tf_cuda_version = reformat_version_sequence(str(tf_cuda_version), 2)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700824
825 # Find out where the CUDA toolkit is installed
826 default_cuda_path = _DEFAULT_CUDA_PATH
Martin Wicked57572e2017-09-02 19:21:45 -0700827 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700828 default_cuda_path = cygpath(
829 environ_cp.get('CUDA_PATH', _DEFAULT_CUDA_PATH_WIN))
830 elif is_linux():
831 # If the default doesn't exist, try an alternative default.
832 if (not os.path.exists(default_cuda_path)
833 ) and os.path.exists(_DEFAULT_CUDA_PATH_LINUX):
834 default_cuda_path = _DEFAULT_CUDA_PATH_LINUX
835 ask_cuda_path = ('Please specify the location where CUDA %s toolkit is'
836 ' installed. Refer to README.md for more details. '
837 '[Default is %s]: ') % (tf_cuda_version, default_cuda_path)
838 cuda_toolkit_path = get_from_env_or_user_or_default(
839 environ_cp, 'CUDA_TOOLKIT_PATH', ask_cuda_path, default_cuda_path)
A. Unique TensorFlower02f17fe2018-07-07 06:59:19 -0700840 if is_windows() or is_cygwin():
841 cuda_toolkit_path = cygpath(cuda_toolkit_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700842
843 if is_windows():
Niall Moranb7d97e82018-08-09 00:29:49 +0100844 cuda_rt_lib_paths = ['lib/x64/cudart.lib']
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700845 elif is_linux():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700846 cuda_rt_lib_paths = [
847 '%s/libcudart.so.%s' % (x, tf_cuda_version) for x in [
848 'lib64',
849 'lib/powerpc64le-linux-gnu',
850 'lib/x86_64-linux-gnu',
851 ]
852 ]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700853 elif is_macos():
Niall Moranb7d97e82018-08-09 00:29:49 +0100854 cuda_rt_lib_paths = ['lib/libcudart.%s.dylib' % tf_cuda_version]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700855
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700856 cuda_toolkit_paths_full = [
857 os.path.join(cuda_toolkit_path, x) for x in cuda_rt_lib_paths
858 ]
Niall Moranb7d97e82018-08-09 00:29:49 +0100859 if any([os.path.exists(x) for x in cuda_toolkit_paths_full]):
Yifei Feng5198cb82018-08-17 13:53:06 -0700860 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700861
862 # Reset and retry
863 print('Invalid path to CUDA %s toolkit. %s cannot be found' %
hellcom9a13fc32018-09-12 10:58:24 +0300864 (tf_cuda_version, cuda_toolkit_paths_full))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700865 environ_cp['TF_CUDA_VERSION'] = ''
866 environ_cp['CUDA_TOOLKIT_PATH'] = ''
867
Austin Andersonf9a88f82017-12-13 11:49:40 -0800868 else:
869 raise UserInputError('Invalid TF_CUDA_SETTING setting was provided %d '
870 'times in a row. Assuming to be a scripting mistake.' %
871 _DEFAULT_PROMPT_ASK_ATTEMPTS)
872
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700873 # Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION
874 environ_cp['CUDA_TOOLKIT_PATH'] = cuda_toolkit_path
875 write_action_env_to_bazelrc('CUDA_TOOLKIT_PATH', cuda_toolkit_path)
876 environ_cp['TF_CUDA_VERSION'] = tf_cuda_version
877 write_action_env_to_bazelrc('TF_CUDA_VERSION', tf_cuda_version)
878
879
Yifei Fengb1d8c592017-11-22 13:42:21 -0800880def set_tf_cudnn_version(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700881 """Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION."""
882 ask_cudnn_version = (
Jonathan Hseu008910f2017-08-25 14:01:05 -0700883 'Please specify the cuDNN version you want to use. '
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700884 '[Leave empty to default to cuDNN %s.0]: ') % _DEFAULT_CUDNN_VERSION
885
Austin Andersonf9a88f82017-12-13 11:49:40 -0800886 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700887 tf_cudnn_version = get_from_env_or_user_or_default(
888 environ_cp, 'TF_CUDNN_VERSION', ask_cudnn_version,
889 _DEFAULT_CUDNN_VERSION)
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800890 tf_cudnn_version = reformat_version_sequence(str(tf_cudnn_version), 1)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700891
892 default_cudnn_path = environ_cp.get('CUDA_TOOLKIT_PATH')
893 ask_cudnn_path = (r'Please specify the location where cuDNN %s library is '
894 'installed. Refer to README.md for more details. [Default'
A. Unique TensorFlower1b212352018-07-19 13:48:50 -0700895 ' is %s]: ') % (tf_cudnn_version, default_cudnn_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700896 cudnn_install_path = get_from_env_or_user_or_default(
897 environ_cp, 'CUDNN_INSTALL_PATH', ask_cudnn_path, default_cudnn_path)
898
899 # Result returned from "read" will be used unexpanded. That make "~"
900 # unusable. Going through one more level of expansion to handle that.
901 cudnn_install_path = os.path.realpath(
902 os.path.expanduser(cudnn_install_path))
Martin Wicked57572e2017-09-02 19:21:45 -0700903 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700904 cudnn_install_path = cygpath(cudnn_install_path)
905
906 if is_windows():
907 cuda_dnn_lib_path = 'lib/x64/cudnn.lib'
908 cuda_dnn_lib_alt_path = 'lib/x64/cudnn.lib'
909 elif is_linux():
910 cuda_dnn_lib_path = 'lib64/libcudnn.so.%s' % tf_cudnn_version
911 cuda_dnn_lib_alt_path = 'libcudnn.so.%s' % tf_cudnn_version
912 elif is_macos():
913 cuda_dnn_lib_path = 'lib/libcudnn.%s.dylib' % tf_cudnn_version
914 cuda_dnn_lib_alt_path = 'libcudnn.%s.dylib' % tf_cudnn_version
915
916 cuda_dnn_lib_path_full = os.path.join(cudnn_install_path, cuda_dnn_lib_path)
917 cuda_dnn_lib_alt_path_full = os.path.join(cudnn_install_path,
918 cuda_dnn_lib_alt_path)
919 if os.path.exists(cuda_dnn_lib_path_full) or os.path.exists(
920 cuda_dnn_lib_alt_path_full):
921 break
922
923 # Try another alternative for Linux
924 if is_linux():
Jonathan Hseu008910f2017-08-25 14:01:05 -0700925 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
926 cudnn_path_from_ldconfig = run_shell([ldconfig_bin, '-p'])
927 cudnn_path_from_ldconfig = re.search('.*libcudnn.so .* => (.*)',
A. Unique TensorFlowere7223582017-09-06 17:57:04 -0700928 cudnn_path_from_ldconfig)
929 if cudnn_path_from_ldconfig:
930 cudnn_path_from_ldconfig = cudnn_path_from_ldconfig.group(1)
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700931 if os.path.exists(
932 '%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version)):
A. Unique TensorFlowere7223582017-09-06 17:57:04 -0700933 cudnn_install_path = os.path.dirname(cudnn_path_from_ldconfig)
934 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700935
936 # Reset and Retry
937 print(
938 'Invalid path to cuDNN %s toolkit. None of the following files can be '
939 'found:' % tf_cudnn_version)
940 print(cuda_dnn_lib_path_full)
941 print(cuda_dnn_lib_alt_path_full)
942 if is_linux():
943 print('%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version))
944
945 environ_cp['TF_CUDNN_VERSION'] = ''
Austin Andersonf9a88f82017-12-13 11:49:40 -0800946 else:
947 raise UserInputError('Invalid TF_CUDNN setting was provided %d '
948 'times in a row. Assuming to be a scripting mistake.' %
949 _DEFAULT_PROMPT_ASK_ATTEMPTS)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700950
951 # Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION
952 environ_cp['CUDNN_INSTALL_PATH'] = cudnn_install_path
953 write_action_env_to_bazelrc('CUDNN_INSTALL_PATH', cudnn_install_path)
954 environ_cp['TF_CUDNN_VERSION'] = tf_cudnn_version
955 write_action_env_to_bazelrc('TF_CUDNN_VERSION', tf_cudnn_version)
956
957
Mingxing Tan1e7b0e42018-06-28 19:13:20 -0700958def is_cuda_compatible(lib, cuda_ver, cudnn_ver):
959 """Check compatibility between given library and cudnn/cudart libraries."""
960 ldd_bin = which('ldd') or '/usr/bin/ldd'
961 ldd_out = run_shell([ldd_bin, lib], True)
962 ldd_out = ldd_out.split(os.linesep)
963 cudnn_pattern = re.compile('.*libcudnn.so\\.?(.*) =>.*$')
964 cuda_pattern = re.compile('.*libcudart.so\\.?(.*) =>.*$')
965 cudnn = None
966 cudart = None
967 cudnn_ok = True # assume no cudnn dependency by default
968 cuda_ok = True # assume no cuda dependency by default
969 for line in ldd_out:
970 if 'libcudnn.so' in line:
971 cudnn = cudnn_pattern.search(line)
972 cudnn_ok = False
973 elif 'libcudart.so' in line:
974 cudart = cuda_pattern.search(line)
975 cuda_ok = False
976 if cudnn and len(cudnn.group(1)):
977 cudnn = convert_version_to_int(cudnn.group(1))
978 if cudart and len(cudart.group(1)):
979 cudart = convert_version_to_int(cudart.group(1))
980 if cudnn is not None:
981 cudnn_ok = (cudnn == cudnn_ver)
982 if cudart is not None:
983 cuda_ok = (cudart == cuda_ver)
984 return cudnn_ok and cuda_ok
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.
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001003 if str(int(get_var(environ_cp, 'TF_NEED_TENSORRT', 'TensorRT',
1004 False))) != '1':
Guangda Lai76f69382018-01-25 23:59:19 -08001005 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.
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001017 trt_install_path = os.path.realpath(os.path.expanduser(trt_install_path))
Guangda Lai76f69382018-01-25 23:59:19 -08001018
1019 def find_libs(search_path):
1020 """Search for libnvinfer.so in "search_path"."""
1021 fl = set()
1022 if os.path.exists(search_path) and os.path.isdir(search_path):
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001023 fl.update([
1024 os.path.realpath(os.path.join(search_path, x))
1025 for x in os.listdir(search_path)
1026 if 'libnvinfer.so' in x
1027 ])
Guangda Lai76f69382018-01-25 23:59:19 -08001028 return fl
1029
1030 possible_files = find_libs(trt_install_path)
1031 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib')))
1032 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib64')))
Guangda Lai76f69382018-01-25 23:59:19 -08001033 cuda_ver = convert_version_to_int(environ_cp['TF_CUDA_VERSION'])
1034 cudnn_ver = convert_version_to_int(environ_cp['TF_CUDNN_VERSION'])
1035 nvinfer_pattern = re.compile('.*libnvinfer.so.?(.*)$')
1036 highest_ver = [0, None, None]
1037
1038 for lib_file in possible_files:
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001039 if is_cuda_compatible(lib_file, cuda_ver, cudnn_ver):
Jacques Pienaar2d0531d2018-03-21 12:07:51 -07001040 matches = nvinfer_pattern.search(lib_file)
1041 if len(matches.groups()) == 0:
1042 continue
1043 ver_str = matches.group(1)
Guangda Lai76f69382018-01-25 23:59:19 -08001044 ver = convert_version_to_int(ver_str) if len(ver_str) else 0
1045 if ver > highest_ver[0]:
1046 highest_ver = [ver, ver_str, lib_file]
1047 if highest_ver[1] is not None:
1048 trt_install_path = os.path.dirname(highest_ver[2])
1049 tf_tensorrt_version = highest_ver[1]
1050 break
1051
1052 # Try another alternative from ldconfig.
1053 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
1054 ldconfig_output = run_shell([ldconfig_bin, '-p'])
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001055 search_result = re.search('.*libnvinfer.so\\.?([0-9.]*).* => (.*)',
1056 ldconfig_output)
Guangda Lai76f69382018-01-25 23:59:19 -08001057 if search_result:
1058 libnvinfer_path_from_ldconfig = search_result.group(2)
1059 if os.path.exists(libnvinfer_path_from_ldconfig):
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001060 if is_cuda_compatible(libnvinfer_path_from_ldconfig, cuda_ver,
1061 cudnn_ver):
Guangda Lai76f69382018-01-25 23:59:19 -08001062 trt_install_path = os.path.dirname(libnvinfer_path_from_ldconfig)
1063 tf_tensorrt_version = search_result.group(1)
1064 break
1065
1066 # Reset and Retry
Yifei Fengdce9a492018-02-22 14:24:57 -08001067 if possible_files:
1068 print('TensorRT libraries found in one the following directories',
1069 'are not compatible with selected cuda and cudnn installations')
1070 print(trt_install_path)
1071 print(os.path.join(trt_install_path, 'lib'))
1072 print(os.path.join(trt_install_path, 'lib64'))
1073 if search_result:
1074 print(libnvinfer_path_from_ldconfig)
1075 else:
1076 print(
1077 'Invalid path to TensorRT. None of the following files can be found:')
1078 print(trt_install_path)
1079 print(os.path.join(trt_install_path, 'lib'))
1080 print(os.path.join(trt_install_path, 'lib64'))
1081 if search_result:
1082 print(libnvinfer_path_from_ldconfig)
Guangda Lai76f69382018-01-25 23:59:19 -08001083
1084 else:
1085 raise UserInputError('Invalid TF_TENSORRT setting was provided %d '
1086 'times in a row. Assuming to be a scripting mistake.' %
1087 _DEFAULT_PROMPT_ASK_ATTEMPTS)
1088
1089 # Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION
1090 environ_cp['TENSORRT_INSTALL_PATH'] = trt_install_path
1091 write_action_env_to_bazelrc('TENSORRT_INSTALL_PATH', trt_install_path)
1092 environ_cp['TF_TENSORRT_VERSION'] = tf_tensorrt_version
1093 write_action_env_to_bazelrc('TF_TENSORRT_VERSION', tf_tensorrt_version)
1094
1095
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001096def set_tf_nccl_install_path(environ_cp):
1097 """Set NCCL_INSTALL_PATH and TF_NCCL_VERSION.
1098
1099 Args:
1100 environ_cp: copy of the os.environ.
1101
1102 Raises:
1103 ValueError: if this method was called under non-Linux platform.
1104 UserInputError: if user has provided invalid input multiple times.
1105 """
1106 if not is_linux():
1107 raise ValueError('Currently NCCL is only supported on Linux platforms.')
1108
1109 ask_nccl_version = (
Smit Hinsu63e6b9b2018-07-13 12:46:24 -07001110 'Please specify the NCCL version you want to use. If NCCL %s is not '
1111 'installed, then you can use version 1.3 that can be fetched '
1112 'automatically but it may have worse performance with multiple GPUs. '
1113 '[Default is %s]: ') % (_DEFAULT_NCCL_VERSION, _DEFAULT_NCCL_VERSION)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001114
1115 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
1116 tf_nccl_version = get_from_env_or_user_or_default(
1117 environ_cp, 'TF_NCCL_VERSION', ask_nccl_version, _DEFAULT_NCCL_VERSION)
1118 tf_nccl_version = reformat_version_sequence(str(tf_nccl_version), 1)
1119
1120 if tf_nccl_version == '1':
1121 break # No need to get install path, NCCL 1 is a GitHub repo.
1122
1123 # TODO(csigg): Look with ldconfig first if we can find the library in paths
1124 # like /usr/lib/x86_64-linux-gnu and the header file in the corresponding
1125 # include directory. This is where the NCCL .deb packages install them.
1126 # Then ask the user if we should use that. Instead of a single
1127 # NCCL_INSTALL_PATH, pass separate NCCL_LIB_PATH and NCCL_HDR_PATH to
1128 # nccl_configure.bzl
1129 default_nccl_path = environ_cp.get('CUDA_TOOLKIT_PATH')
1130 ask_nccl_path = (r'Please specify the location where NCCL %s library is '
1131 'installed. Refer to README.md for more details. [Default '
1132 'is %s]:') % (tf_nccl_version, default_nccl_path)
1133 nccl_install_path = get_from_env_or_user_or_default(
1134 environ_cp, 'NCCL_INSTALL_PATH', ask_nccl_path, default_nccl_path)
1135
1136 # Result returned from "read" will be used unexpanded. That make "~"
1137 # unusable. Going through one more level of expansion to handle that.
1138 nccl_install_path = os.path.realpath(os.path.expanduser(nccl_install_path))
1139 if is_windows() or is_cygwin():
1140 nccl_install_path = cygpath(nccl_install_path)
1141
1142 if is_windows():
1143 nccl_lib_path = 'lib/x64/nccl.lib'
1144 elif is_linux():
1145 nccl_lib_path = 'lib/libnccl.so.%s' % tf_nccl_version
1146 elif is_macos():
1147 nccl_lib_path = 'lib/libnccl.%s.dylib' % tf_nccl_version
1148
1149 nccl_lib_path = os.path.join(nccl_install_path, nccl_lib_path)
1150 nccl_hdr_path = os.path.join(nccl_install_path, 'include/nccl.h')
1151 if os.path.exists(nccl_lib_path) and os.path.exists(nccl_hdr_path):
1152 # Set NCCL_INSTALL_PATH
1153 environ_cp['NCCL_INSTALL_PATH'] = nccl_install_path
1154 write_action_env_to_bazelrc('NCCL_INSTALL_PATH', nccl_install_path)
1155 break
1156
1157 # Reset and Retry
1158 print('Invalid path to NCCL %s toolkit, %s or %s not found. Please use the '
1159 'O/S agnostic package of NCCL 2' % (tf_nccl_version, nccl_lib_path,
1160 nccl_hdr_path))
1161
1162 environ_cp['TF_NCCL_VERSION'] = ''
1163 else:
1164 raise UserInputError('Invalid TF_NCCL setting was provided %d '
1165 'times in a row. Assuming to be a scripting mistake.' %
1166 _DEFAULT_PROMPT_ASK_ATTEMPTS)
1167
1168 # Set TF_NCCL_VERSION
1169 environ_cp['TF_NCCL_VERSION'] = tf_nccl_version
1170 write_action_env_to_bazelrc('TF_NCCL_VERSION', tf_nccl_version)
1171
1172
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001173def get_native_cuda_compute_capabilities(environ_cp):
1174 """Get native cuda compute capabilities.
1175
1176 Args:
1177 environ_cp: copy of the os.environ.
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001178
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001179 Returns:
1180 string of native cuda compute capabilities, separated by comma.
1181 """
1182 device_query_bin = os.path.join(
1183 environ_cp.get('CUDA_TOOLKIT_PATH'), 'extras/demo_suite/deviceQuery')
Jonathan Hseu008910f2017-08-25 14:01:05 -07001184 if os.path.isfile(device_query_bin) and os.access(device_query_bin, os.X_OK):
1185 try:
1186 output = run_shell(device_query_bin).split('\n')
1187 pattern = re.compile('[0-9]*\\.[0-9]*')
1188 output = [pattern.search(x) for x in output if 'Capability' in x]
1189 output = ','.join(x.group() for x in output if x is not None)
1190 except subprocess.CalledProcessError:
1191 output = ''
1192 else:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001193 output = ''
1194 return output
1195
1196
1197def set_tf_cuda_compute_capabilities(environ_cp):
1198 """Set TF_CUDA_COMPUTE_CAPABILITIES."""
1199 while True:
1200 native_cuda_compute_capabilities = get_native_cuda_compute_capabilities(
1201 environ_cp)
1202 if not native_cuda_compute_capabilities:
1203 default_cuda_compute_capabilities = _DEFAULT_CUDA_COMPUTE_CAPABILITIES
1204 else:
1205 default_cuda_compute_capabilities = native_cuda_compute_capabilities
1206
1207 ask_cuda_compute_capabilities = (
1208 'Please specify a list of comma-separated '
1209 'Cuda compute capabilities you want to '
1210 'build with.\nYou can find the compute '
1211 'capability of your device at: '
1212 'https://developer.nvidia.com/cuda-gpus.\nPlease'
1213 ' note that each additional compute '
1214 'capability significantly increases your '
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001215 'build time and binary size. [Default is: %s]: ' %
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001216 default_cuda_compute_capabilities)
1217 tf_cuda_compute_capabilities = get_from_env_or_user_or_default(
1218 environ_cp, 'TF_CUDA_COMPUTE_CAPABILITIES',
1219 ask_cuda_compute_capabilities, default_cuda_compute_capabilities)
1220 # Check whether all capabilities from the input is valid
1221 all_valid = True
Maciejd0f5bc12018-04-30 22:30:58 -05001222 # Remove all whitespace characters before splitting the string
Michael Case51053502018-06-05 17:47:19 -07001223 # that users may insert by accident, as this will result in error
Maciejd0f5bc12018-04-30 22:30:58 -05001224 tf_cuda_compute_capabilities = ''.join(tf_cuda_compute_capabilities.split())
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001225 for compute_capability in tf_cuda_compute_capabilities.split(','):
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001226 m = re.match('[0-9]+.[0-9]+', compute_capability)
1227 if not m:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001228 print('Invalid compute capability: ' % compute_capability)
1229 all_valid = False
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001230 else:
1231 ver = int(m.group(0).split('.')[0])
1232 if ver < 3:
1233 print('Only compute capabilities 3.0 or higher are supported.')
1234 all_valid = False
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001235
1236 if all_valid:
1237 break
1238
1239 # Reset and Retry
1240 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = ''
1241
1242 # Set TF_CUDA_COMPUTE_CAPABILITIES
1243 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = tf_cuda_compute_capabilities
1244 write_action_env_to_bazelrc('TF_CUDA_COMPUTE_CAPABILITIES',
1245 tf_cuda_compute_capabilities)
1246
1247
1248def set_other_cuda_vars(environ_cp):
1249 """Set other CUDA related variables."""
A. Unique TensorFlowerab391982018-07-11 04:52:49 -07001250 # If CUDA is enabled, always use GPU during build and test.
1251 if environ_cp.get('TF_CUDA_CLANG') == '1':
1252 write_to_bazelrc('build --config=cuda_clang')
1253 write_to_bazelrc('test --config=cuda_clang')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001254 else:
A. Unique TensorFlowerab391982018-07-11 04:52:49 -07001255 write_to_bazelrc('build --config=cuda')
1256 write_to_bazelrc('test --config=cuda')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001257
1258
1259def set_host_cxx_compiler(environ_cp):
1260 """Set HOST_CXX_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001261 default_cxx_host_compiler = which('g++') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001262
Austin Anderson6afface2017-12-05 11:59:17 -08001263 host_cxx_compiler = prompt_loop_or_load_from_env(
1264 environ_cp,
1265 var_name='HOST_CXX_COMPILER',
1266 var_default=default_cxx_host_compiler,
1267 ask_for_var=('Please specify which C++ compiler should be used as the '
1268 'host C++ compiler.'),
1269 check_success=os.path.exists,
1270 error_msg='Invalid C++ compiler path. %s cannot be found.',
1271 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001272
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001273 write_action_env_to_bazelrc('HOST_CXX_COMPILER', host_cxx_compiler)
1274
1275
1276def set_host_c_compiler(environ_cp):
1277 """Set HOST_C_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001278 default_c_host_compiler = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001279
Austin Anderson6afface2017-12-05 11:59:17 -08001280 host_c_compiler = prompt_loop_or_load_from_env(
1281 environ_cp,
1282 var_name='HOST_C_COMPILER',
1283 var_default=default_c_host_compiler,
Shanqing Cai71445712018-03-12 19:33:52 -07001284 ask_for_var=('Please specify which C compiler should be used as the host '
Austin Anderson6afface2017-12-05 11:59:17 -08001285 'C compiler.'),
1286 check_success=os.path.exists,
1287 error_msg='Invalid C compiler path. %s cannot be found.',
1288 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001289
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001290 write_action_env_to_bazelrc('HOST_C_COMPILER', host_c_compiler)
1291
1292
1293def set_computecpp_toolkit_path(environ_cp):
1294 """Set COMPUTECPP_TOOLKIT_PATH."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001295
Austin Anderson6afface2017-12-05 11:59:17 -08001296 def toolkit_exists(toolkit_path):
1297 """Check if a computecpp toolkit path is valid."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001298 if is_linux():
1299 sycl_rt_lib_path = 'lib/libComputeCpp.so'
1300 else:
1301 sycl_rt_lib_path = ''
1302
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001303 sycl_rt_lib_path_full = os.path.join(toolkit_path, sycl_rt_lib_path)
Austin Anderson6afface2017-12-05 11:59:17 -08001304 exists = os.path.exists(sycl_rt_lib_path_full)
1305 if not exists:
1306 print('Invalid SYCL %s library path. %s cannot be found' %
1307 (_TF_OPENCL_VERSION, sycl_rt_lib_path_full))
1308 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001309
Austin Anderson6afface2017-12-05 11:59:17 -08001310 computecpp_toolkit_path = prompt_loop_or_load_from_env(
1311 environ_cp,
1312 var_name='COMPUTECPP_TOOLKIT_PATH',
1313 var_default=_DEFAULT_COMPUTECPP_TOOLKIT_PATH,
1314 ask_for_var=(
1315 'Please specify the location where ComputeCpp for SYCL %s is '
1316 'installed.' % _TF_OPENCL_VERSION),
1317 check_success=toolkit_exists,
1318 error_msg='Invalid SYCL compiler path. %s cannot be found.',
1319 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001320
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001321 write_action_env_to_bazelrc('COMPUTECPP_TOOLKIT_PATH',
1322 computecpp_toolkit_path)
1323
Michael Cased31531a2018-01-05 14:09:41 -08001324
Dandelion Man?90e42f32017-12-15 18:15:07 -08001325def set_trisycl_include_dir(environ_cp):
Michael Cased31531a2018-01-05 14:09:41 -08001326 """Set TRISYCL_INCLUDE_DIR."""
Frank Chenc4ef9272018-01-10 11:36:52 -08001327
Dandelion Man?90e42f32017-12-15 18:15:07 -08001328 ask_trisycl_include_dir = ('Please specify the location of the triSYCL '
1329 'include directory. (Use --config=sycl_trisycl '
1330 'when building with Bazel) '
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001331 '[Default is %s]: ') % (
1332 _DEFAULT_TRISYCL_INCLUDE_DIR)
Frank Chenc4ef9272018-01-10 11:36:52 -08001333
Dandelion Man?90e42f32017-12-15 18:15:07 -08001334 while True:
1335 trisycl_include_dir = get_from_env_or_user_or_default(
Michael Cased31531a2018-01-05 14:09:41 -08001336 environ_cp, 'TRISYCL_INCLUDE_DIR', ask_trisycl_include_dir,
1337 _DEFAULT_TRISYCL_INCLUDE_DIR)
Dandelion Man?90e42f32017-12-15 18:15:07 -08001338 if os.path.exists(trisycl_include_dir):
1339 break
1340
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001341 print('Invalid triSYCL include directory, %s cannot be found' %
1342 (trisycl_include_dir))
Dandelion Man?90e42f32017-12-15 18:15:07 -08001343
1344 # Set TRISYCL_INCLUDE_DIR
1345 environ_cp['TRISYCL_INCLUDE_DIR'] = trisycl_include_dir
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001346 write_action_env_to_bazelrc('TRISYCL_INCLUDE_DIR', trisycl_include_dir)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001347
Yifei Fengb1d8c592017-11-22 13:42:21 -08001348
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001349def set_mpi_home(environ_cp):
1350 """Set MPI_HOME."""
Austin Anderson6afface2017-12-05 11:59:17 -08001351
Jonathan Hseu008910f2017-08-25 14:01:05 -07001352 default_mpi_home = which('mpirun') or which('mpiexec') or ''
1353 default_mpi_home = os.path.dirname(os.path.dirname(default_mpi_home))
1354
Austin Anderson6afface2017-12-05 11:59:17 -08001355 def valid_mpi_path(mpi_home):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001356 exists = (
1357 os.path.exists(os.path.join(mpi_home, 'include')) and
1358 os.path.exists(os.path.join(mpi_home, 'lib')))
Austin Anderson6afface2017-12-05 11:59:17 -08001359 if not exists:
1360 print('Invalid path to the MPI Toolkit. %s or %s cannot be found' %
1361 (os.path.join(mpi_home, 'include'),
1362 os.path.exists(os.path.join(mpi_home, 'lib'))))
1363 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001364
Austin Anderson6afface2017-12-05 11:59:17 -08001365 _ = prompt_loop_or_load_from_env(
1366 environ_cp,
1367 var_name='MPI_HOME',
1368 var_default=default_mpi_home,
1369 ask_for_var='Please specify the MPI toolkit folder.',
1370 check_success=valid_mpi_path,
1371 error_msg='',
1372 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001373
1374
1375def set_other_mpi_vars(environ_cp):
1376 """Set other MPI related variables."""
1377 # Link the MPI header files
1378 mpi_home = environ_cp.get('MPI_HOME')
1379 symlink_force('%s/include/mpi.h' % mpi_home, 'third_party/mpi/mpi.h')
1380
1381 # Determine if we use OpenMPI or MVAPICH, these require different header files
1382 # to be included here to make bazel dependency checker happy
1383 if os.path.exists(os.path.join(mpi_home, 'include/mpi_portable_platform.h')):
1384 symlink_force(
1385 os.path.join(mpi_home, 'include/mpi_portable_platform.h'),
1386 'third_party/mpi/mpi_portable_platform.h')
1387 # TODO(gunan): avoid editing files in configure
1388 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=False',
1389 'MPI_LIB_IS_OPENMPI=True')
1390 else:
1391 # MVAPICH / MPICH
1392 symlink_force(
1393 os.path.join(mpi_home, 'include/mpio.h'), 'third_party/mpi/mpio.h')
1394 symlink_force(
1395 os.path.join(mpi_home, 'include/mpicxx.h'), 'third_party/mpi/mpicxx.h')
1396 # TODO(gunan): avoid editing files in configure
1397 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=True',
1398 'MPI_LIB_IS_OPENMPI=False')
1399
1400 if os.path.exists(os.path.join(mpi_home, 'lib/libmpi.so')):
1401 symlink_force(
1402 os.path.join(mpi_home, 'lib/libmpi.so'), 'third_party/mpi/libmpi.so')
1403 else:
1404 raise ValueError('Cannot find the MPI library file in %s/lib' % mpi_home)
1405
1406
Yifei Feng5198cb82018-08-17 13:53:06 -07001407def set_system_libs_flag(environ_cp):
1408 syslibs = environ_cp.get('TF_SYSTEM_LIBS', '')
Yifei Feng5198cb82018-08-17 13:53:06 -07001409 if syslibs and syslibs != '':
Jason Zaman5fc39bd2018-09-16 01:38:55 +08001410 if ',' in syslibs:
1411 syslibs = ','.join(sorted(syslibs.split(',')))
1412 else:
1413 syslibs = ','.join(sorted(syslibs.split()))
Yifei Feng5198cb82018-08-17 13:53:06 -07001414 write_action_env_to_bazelrc('TF_SYSTEM_LIBS', syslibs)
1415
Jason Zaman5fc39bd2018-09-16 01:38:55 +08001416 if 'PREFIX' in environ_cp:
1417 write_to_bazelrc('build --define=PREFIX=%s' % environ_cp['PREFIX'])
1418 if 'LIBDIR' in environ_cp:
1419 write_to_bazelrc('build --define=LIBDIR=%s' % environ_cp['LIBDIR'])
1420 if 'INCLUDEDIR' in environ_cp:
1421 write_to_bazelrc('build --define=INCLUDEDIR=%s' % environ_cp['INCLUDEDIR'])
1422
Yifei Feng5198cb82018-08-17 13:53:06 -07001423
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001424def set_windows_build_flags(environ_cp):
1425 """Set Windows specific build options."""
1426 # The non-monolithic build is not supported yet
1427 write_to_bazelrc('build --config monolithic')
1428 # Suppress warning messages
1429 write_to_bazelrc('build --copt=-w --host_copt=-w')
1430 # Output more verbose information when something goes wrong
1431 write_to_bazelrc('build --verbose_failures')
1432 # The host and target platforms are the same in Windows build. So we don't
1433 # have to distinct them. This avoids building the same targets twice.
1434 write_to_bazelrc('build --distinct_host_configuration=false')
1435 # Enable short object file path to avoid long path issue on Windows.
1436 # TODO(pcloudy): Remove this flag when upgrading Bazel to 0.16.0
1437 # Short object file path will be enabled by default.
1438 write_to_bazelrc('build --experimental_shortened_obj_file_path=true')
A. Unique TensorFlower77e26862018-09-27 06:19:58 -07001439 # When building zip file for some py_binary and py_test targets, don't
1440 # include its dependencies. This is for:
1441 # 1. Running python tests against the system installed TF pip package.
1442 # 2. Avoiding redundant files in
1443 # //tensorflow/tools/pip_package:simple_console_windows,
1444 # which is a py_binary used during creating TF pip package.
1445 # See https://github.com/tensorflow/tensorflow/issues/22390
1446 write_to_bazelrc('build --define=no_tensorflow_py_deps=true')
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001447
1448 if get_var(
1449 environ_cp, 'TF_OVERRIDE_EIGEN_STRONG_INLINE', 'Eigen strong inline',
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001450 True, ('Would you like to override eigen strong inline for some C++ '
1451 'compilation to reduce the compilation time?'),
1452 'Eigen strong inline overridden.', 'Not overriding eigen strong inline, '
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001453 'some compilations could take more than 20 mins.'):
1454 # Due to a known MSVC compiler issue
1455 # https://github.com/tensorflow/tensorflow/issues/10521
1456 # Overriding eigen strong inline speeds up the compiling of
1457 # conv_grad_ops_3d.cc and conv_ops_3d.cc by 20 minutes,
1458 # but this also hurts the performance. Let users decide what they want.
1459 write_to_bazelrc('build --define=override_eigen_strong_inline=true')
Dandelion Man?90e42f32017-12-15 18:15:07 -08001460
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001461
Michael Cased31531a2018-01-05 14:09:41 -08001462def config_info_line(name, help_text):
1463 """Helper function to print formatted help text for Bazel config options."""
1464 print('\t--config=%-12s\t# %s' % (name, help_text))
1465
1466
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001467def main():
Shanqing Cai71445712018-03-12 19:33:52 -07001468 parser = argparse.ArgumentParser()
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001469 parser.add_argument(
1470 '--workspace',
1471 type=str,
1472 default=_TF_WORKSPACE_ROOT,
1473 help='The absolute path to your active Bazel workspace.')
Shanqing Cai71445712018-03-12 19:33:52 -07001474 args = parser.parse_args()
1475
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001476 # Make a copy of os.environ to be clear when functions and getting and setting
1477 # environment variables.
1478 environ_cp = dict(os.environ)
1479
Yifei Fengbb384112018-07-24 13:12:54 -07001480 check_bazel_version('0.15.0')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001481
Shanqing Cai71445712018-03-12 19:33:52 -07001482 reset_tf_configure_bazelrc(args.workspace)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001483 cleanup_makefile()
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -07001484 setup_python(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001485
1486 if is_windows():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001487 environ_cp['TF_NEED_JEMALLOC'] = '0'
Yifei Fengb1d8c592017-11-22 13:42:21 -08001488 environ_cp['TF_NEED_OPENCL_SYCL'] = '0'
1489 environ_cp['TF_NEED_COMPUTECPP'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001490 environ_cp['TF_NEED_OPENCL'] = '0'
1491 environ_cp['TF_CUDA_CLANG'] = '0'
Guangda Lai76f69382018-01-25 23:59:19 -08001492 environ_cp['TF_NEED_TENSORRT'] = '0'
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001493 # TODO(ibiryukov): Investigate using clang as a cpu or cuda compiler on
1494 # Windows.
1495 environ_cp['TF_DOWNLOAD_CLANG'] = '0'
A. Unique TensorFlower6e97fb32018-07-16 14:07:29 -07001496 environ_cp['TF_ENABLE_XLA'] = '0'
A. Unique TensorFlower6e97fb32018-07-16 14:07:29 -07001497 environ_cp['TF_NEED_MPI'] = '0'
1498 environ_cp['TF_SET_ANDROID_WORKSPACE'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001499
1500 if is_macos():
1501 environ_cp['TF_NEED_JEMALLOC'] = '0'
Guangda Lai76f69382018-01-25 23:59:19 -08001502 environ_cp['TF_NEED_TENSORRT'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001503
Jon Triebenbach6896a742018-06-27 13:29:53 -05001504 # The numpy package on ppc64le uses OpenBLAS which has multi-threading
1505 # issues that lead to incorrect answers. Set OMP_NUM_THREADS=1 at
1506 # runtime to allow the Tensorflow testcases which compare numpy
1507 # results to Tensorflow results to succeed.
1508 if is_ppc64le():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001509 write_action_env_to_bazelrc('OMP_NUM_THREADS', 1)
Jon Triebenbach6896a742018-06-27 13:29:53 -05001510
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001511 set_build_var(environ_cp, 'TF_NEED_JEMALLOC', 'jemalloc as malloc',
1512 'with_jemalloc', True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001513 set_build_var(environ_cp, 'TF_ENABLE_XLA', 'XLA JIT', 'with_xla_support',
Michael Case98850a52017-09-14 13:35:57 -07001514 False, 'xla')
Gunhan Gulsoy3da0dff2018-09-26 11:55:50 -07001515
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001516
Yifei Fengb1d8c592017-11-22 13:42:21 -08001517 set_action_env_var(environ_cp, 'TF_NEED_OPENCL_SYCL', 'OpenCL SYCL', False)
1518 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001519 set_host_cxx_compiler(environ_cp)
1520 set_host_c_compiler(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001521 set_action_env_var(environ_cp, 'TF_NEED_COMPUTECPP', 'ComputeCPP', True)
1522 if environ_cp.get('TF_NEED_COMPUTECPP') == '1':
1523 set_computecpp_toolkit_path(environ_cp)
1524 else:
1525 set_trisycl_include_dir(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001526
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001527 set_action_env_var(environ_cp, 'TF_NEED_ROCM', 'ROCm', False)
1528 if (environ_cp.get('TF_NEED_ROCM') == '1' and
TensorFlower Gardener62e60162018-09-27 10:22:55 -07001529 'LD_LIBRARY_PATH' in environ_cp and
1530 environ_cp.get('LD_LIBRARY_PATH') != '1'):
1531 write_action_env_to_bazelrc('LD_LIBRARY_PATH',
1532 environ_cp.get('LD_LIBRARY_PATH'))
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001533
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001534 set_action_env_var(environ_cp, 'TF_NEED_CUDA', 'CUDA', False)
A. Unique TensorFlower24cbb2a2017-09-08 07:45:44 -07001535 if (environ_cp.get('TF_NEED_CUDA') == '1' and
1536 'TF_CUDA_CONFIG_REPO' not in environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001537 set_tf_cuda_version(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001538 set_tf_cudnn_version(environ_cp)
Guangda Lai76f69382018-01-25 23:59:19 -08001539 if is_linux():
1540 set_tf_tensorrt_install_path(environ_cp)
Michael Case0073d132018-04-11 09:34:44 -07001541 set_tf_nccl_install_path(environ_cp)
1542
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001543 set_tf_cuda_compute_capabilities(environ_cp)
Ankur Taly0e6f39d2018-02-16 18:22:55 -08001544 if 'LD_LIBRARY_PATH' in environ_cp and environ_cp.get(
1545 'LD_LIBRARY_PATH') != '1':
1546 write_action_env_to_bazelrc('LD_LIBRARY_PATH',
1547 environ_cp.get('LD_LIBRARY_PATH'))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001548
1549 set_tf_cuda_clang(environ_cp)
1550 if environ_cp.get('TF_CUDA_CLANG') == '1':
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001551 # Ask whether we should download the clang toolchain.
1552 set_tf_download_clang(environ_cp)
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -08001553 if environ_cp.get('TF_DOWNLOAD_CLANG') != '1':
1554 # Set up which clang we should use as the cuda / host compiler.
1555 set_clang_cuda_compiler_path(environ_cp)
Ilya Biryukov1c3d02e2018-09-04 03:09:52 -07001556 else:
1557 # Use downloaded LLD for linking.
1558 write_to_bazelrc('build:cuda_clang --config=download_clang_use_lld')
1559 write_to_bazelrc('test:cuda_clang --config=download_clang_use_lld')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001560 else:
1561 # Set up which gcc nvcc should use as the host compiler
1562 # No need to set this on Windows
1563 if not is_windows():
1564 set_gcc_host_compiler_path(environ_cp)
1565 set_other_cuda_vars(environ_cp)
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001566 else:
1567 # CUDA not required. Ask whether we should download the clang toolchain and
1568 # use it for the CPU build.
1569 set_tf_download_clang(environ_cp)
1570 if environ_cp.get('TF_DOWNLOAD_CLANG') == '1':
1571 write_to_bazelrc('build --config=download_clang')
1572 write_to_bazelrc('test --config=download_clang')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001573
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001574 # SYCL / ROCm / CUDA are mutually exclusive.
1575 # At most 1 GPU platform can be configured.
1576 gpu_platform_count = 0
1577 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
1578 gpu_platform_count += 1
1579 if environ_cp.get('TF_NEED_ROCM') == '1':
1580 gpu_platform_count += 1
1581 if environ_cp.get('TF_NEED_CUDA') == '1':
1582 gpu_platform_count += 1
1583 if gpu_platform_count >= 2:
1584 raise UserInputError('SYCL / CUDA / ROCm are mututally exclusive. '
1585 'At most 1 GPU platform can be configured.')
1586
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001587 set_build_var(environ_cp, 'TF_NEED_MPI', 'MPI', 'with_mpi_support', False)
1588 if environ_cp.get('TF_NEED_MPI') == '1':
1589 set_mpi_home(environ_cp)
1590 set_other_mpi_vars(environ_cp)
1591
1592 set_cc_opt_flags(environ_cp)
Yifei Feng5198cb82018-08-17 13:53:06 -07001593 set_system_libs_flag(environ_cp)
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001594 if is_windows():
1595 set_windows_build_flags(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001596
Anna Ra9a1d5a2018-09-14 12:44:31 -07001597 # Add a config option to build TensorFlow 2.0 API.
1598 write_to_bazelrc('build:v2 --define=tf_api_version=2')
1599
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001600 if get_var(environ_cp, 'TF_SET_ANDROID_WORKSPACE', 'android workspace', False,
1601 ('Would you like to interactively configure ./WORKSPACE for '
1602 'Android builds?'), 'Searching for NDK and SDK installations.',
1603 'Not configuring the WORKSPACE for Android builds.'):
Michael Case51053502018-06-05 17:47:19 -07001604 create_android_ndk_rule(environ_cp)
1605 create_android_sdk_rule(environ_cp)
Austin Anderson6afface2017-12-05 11:59:17 -08001606
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001607 # On Windows, we don't have MKL support and the build is always monolithic.
1608 # So no need to print the following message.
1609 # TODO(pcloudy): remove the following if check when they make sense on Windows
1610 if not is_windows():
1611 print('Preconfigured Bazel build configs. You can use any of the below by '
1612 'adding "--config=<>" to your build command. See tools/bazel.rc for '
1613 'more details.')
1614 config_info_line('mkl', 'Build with MKL support.')
1615 config_info_line('monolithic', 'Config for mostly static monolithic build.')
Gunhan Gulsoy3da0dff2018-09-26 11:55:50 -07001616 config_info_line('gdr', 'Build with GDR support.')
1617 config_info_line('verbs', 'Build with libverbs support.')
avijit-nervanaf172c522018-09-27 12:57:24 -07001618 config_info_line('ngraph', 'Build with Intel nGraph support.')
Austin Anderson6afface2017-12-05 11:59:17 -08001619
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001620
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001621if __name__ == '__main__':
1622 main()
Gunhan Gulsoy3da0dff2018-09-26 11:55:50 -07001623