blob: e4495fb684eb5e4a9a2802c1515acbe45d6161a5 [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:
Avijitf88a6f92018-07-24 23:58:58 -070031 from shutil import which
Jonathan Hseu008910f2017-08-25 14:01:05 -070032except ImportError:
Avijitf88a6f92018-07-24 23:58:58 -070033 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'
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -070038_DEFAULT_NCCL_VERSION = '1.3'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070039_DEFAULT_CUDA_COMPUTE_CAPABILITIES = '3.5,5.2'
40_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)
Benoit Steiner0dadbfe2018-03-22 18:54:27 -070044_DEFAULT_TENSORRT_PATH_LINUX = '/usr/lib/%s-linux-gnu' % platform.machine()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070045_TF_OPENCL_VERSION = '1.2'
46_DEFAULT_COMPUTECPP_TOOLKIT_PATH = '/usr/local/computecpp'
Yifei Fengb1d8c592017-11-22 13:42:21 -080047_DEFAULT_TRISYCL_INCLUDE_DIR = '/usr/local/triSYCL/include'
Austin Anderson6afface2017-12-05 11:59:17 -080048_SUPPORTED_ANDROID_NDK_VERSIONS = [10, 11, 12, 13, 14, 15]
49
50_DEFAULT_PROMPT_ASK_ATTEMPTS = 10
51
Shanqing Cai71445712018-03-12 19:33:52 -070052_TF_WORKSPACE_ROOT = os.path.abspath(os.path.dirname(__file__))
53_TF_BAZELRC_FILENAME = '.tf_configure.bazelrc'
54_TF_BAZELRC = os.path.join(_TF_WORKSPACE_ROOT, _TF_BAZELRC_FILENAME)
55_TF_WORKSPACE = os.path.join(_TF_WORKSPACE_ROOT, 'WORKSPACE')
56
Austin Anderson6afface2017-12-05 11:59:17 -080057
58class UserInputError(Exception):
Avijitf88a6f92018-07-24 23:58:58 -070059 pass
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070060
61
62def is_windows():
Avijitf88a6f92018-07-24 23:58:58 -070063 return platform.system() == 'Windows'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070064
65
66def is_linux():
Avijitf88a6f92018-07-24 23:58:58 -070067 return platform.system() == 'Linux'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070068
69
70def is_macos():
Avijitf88a6f92018-07-24 23:58:58 -070071 return platform.system() == 'Darwin'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070072
73
74def is_ppc64le():
Avijitf88a6f92018-07-24 23:58:58 -070075 return platform.machine() == 'ppc64le'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070076
77
Jonathan Hseu008910f2017-08-25 14:01:05 -070078def is_cygwin():
Avijitf88a6f92018-07-24 23:58:58 -070079 return platform.system().startswith('CYGWIN_NT')
Jonathan Hseu008910f2017-08-25 14:01:05 -070080
81
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070082def get_input(question):
Avijitf88a6f92018-07-24 23:58:58 -070083 try:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070084 try:
Avijitf88a6f92018-07-24 23:58:58 -070085 answer = raw_input(question)
86 except NameError:
87 answer = input(question) # pylint: disable=bad-builtin
88 except EOFError:
89 answer = ''
90 return answer
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070091
92
93def symlink_force(target, link_name):
Avijitf88a6f92018-07-24 23:58:58 -070094 """Force symlink, equivalent of 'ln -sf'.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070095
Avijitf88a6f92018-07-24 23:58:58 -070096Args:
97 target: items to link to.
98 link_name: name of the link.
99"""
100 try:
101 os.symlink(target, link_name)
102 except OSError as e:
103 if e.errno == errno.EEXIST:
104 os.remove(link_name)
105 os.symlink(target, link_name)
106 else:
107 raise e
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700108
109
110def sed_in_place(filename, old, new):
Avijitf88a6f92018-07-24 23:58:58 -0700111 """Replace old string with new string in file.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700112
Avijitf88a6f92018-07-24 23:58:58 -0700113Args:
114 filename: string for filename.
115 old: string to replace.
116 new: new string to replace to.
117"""
118 with open(filename, 'r') as f:
119 filedata = f.read()
120 newdata = filedata.replace(old, new)
121 with open(filename, 'w') as f:
122 f.write(newdata)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700123
124
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700125def write_to_bazelrc(line):
Avijitf88a6f92018-07-24 23:58:58 -0700126 with open(_TF_BAZELRC, 'a') as f:
127 f.write(line + '\n')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700128
129
130def write_action_env_to_bazelrc(var_name, var):
Avijitf88a6f92018-07-24 23:58:58 -0700131 write_to_bazelrc('build --action_env %s="%s"' % (var_name, str(var)))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700132
133
Jonathan Hseu008910f2017-08-25 14:01:05 -0700134def run_shell(cmd, allow_non_zero=False):
Avijitf88a6f92018-07-24 23:58:58 -0700135 if allow_non_zero:
136 try:
137 output = subprocess.check_output(cmd)
138 except subprocess.CalledProcessError as e:
139 output = e.output
140 else:
141 output = subprocess.check_output(cmd)
142 return output.decode('UTF-8').strip()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700143
144
145def cygpath(path):
Avijitf88a6f92018-07-24 23:58:58 -0700146 """Convert path from posix to windows."""
147 return os.path.abspath(path).replace('\\', '/')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700148
149
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700150def get_python_path(environ_cp, python_bin_path):
Avijitf88a6f92018-07-24 23:58:58 -0700151 """Get the python site package paths."""
152 python_paths = []
153 if environ_cp.get('PYTHONPATH'):
154 python_paths = environ_cp.get('PYTHONPATH').split(':')
155 try:
156 library_paths = run_shell([
157 python_bin_path, '-c',
158 'import site; print("\\n".join(site.getsitepackages()))'
159 ]).split('\n')
160 except subprocess.CalledProcessError:
161 library_paths = [
162 run_shell([
Avijit121e0162018-07-24 23:35:27 -0700163 python_bin_path, '-c',
Avijitf88a6f92018-07-24 23:58:58 -0700164 'from distutils.sysconfig import get_python_lib;'
165 'print(get_python_lib())'
166 ])
167 ]
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700168
Avijitf88a6f92018-07-24 23:58:58 -0700169 all_paths = set(python_paths + library_paths)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700170
Avijitf88a6f92018-07-24 23:58:58 -0700171 paths = []
172 for path in all_paths:
173 if os.path.isdir(path):
174 paths.append(path)
175 return paths
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700176
177
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700178def get_python_major_version(python_bin_path):
Avijitf88a6f92018-07-24 23:58:58 -0700179 """Get the python major version."""
180 return run_shell(
181 [python_bin_path, '-c', 'import sys; print(sys.version[0])'])
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700182
183
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700184def setup_python(environ_cp):
Avijitf88a6f92018-07-24 23:58:58 -0700185 """Setup python related env variables."""
186 # Get PYTHON_BIN_PATH, default is the current running python.
187 default_python_bin_path = sys.executable
188 ask_python_bin_path = (
189 'Please specify the location of python. [Default is '
190 '%s]: ') % default_python_bin_path
191 while True:
192 python_bin_path = get_from_env_or_user_or_default(
193 environ_cp, 'PYTHON_BIN_PATH', ask_python_bin_path,
194 default_python_bin_path)
195 # Check if the path is valid
196 if os.path.isfile(python_bin_path) and os.access(
197 python_bin_path, os.X_OK):
198 break
199 elif not os.path.exists(python_bin_path):
200 print('Invalid python path: %s cannot be found.' % python_bin_path)
201 else:
202 print('%s is not executable. Is it the python binary?' %
203 python_bin_path)
204 environ_cp['PYTHON_BIN_PATH'] = ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700205
Avijitf88a6f92018-07-24 23:58:58 -0700206 # Convert python path to Windows style before checking lib and version
207 if is_windows() or is_cygwin():
208 python_bin_path = cygpath(python_bin_path)
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700209
Avijitf88a6f92018-07-24 23:58:58 -0700210 # Get PYTHON_LIB_PATH
211 python_lib_path = environ_cp.get('PYTHON_LIB_PATH')
212 if not python_lib_path:
213 python_lib_paths = get_python_path(environ_cp, python_bin_path)
214 if environ_cp.get('USE_DEFAULT_PYTHON_LIB_PATH') == '1':
215 python_lib_path = python_lib_paths[0]
216 else:
217 print('Found possible Python library paths:\n %s' %
218 '\n '.join(python_lib_paths))
219 default_python_lib_path = python_lib_paths[0]
220 python_lib_path = get_input(
221 'Please input the desired Python library path to use. '
222 'Default is [%s]\n' % python_lib_paths[0])
223 if not python_lib_path:
224 python_lib_path = default_python_lib_path
225 environ_cp['PYTHON_LIB_PATH'] = python_lib_path
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700226
Avijitf88a6f92018-07-24 23:58:58 -0700227 python_major_version = get_python_major_version(python_bin_path)
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700228
Avijitf88a6f92018-07-24 23:58:58 -0700229 # Convert python path to Windows style before writing into bazel.rc
230 if is_windows() or is_cygwin():
231 python_lib_path = cygpath(python_lib_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700232
Avijitf88a6f92018-07-24 23:58:58 -0700233 # 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)
236 write_to_bazelrc('build --python_path=\"%s"' % python_bin_path)
237 environ_cp['PYTHON_BIN_PATH'] = python_bin_path
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700238
Avijitf88a6f92018-07-24 23:58:58 -0700239 # Write tools/python_bin_path.sh
240 with open(
241 os.path.join(_TF_WORKSPACE_ROOT, 'tools', 'python_bin_path.sh'),
242 'w') as f:
243 f.write('export PYTHON_BIN_PATH="%s"' % python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700244
245
Shanqing Cai71445712018-03-12 19:33:52 -0700246def reset_tf_configure_bazelrc(workspace_path):
Avijitf88a6f92018-07-24 23:58:58 -0700247 """Reset file that contains customized config settings."""
248 open(_TF_BAZELRC, 'w').close()
249 bazelrc_path = os.path.join(workspace_path, '.bazelrc')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700250
Avijitf88a6f92018-07-24 23:58:58 -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)
260 if is_windows():
261 tf_bazelrc_path = _TF_BAZELRC.replace("\\", "/")
262 else:
263 tf_bazelrc_path = _TF_BAZELRC
264 f.write('import %s\n' % tf_bazelrc_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700265
266
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700267def cleanup_makefile():
Avijitf88a6f92018-07-24 23:58:58 -0700268 """Delete any leftover BUILD files from the Makefile build.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700269
Avijitf88a6f92018-07-24 23:58:58 -0700270These files could interfere with Bazel parsing.
271"""
272 makefile_download_dir = os.path.join(_TF_WORKSPACE_ROOT, 'tensorflow',
273 'contrib', 'makefile', 'downloads')
274 if os.path.isdir(makefile_download_dir):
275 for root, _, filenames in os.walk(makefile_download_dir):
276 for f in filenames:
277 if f.endswith('BUILD'):
278 os.remove(os.path.join(root, f))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700279
280
281def get_var(environ_cp,
282 var_name,
283 query_item,
284 enabled_by_default,
285 question=None,
286 yes_reply=None,
287 no_reply=None):
Avijitf88a6f92018-07-24 23:58:58 -0700288 """Get boolean input from user.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700289
Avijitf88a6f92018-07-24 23:58:58 -0700290If var_name is not set in env, ask user to enable query_item or not. If the
291response is empty, use the default.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700292
Avijitf88a6f92018-07-24 23:58:58 -0700293Args:
294 environ_cp: copy of the os.environ.
295 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
296 query_item: string for feature related to the variable, e.g. "Hadoop File
297 System".
298 enabled_by_default: boolean for default behavior.
299 question: optional string for how to ask for user input.
300 yes_reply: optional string for reply when feature is enabled.
301 no_reply: optional string for reply when feature is disabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700302
Avijitf88a6f92018-07-24 23:58:58 -0700303Returns:
304 boolean value of the variable.
Frank Chenc4ef9272018-01-10 11:36:52 -0800305
Avijitf88a6f92018-07-24 23:58:58 -0700306Raises:
307 UserInputError: if an environment variable is set, but it cannot be
308 interpreted as a boolean indicator, assume that the user has made a
309 scripting error, and will continue to provide invalid input.
310 Raise the error to avoid infinitely looping.
311"""
312 if not question:
313 question = 'Do you wish to build TensorFlow with %s support?' % query_item
314 if not yes_reply:
315 yes_reply = '%s support will be enabled for TensorFlow.' % query_item
316 if not no_reply:
317 no_reply = 'No %s' % yes_reply
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700318
Avijitf88a6f92018-07-24 23:58:58 -0700319 yes_reply += '\n'
320 no_reply += '\n'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700321
Avijitf88a6f92018-07-24 23:58:58 -0700322 if enabled_by_default:
323 question += ' [Y/n]: '
324 else:
325 question += ' [y/N]: '
326
327 var = environ_cp.get(var_name)
328 if var is not None:
329 var_content = var.strip().lower()
330 true_strings = ('1', 't', 'true', 'y', 'yes')
331 false_strings = ('0', 'f', 'false', 'n', 'no')
332 if var_content in true_strings:
333 var = True
334 elif var_content in false_strings:
335 var = False
Frank Chenc4ef9272018-01-10 11:36:52 -0800336 else:
Avijitf88a6f92018-07-24 23:58:58 -0700337 raise UserInputError(
338 'Environment variable %s must be set as a boolean indicator.\n'
339 'The following are accepted as TRUE : %s.\n'
340 'The following are accepted as FALSE: %s.\n'
341 'Current value is %s.' % (var_name, ', '.join(true_strings),
342 ', '.join(false_strings), var))
Frank Chenc4ef9272018-01-10 11:36:52 -0800343
Avijitf88a6f92018-07-24 23:58:58 -0700344 while var is None:
345 user_input_origin = get_input(question)
346 user_input = user_input_origin.strip().lower()
347 if user_input == 'y':
348 print(yes_reply)
349 var = True
350 elif user_input == 'n':
351 print(no_reply)
352 var = False
353 elif not user_input:
354 if enabled_by_default:
355 print(yes_reply)
356 var = True
357 else:
358 print(no_reply)
359 var = False
360 else:
361 print('Invalid selection: %s' % user_input_origin)
362 return var
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700363
364
Avijit121e0162018-07-24 23:35:27 -0700365def set_build_var(environ_cp,
366 var_name,
367 query_item,
368 option_name,
369 enabled_by_default,
370 bazel_config_name=None):
Avijitf88a6f92018-07-24 23:58:58 -0700371 """Set if query_item will be enabled for the build.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700372
Avijitf88a6f92018-07-24 23:58:58 -0700373Ask user if query_item will be enabled. Default is used if no input is given.
374Set subprocess environment variable and write to .bazelrc if enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700375
Avijitf88a6f92018-07-24 23:58:58 -0700376Args:
377 environ_cp: copy of the os.environ.
378 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
379 query_item: string for feature related to the variable, e.g. "Hadoop File
380 System".
381 option_name: string for option to define in .bazelrc.
382 enabled_by_default: boolean for default behavior.
383 bazel_config_name: Name for Bazel --config argument to enable build feature.
384"""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700385
Avijitf88a6f92018-07-24 23:58:58 -0700386 var = str(
387 int(get_var(environ_cp, var_name, query_item, enabled_by_default)))
388 environ_cp[var_name] = var
389 if var == '1':
390 write_to_bazelrc('build --define %s=true' % option_name)
391 elif bazel_config_name is not None:
392 # TODO(mikecase): Migrate all users of configure.py to use --config Bazel
393 # options and not to set build configs through environment variables.
394 write_to_bazelrc(
395 'build:%s --define %s=true' % (bazel_config_name, option_name))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700396
397
398def set_action_env_var(environ_cp,
399 var_name,
400 query_item,
401 enabled_by_default,
402 question=None,
403 yes_reply=None,
404 no_reply=None):
Avijitf88a6f92018-07-24 23:58:58 -0700405 """Set boolean action_env variable.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700406
Avijitf88a6f92018-07-24 23:58:58 -0700407Ask user if query_item will be enabled. Default is used if no input is given.
408Set environment variable and write to .bazelrc.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700409
Avijitf88a6f92018-07-24 23:58:58 -0700410Args:
411 environ_cp: copy of the os.environ.
412 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
413 query_item: string for feature related to the variable, e.g. "Hadoop File
414 System".
415 enabled_by_default: boolean for default behavior.
416 question: optional string for how to ask for user input.
417 yes_reply: optional string for reply when feature is enabled.
418 no_reply: optional string for reply when feature is disabled.
419"""
420 var = int(
421 get_var(environ_cp, var_name, query_item, enabled_by_default, question,
422 yes_reply, no_reply))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700423
Avijitf88a6f92018-07-24 23:58:58 -0700424 write_action_env_to_bazelrc(var_name, var)
425 environ_cp[var_name] = str(var)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700426
427
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700428def convert_version_to_int(version):
Avijitf88a6f92018-07-24 23:58:58 -0700429 """Convert a version number to a integer that can be used to compare.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700430
Avijitf88a6f92018-07-24 23:58:58 -0700431Version strings of the form X.YZ and X.Y.Z-xxxxx are supported. The
432'xxxxx' part, for instance 'homebrew' on OS/X, is ignored.
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700433
Avijitf88a6f92018-07-24 23:58:58 -0700434Args:
435 version: a version to be converted
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700436
Avijitf88a6f92018-07-24 23:58:58 -0700437Returns:
438 An integer if converted successfully, otherwise return None.
439"""
440 version = version.split('-')[0]
441 version_segments = version.split('.')
442 for seg in version_segments:
443 if not seg.isdigit():
444 return None
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700445
Avijitf88a6f92018-07-24 23:58:58 -0700446 version_str = ''.join(['%03d' % int(seg) for seg in version_segments])
447 return int(version_str)
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700448
449
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700450def check_bazel_version(min_version):
Avijitf88a6f92018-07-24 23:58:58 -0700451 """Check installed bazel version is at least min_version.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700452
Avijitf88a6f92018-07-24 23:58:58 -0700453Args:
454 min_version: string for minimum bazel version.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700455
Avijitf88a6f92018-07-24 23:58:58 -0700456Returns:
457 The bazel version detected.
458"""
459 if which('bazel') is None:
460 print('Cannot find bazel. Please install bazel.')
461 sys.exit(0)
462 curr_version = run_shell(
463 ['bazel', '--batch', '--bazelrc=/dev/null', 'version'])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700464
Avijitf88a6f92018-07-24 23:58:58 -0700465 for line in curr_version.split('\n'):
466 if 'Build label: ' in line:
467 curr_version = line.split('Build label: ')[1]
468 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700469
Avijitf88a6f92018-07-24 23:58:58 -0700470 min_version_int = convert_version_to_int(min_version)
471 curr_version_int = convert_version_to_int(curr_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700472
Avijitf88a6f92018-07-24 23:58:58 -0700473 # Check if current bazel version can be detected properly.
474 if not curr_version_int:
475 print('WARNING: current bazel installation is not a release version.')
476 print('Make sure you are running at least bazel %s' % min_version)
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700477 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700478
Avijitf88a6f92018-07-24 23:58:58 -0700479 print('You have bazel %s installed.' % curr_version)
480
481 if curr_version_int < min_version_int:
482 print(
483 'Please upgrade your bazel installation to version %s or higher to '
484 'build TensorFlow!' % min_version)
485 sys.exit(0)
486 return curr_version
487
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700488
489def set_cc_opt_flags(environ_cp):
Avijitf88a6f92018-07-24 23:58:58 -0700490 """Set up architecture-dependent optimization flags.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700491
Avijitf88a6f92018-07-24 23:58:58 -0700492Also append CC optimization flags to bazel.rc..
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700493
Avijitf88a6f92018-07-24 23:58:58 -0700494Args:
495 environ_cp: copy of the os.environ.
496"""
497 if is_ppc64le():
498 # gcc on ppc64le does not support -march, use mcpu instead
499 default_cc_opt_flags = '-mcpu=native'
500 elif is_windows():
501 default_cc_opt_flags = '/arch:AVX'
502 else:
503 default_cc_opt_flags = '-march=native'
504 question = (
505 'Please specify optimization flags to use during compilation when'
506 ' bazel option "--config=opt" is specified [Default is %s]: '
507 ) % default_cc_opt_flags
508 cc_opt_flags = get_from_env_or_user_or_default(
509 environ_cp, 'CC_OPT_FLAGS', question, default_cc_opt_flags)
510 for opt in cc_opt_flags.split():
511 write_to_bazelrc('build:opt --copt=%s' % opt)
512 # It should be safe on the same build host.
513 if not is_ppc64le() and not is_windows():
514 write_to_bazelrc('build:opt --host_copt=-march=native')
515 write_to_bazelrc('build:opt --define with_default_optimizations=true')
Avijit121e0162018-07-24 23:35:27 -0700516
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700517
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700518def set_tf_cuda_clang(environ_cp):
Avijitf88a6f92018-07-24 23:58:58 -0700519 """set TF_CUDA_CLANG action_env.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700520
Avijitf88a6f92018-07-24 23:58:58 -0700521Args:
522 environ_cp: copy of the os.environ.
523"""
524 question = 'Do you want to use clang as CUDA compiler?'
525 yes_reply = 'Clang will be used as CUDA compiler.'
526 no_reply = 'nvcc will be used as CUDA compiler.'
527 set_action_env_var(
528 environ_cp,
529 'TF_CUDA_CLANG',
530 None,
531 False,
532 question=question,
533 yes_reply=yes_reply,
534 no_reply=no_reply)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700535
536
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800537def set_tf_download_clang(environ_cp):
Avijitf88a6f92018-07-24 23:58:58 -0700538 """Set TF_DOWNLOAD_CLANG action_env."""
539 question = 'Do you wish to download a fresh release of clang? (Experimental)'
540 yes_reply = 'Clang will be downloaded and used to compile tensorflow.'
541 no_reply = 'Clang will not be downloaded.'
542 set_action_env_var(
543 environ_cp,
544 'TF_DOWNLOAD_CLANG',
545 None,
546 False,
547 question=question,
548 yes_reply=yes_reply,
549 no_reply=no_reply)
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800550
551
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700552def get_from_env_or_user_or_default(environ_cp, var_name, ask_for_var,
553 var_default):
Avijitf88a6f92018-07-24 23:58:58 -0700554 """Get var_name either from env, or user or default.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700555
Avijitf88a6f92018-07-24 23:58:58 -0700556If var_name has been set as environment variable, use the preset value, else
557ask for user input. If no input is provided, the default is used.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700558
Avijitf88a6f92018-07-24 23:58:58 -0700559Args:
560 environ_cp: copy of the os.environ.
561 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
562 ask_for_var: string for how to ask for user input.
563 var_default: default value string.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700564
Avijitf88a6f92018-07-24 23:58:58 -0700565Returns:
566 string value for var_name
567"""
568 var = environ_cp.get(var_name)
569 if not var:
570 var = get_input(ask_for_var)
571 print('\n')
572 if not var:
573 var = var_default
574 return var
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700575
576
577def set_clang_cuda_compiler_path(environ_cp):
Avijitf88a6f92018-07-24 23:58:58 -0700578 """Set CLANG_CUDA_COMPILER_PATH."""
579 default_clang_path = which('clang') or ''
580 ask_clang_path = (
581 'Please specify which clang should be used as device and '
582 'host compiler. [Default is %s]: ') % default_clang_path
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700583
Avijitf88a6f92018-07-24 23:58:58 -0700584 while True:
585 clang_cuda_compiler_path = get_from_env_or_user_or_default(
586 environ_cp, 'CLANG_CUDA_COMPILER_PATH', ask_clang_path,
587 default_clang_path)
588 if os.path.exists(clang_cuda_compiler_path):
589 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700590
Avijitf88a6f92018-07-24 23:58:58 -0700591 # Reset and retry
592 print('Invalid clang path: %s cannot be found.' %
593 clang_cuda_compiler_path)
594 environ_cp['CLANG_CUDA_COMPILER_PATH'] = ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700595
Avijitf88a6f92018-07-24 23:58:58 -0700596 # Set CLANG_CUDA_COMPILER_PATH
597 environ_cp['CLANG_CUDA_COMPILER_PATH'] = clang_cuda_compiler_path
598 write_action_env_to_bazelrc('CLANG_CUDA_COMPILER_PATH',
599 clang_cuda_compiler_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700600
601
Avijit121e0162018-07-24 23:35:27 -0700602def prompt_loop_or_load_from_env(environ_cp,
603 var_name,
604 var_default,
605 ask_for_var,
606 check_success,
607 error_msg,
608 suppress_default_error=False,
609 n_ask_attempts=_DEFAULT_PROMPT_ASK_ATTEMPTS):
Avijitf88a6f92018-07-24 23:58:58 -0700610 """Loop over user prompts for an ENV param until receiving a valid response.
Austin Anderson6afface2017-12-05 11:59:17 -0800611
Avijitf88a6f92018-07-24 23:58:58 -0700612For the env param var_name, read from the environment or verify user input
613until receiving valid input. When done, set var_name in the environ_cp to its
614new value.
Austin Anderson6afface2017-12-05 11:59:17 -0800615
Avijitf88a6f92018-07-24 23:58:58 -0700616Args:
617 environ_cp: (Dict) copy of the os.environ.
618 var_name: (String) string for name of environment variable, e.g. "TF_MYVAR".
619 var_default: (String) default value string.
620 ask_for_var: (String) string for how to ask for user input.
621 check_success: (Function) function that takes one argument and returns a
622 boolean. Should return True if the value provided is considered valid. May
623 contain a complex error message if error_msg does not provide enough
624 information. In that case, set suppress_default_error to True.
625 error_msg: (String) String with one and only one '%s'. Formatted with each
626 invalid response upon check_success(input) failure.
627 suppress_default_error: (Bool) Suppress the above error message in favor of
628 one from the check_success function.
629 n_ask_attempts: (Integer) Number of times to query for valid input before
630 raising an error and quitting.
Austin Anderson6afface2017-12-05 11:59:17 -0800631
Avijitf88a6f92018-07-24 23:58:58 -0700632Returns:
633 [String] The value of var_name after querying for input.
Austin Anderson6afface2017-12-05 11:59:17 -0800634
Avijitf88a6f92018-07-24 23:58:58 -0700635Raises:
636 UserInputError: if a query has been attempted n_ask_attempts times without
637 success, assume that the user has made a scripting error, and will
638 continue to provide invalid input. Raise the error to avoid infinitely
639 looping.
640"""
641 default = environ_cp.get(var_name) or var_default
642 full_query = '%s [Default is %s]: ' % (
643 ask_for_var,
644 default,
645 )
Austin Anderson6afface2017-12-05 11:59:17 -0800646
Avijitf88a6f92018-07-24 23:58:58 -0700647 for _ in range(n_ask_attempts):
648 val = get_from_env_or_user_or_default(environ_cp, var_name, full_query,
649 default)
650 if check_success(val):
651 break
652 if not suppress_default_error:
653 print(error_msg % val)
654 environ_cp[var_name] = ''
655 else:
656 raise UserInputError(
657 'Invalid %s setting was provided %d times in a row. '
658 'Assuming to be a scripting mistake.' % (var_name, n_ask_attempts))
Austin Anderson6afface2017-12-05 11:59:17 -0800659
Avijitf88a6f92018-07-24 23:58:58 -0700660 environ_cp[var_name] = val
661 return val
Austin Anderson6afface2017-12-05 11:59:17 -0800662
663
664def create_android_ndk_rule(environ_cp):
Avijitf88a6f92018-07-24 23:58:58 -0700665 """Set ANDROID_NDK_HOME and write Android NDK WORKSPACE rule."""
666 if is_windows() or is_cygwin():
667 default_ndk_path = cygpath(
668 '%s/Android/Sdk/ndk-bundle' % environ_cp['APPDATA'])
669 elif is_macos():
670 default_ndk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
671 else:
672 default_ndk_path = '%s/Android/Sdk/ndk-bundle' % environ_cp['HOME']
Austin Anderson6afface2017-12-05 11:59:17 -0800673
Avijitf88a6f92018-07-24 23:58:58 -0700674 def valid_ndk_path(path):
675 return (os.path.exists(path)
676 and os.path.exists(os.path.join(path, 'source.properties')))
Austin Anderson6afface2017-12-05 11:59:17 -0800677
Avijitf88a6f92018-07-24 23:58:58 -0700678 android_ndk_home_path = prompt_loop_or_load_from_env(
679 environ_cp,
680 var_name='ANDROID_NDK_HOME',
681 var_default=default_ndk_path,
682 ask_for_var='Please specify the home path of the Android NDK to use.',
683 check_success=valid_ndk_path,
684 error_msg=('The path %s or its child file "source.properties" '
685 'does not exist.'))
686 write_action_env_to_bazelrc('ANDROID_NDK_HOME', android_ndk_home_path)
687 write_action_env_to_bazelrc('ANDROID_NDK_API_LEVEL',
688 check_ndk_level(android_ndk_home_path))
Austin Anderson6afface2017-12-05 11:59:17 -0800689
690
691def create_android_sdk_rule(environ_cp):
Avijitf88a6f92018-07-24 23:58:58 -0700692 """Set Android variables and write Android SDK WORKSPACE rule."""
693 if is_windows() or is_cygwin():
694 default_sdk_path = cygpath('%s/Android/Sdk' % environ_cp['APPDATA'])
695 elif is_macos():
696 default_sdk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
697 else:
698 default_sdk_path = '%s/Android/Sdk' % environ_cp['HOME']
Austin Anderson6afface2017-12-05 11:59:17 -0800699
Avijitf88a6f92018-07-24 23:58:58 -0700700 def valid_sdk_path(path):
701 return (os.path.exists(path)
702 and os.path.exists(os.path.join(path, 'platforms'))
703 and os.path.exists(os.path.join(path, 'build-tools')))
Austin Anderson6afface2017-12-05 11:59:17 -0800704
Avijitf88a6f92018-07-24 23:58:58 -0700705 android_sdk_home_path = prompt_loop_or_load_from_env(
706 environ_cp,
707 var_name='ANDROID_SDK_HOME',
708 var_default=default_sdk_path,
709 ask_for_var='Please specify the home path of the Android SDK to use.',
710 check_success=valid_sdk_path,
711 error_msg=('Either %s does not exist, or it does not contain the '
712 'subdirectories "platforms" and "build-tools".'))
Austin Anderson6afface2017-12-05 11:59:17 -0800713
Avijitf88a6f92018-07-24 23:58:58 -0700714 platforms = os.path.join(android_sdk_home_path, 'platforms')
715 api_levels = sorted(os.listdir(platforms))
716 api_levels = [x.replace('android-', '') for x in api_levels]
Austin Anderson6afface2017-12-05 11:59:17 -0800717
Avijitf88a6f92018-07-24 23:58:58 -0700718 def valid_api_level(api_level):
719 return os.path.exists(
720 os.path.join(android_sdk_home_path, 'platforms',
721 'android-' + api_level))
Austin Anderson6afface2017-12-05 11:59:17 -0800722
Avijitf88a6f92018-07-24 23:58:58 -0700723 android_api_level = prompt_loop_or_load_from_env(
724 environ_cp,
725 var_name='ANDROID_API_LEVEL',
726 var_default=api_levels[-1],
727 ask_for_var=('Please specify the Android SDK API level to use. '
728 '[Available levels: %s]') % api_levels,
729 check_success=valid_api_level,
730 error_msg='Android-%s is not present in the SDK path.')
Austin Anderson6afface2017-12-05 11:59:17 -0800731
Avijitf88a6f92018-07-24 23:58:58 -0700732 build_tools = os.path.join(android_sdk_home_path, 'build-tools')
733 versions = sorted(os.listdir(build_tools))
Austin Anderson6afface2017-12-05 11:59:17 -0800734
Avijitf88a6f92018-07-24 23:58:58 -0700735 def valid_build_tools(version):
736 return os.path.exists(
737 os.path.join(android_sdk_home_path, 'build-tools', version))
Austin Anderson6afface2017-12-05 11:59:17 -0800738
Avijitf88a6f92018-07-24 23:58:58 -0700739 android_build_tools_version = prompt_loop_or_load_from_env(
740 environ_cp,
741 var_name='ANDROID_BUILD_TOOLS_VERSION',
742 var_default=versions[-1],
743 ask_for_var=('Please specify an Android build tools version to use. '
744 '[Available versions: %s]') % versions,
745 check_success=valid_build_tools,
746 error_msg=('The selected SDK does not have build-tools version %s '
747 'available.'))
Austin Anderson6afface2017-12-05 11:59:17 -0800748
Avijitf88a6f92018-07-24 23:58:58 -0700749 write_action_env_to_bazelrc('ANDROID_BUILD_TOOLS_VERSION',
750 android_build_tools_version)
751 write_action_env_to_bazelrc('ANDROID_SDK_API_LEVEL', android_api_level)
752 write_action_env_to_bazelrc('ANDROID_SDK_HOME', android_sdk_home_path)
Austin Anderson6afface2017-12-05 11:59:17 -0800753
754
755def check_ndk_level(android_ndk_home_path):
Avijitf88a6f92018-07-24 23:58:58 -0700756 """Check the revision number of an Android NDK path."""
757 properties_path = '%s/source.properties' % android_ndk_home_path
758 if is_windows() or is_cygwin():
759 properties_path = cygpath(properties_path)
760 with open(properties_path, 'r') as f:
761 filedata = f.read()
Austin Anderson6afface2017-12-05 11:59:17 -0800762
Avijitf88a6f92018-07-24 23:58:58 -0700763 revision = re.search(r'Pkg.Revision = (\d+)', filedata)
764 if revision:
765 ndk_api_level = revision.group(1)
766 else:
767 raise Exception('Unable to parse NDK revision.')
768 if int(ndk_api_level) not in _SUPPORTED_ANDROID_NDK_VERSIONS:
769 print(
770 'WARNING: The API level of the NDK in %s is %s, which is not '
771 'supported by Bazel (officially supported versions: %s). Please use '
772 'another version. Compiling Android targets may result in confusing '
773 'errors.\n' % (android_ndk_home_path, ndk_api_level,
774 _SUPPORTED_ANDROID_NDK_VERSIONS))
775 return ndk_api_level
Austin Anderson6afface2017-12-05 11:59:17 -0800776
777
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700778def set_gcc_host_compiler_path(environ_cp):
Avijitf88a6f92018-07-24 23:58:58 -0700779 """Set GCC_HOST_COMPILER_PATH."""
780 default_gcc_host_compiler_path = which('gcc') or ''
781 cuda_bin_symlink = '%s/bin/gcc' % environ_cp.get('CUDA_TOOLKIT_PATH')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700782
Avijitf88a6f92018-07-24 23:58:58 -0700783 if os.path.islink(cuda_bin_symlink):
784 # os.readlink is only available in linux
785 default_gcc_host_compiler_path = os.path.realpath(cuda_bin_symlink)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700786
Avijitf88a6f92018-07-24 23:58:58 -0700787 gcc_host_compiler_path = prompt_loop_or_load_from_env(
788 environ_cp,
789 var_name='GCC_HOST_COMPILER_PATH',
790 var_default=default_gcc_host_compiler_path,
791 ask_for_var='Please specify which gcc should be used by nvcc as the host compiler.',
792 check_success=os.path.exists,
793 error_msg='Invalid gcc path. %s cannot be found.',
794 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700795
Avijitf88a6f92018-07-24 23:58:58 -0700796 write_action_env_to_bazelrc('GCC_HOST_COMPILER_PATH',
797 gcc_host_compiler_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700798
799
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800800def reformat_version_sequence(version_str, sequence_count):
Avijitf88a6f92018-07-24 23:58:58 -0700801 """Reformat the version string to have the given number of sequences.
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800802
Avijitf88a6f92018-07-24 23:58:58 -0700803For example:
804Given (7, 2) -> 7.0
805 (7.0.1, 2) -> 7.0
806 (5, 1) -> 5
807 (5.0.3.2, 1) -> 5
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800808
Avijitf88a6f92018-07-24 23:58:58 -0700809Args:
810 version_str: String, the version string.
811 sequence_count: int, an integer.
812Returns:
813 string, reformatted version string.
814"""
815 v = version_str.split('.')
816 if len(v) < sequence_count:
817 v = v + (['0'] * (sequence_count - len(v)))
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800818
Avijitf88a6f92018-07-24 23:58:58 -0700819 return '.'.join(v[:sequence_count])
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800820
821
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700822def set_tf_cuda_version(environ_cp):
Avijitf88a6f92018-07-24 23:58:58 -0700823 """Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION."""
824 ask_cuda_version = (
825 'Please specify the CUDA SDK version you want to use. '
826 '[Leave empty to default to CUDA %s]: ') % _DEFAULT_CUDA_VERSION
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700827
Avijitf88a6f92018-07-24 23:58:58 -0700828 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
829 # Configure the Cuda SDK version to use.
830 tf_cuda_version = get_from_env_or_user_or_default(
831 environ_cp, 'TF_CUDA_VERSION', ask_cuda_version,
832 _DEFAULT_CUDA_VERSION)
833 tf_cuda_version = reformat_version_sequence(str(tf_cuda_version), 2)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700834
Avijitf88a6f92018-07-24 23:58:58 -0700835 # Find out where the CUDA toolkit is installed
836 default_cuda_path = _DEFAULT_CUDA_PATH
837 if is_windows() or is_cygwin():
838 default_cuda_path = cygpath(
839 environ_cp.get('CUDA_PATH', _DEFAULT_CUDA_PATH_WIN))
840 elif is_linux():
841 # If the default doesn't exist, try an alternative default.
842 if (not os.path.exists(default_cuda_path)
843 ) and os.path.exists(_DEFAULT_CUDA_PATH_LINUX):
844 default_cuda_path = _DEFAULT_CUDA_PATH_LINUX
845 ask_cuda_path = ('Please specify the location where CUDA %s toolkit is'
846 ' installed. Refer to README.md for more details. '
847 '[Default is %s]: ') % (tf_cuda_version,
848 default_cuda_path)
849 cuda_toolkit_path = get_from_env_or_user_or_default(
850 environ_cp, 'CUDA_TOOLKIT_PATH', ask_cuda_path, default_cuda_path)
851 if is_windows() or is_cygwin():
852 cuda_toolkit_path = cygpath(cuda_toolkit_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700853
Avijitf88a6f92018-07-24 23:58:58 -0700854 if is_windows():
855 cuda_rt_lib_path = 'lib/x64/cudart.lib'
856 elif is_linux():
857 cuda_rt_lib_path = 'lib64/libcudart.so.%s' % tf_cuda_version
858 elif is_macos():
859 cuda_rt_lib_path = 'lib/libcudart.%s.dylib' % tf_cuda_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700860
Avijitf88a6f92018-07-24 23:58:58 -0700861 cuda_toolkit_path_full = os.path.join(cuda_toolkit_path,
862 cuda_rt_lib_path)
863 if os.path.exists(cuda_toolkit_path_full):
864 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700865
Avijitf88a6f92018-07-24 23:58:58 -0700866 # Reset and retry
867 print('Invalid path to CUDA %s toolkit. %s cannot be found' %
868 (tf_cuda_version, cuda_toolkit_path_full))
869 environ_cp['TF_CUDA_VERSION'] = ''
870 environ_cp['CUDA_TOOLKIT_PATH'] = ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700871
Avijitf88a6f92018-07-24 23:58:58 -0700872 else:
873 raise UserInputError(
874 'Invalid TF_CUDA_SETTING setting was provided %d '
875 'times in a row. Assuming to be a scripting mistake.' %
876 _DEFAULT_PROMPT_ASK_ATTEMPTS)
Austin Andersonf9a88f82017-12-13 11:49:40 -0800877
Avijitf88a6f92018-07-24 23:58:58 -0700878 # Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION
879 environ_cp['CUDA_TOOLKIT_PATH'] = cuda_toolkit_path
880 write_action_env_to_bazelrc('CUDA_TOOLKIT_PATH', cuda_toolkit_path)
881 environ_cp['TF_CUDA_VERSION'] = tf_cuda_version
882 write_action_env_to_bazelrc('TF_CUDA_VERSION', tf_cuda_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700883
884
Yifei Fengb1d8c592017-11-22 13:42:21 -0800885def set_tf_cudnn_version(environ_cp):
Avijitf88a6f92018-07-24 23:58:58 -0700886 """Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION."""
887 ask_cudnn_version = (
888 'Please specify the cuDNN version you want to use. '
889 '[Leave empty to default to cuDNN %s.0]: ') % _DEFAULT_CUDNN_VERSION
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700890
Avijitf88a6f92018-07-24 23:58:58 -0700891 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
892 tf_cudnn_version = get_from_env_or_user_or_default(
893 environ_cp, 'TF_CUDNN_VERSION', ask_cudnn_version,
894 _DEFAULT_CUDNN_VERSION)
895 tf_cudnn_version = reformat_version_sequence(str(tf_cudnn_version), 1)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700896
Avijitf88a6f92018-07-24 23:58:58 -0700897 default_cudnn_path = environ_cp.get('CUDA_TOOLKIT_PATH')
898 ask_cudnn_path = (
899 r'Please specify the location where cuDNN %s library is '
900 'installed. Refer to README.md for more details. [Default'
901 ' is %s]:') % (tf_cudnn_version, default_cudnn_path)
902 cudnn_install_path = get_from_env_or_user_or_default(
903 environ_cp, 'CUDNN_INSTALL_PATH', ask_cudnn_path,
904 default_cudnn_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700905
Avijitf88a6f92018-07-24 23:58:58 -0700906 # Result returned from "read" will be used unexpanded. That make "~"
907 # unusable. Going through one more level of expansion to handle that.
908 cudnn_install_path = os.path.realpath(
909 os.path.expanduser(cudnn_install_path))
910 if is_windows() or is_cygwin():
911 cudnn_install_path = cygpath(cudnn_install_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700912
Avijitf88a6f92018-07-24 23:58:58 -0700913 if is_windows():
914 cuda_dnn_lib_path = 'lib/x64/cudnn.lib'
915 cuda_dnn_lib_alt_path = 'lib/x64/cudnn.lib'
916 elif is_linux():
917 cuda_dnn_lib_path = 'lib64/libcudnn.so.%s' % tf_cudnn_version
918 cuda_dnn_lib_alt_path = 'libcudnn.so.%s' % tf_cudnn_version
919 elif is_macos():
920 cuda_dnn_lib_path = 'lib/libcudnn.%s.dylib' % tf_cudnn_version
921 cuda_dnn_lib_alt_path = 'libcudnn.%s.dylib' % tf_cudnn_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700922
Avijitf88a6f92018-07-24 23:58:58 -0700923 cuda_dnn_lib_path_full = os.path.join(cudnn_install_path,
924 cuda_dnn_lib_path)
925 cuda_dnn_lib_alt_path_full = os.path.join(cudnn_install_path,
926 cuda_dnn_lib_alt_path)
927 if os.path.exists(cuda_dnn_lib_path_full) or os.path.exists(
928 cuda_dnn_lib_alt_path_full):
929 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700930
Avijitf88a6f92018-07-24 23:58:58 -0700931 # Try another alternative for Linux
932 if is_linux():
933 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
934 cudnn_path_from_ldconfig = run_shell([ldconfig_bin, '-p'])
935 cudnn_path_from_ldconfig = re.search('.*libcudnn.so .* => (.*)',
936 cudnn_path_from_ldconfig)
937 if cudnn_path_from_ldconfig:
938 cudnn_path_from_ldconfig = cudnn_path_from_ldconfig.group(1)
939 if os.path.exists('%s.%s' % (cudnn_path_from_ldconfig,
940 tf_cudnn_version)):
941 cudnn_install_path = os.path.dirname(
942 cudnn_path_from_ldconfig)
943 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700944
Avijitf88a6f92018-07-24 23:58:58 -0700945 # Reset and Retry
946 print(
947 'Invalid path to cuDNN %s toolkit. None of the following files can be '
948 'found:' % tf_cudnn_version)
949 print(cuda_dnn_lib_path_full)
950 print(cuda_dnn_lib_alt_path_full)
951 if is_linux():
952 print('%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700953
Avijitf88a6f92018-07-24 23:58:58 -0700954 environ_cp['TF_CUDNN_VERSION'] = ''
955 else:
956 raise UserInputError(
957 'Invalid TF_CUDNN setting was provided %d '
958 'times in a row. Assuming to be a scripting mistake.' %
959 _DEFAULT_PROMPT_ASK_ATTEMPTS)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700960
Avijitf88a6f92018-07-24 23:58:58 -0700961 # Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION
962 environ_cp['CUDNN_INSTALL_PATH'] = cudnn_install_path
963 write_action_env_to_bazelrc('CUDNN_INSTALL_PATH', cudnn_install_path)
964 environ_cp['TF_CUDNN_VERSION'] = tf_cudnn_version
965 write_action_env_to_bazelrc('TF_CUDNN_VERSION', tf_cudnn_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700966
967
Mingxing Tan1e7b0e42018-06-28 19:13:20 -0700968def is_cuda_compatible(lib, cuda_ver, cudnn_ver):
Avijitf88a6f92018-07-24 23:58:58 -0700969 """Check compatibility between given library and cudnn/cudart libraries."""
970 ldd_bin = which('ldd') or '/usr/bin/ldd'
971 ldd_out = run_shell([ldd_bin, lib], True)
972 ldd_out = ldd_out.split(os.linesep)
973 cudnn_pattern = re.compile('.*libcudnn.so\\.?(.*) =>.*$')
974 cuda_pattern = re.compile('.*libcudart.so\\.?(.*) =>.*$')
975 cudnn = None
976 cudart = None
977 cudnn_ok = True # assume no cudnn dependency by default
978 cuda_ok = True # assume no cuda dependency by default
979 for line in ldd_out:
980 if 'libcudnn.so' in line:
981 cudnn = cudnn_pattern.search(line)
982 cudnn_ok = False
983 elif 'libcudart.so' in line:
984 cudart = cuda_pattern.search(line)
985 cuda_ok = False
986 if cudnn and len(cudnn.group(1)):
987 cudnn = convert_version_to_int(cudnn.group(1))
988 if cudart and len(cudart.group(1)):
989 cudart = convert_version_to_int(cudart.group(1))
990 if cudnn is not None:
991 cudnn_ok = (cudnn == cudnn_ver)
992 if cudart is not None:
993 cuda_ok = (cudart == cuda_ver)
994 return cudnn_ok and cuda_ok
Mingxing Tan1e7b0e42018-06-28 19:13:20 -0700995
996
Guangda Lai76f69382018-01-25 23:59:19 -0800997def set_tf_tensorrt_install_path(environ_cp):
Avijitf88a6f92018-07-24 23:58:58 -0700998 """Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION.
Guangda Lai76f69382018-01-25 23:59:19 -0800999
Avijitf88a6f92018-07-24 23:58:58 -07001000Adapted from code contributed by Sami Kama (https://github.com/samikama).
Guangda Lai76f69382018-01-25 23:59:19 -08001001
Avijitf88a6f92018-07-24 23:58:58 -07001002Args:
1003 environ_cp: copy of the os.environ.
Guangda Lai76f69382018-01-25 23:59:19 -08001004
Avijitf88a6f92018-07-24 23:58:58 -07001005Raises:
1006 ValueError: if this method was called under non-Linux platform.
1007 UserInputError: if user has provided invalid input multiple times.
1008"""
1009 if not is_linux():
1010 raise ValueError(
1011 'Currently TensorRT is only supported on Linux platform.')
Guangda Lai76f69382018-01-25 23:59:19 -08001012
Avijitf88a6f92018-07-24 23:58:58 -07001013 # Ask user whether to add TensorRT support.
1014 if str(int(get_var(environ_cp, 'TF_NEED_TENSORRT', 'TensorRT',
1015 False))) != '1':
1016 return
Guangda Lai76f69382018-01-25 23:59:19 -08001017
Avijitf88a6f92018-07-24 23:58:58 -07001018 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
1019 ask_tensorrt_path = (r'Please specify the location where TensorRT is '
1020 'installed. [Default is %s]:') % (
1021 _DEFAULT_TENSORRT_PATH_LINUX)
1022 trt_install_path = get_from_env_or_user_or_default(
1023 environ_cp, 'TENSORRT_INSTALL_PATH', ask_tensorrt_path,
1024 _DEFAULT_TENSORRT_PATH_LINUX)
Guangda Lai76f69382018-01-25 23:59:19 -08001025
Avijitf88a6f92018-07-24 23:58:58 -07001026 # Result returned from "read" will be used unexpanded. That make "~"
1027 # unusable. Going through one more level of expansion to handle that.
1028 trt_install_path = os.path.realpath(
1029 os.path.expanduser(trt_install_path))
Guangda Lai76f69382018-01-25 23:59:19 -08001030
Avijitf88a6f92018-07-24 23:58:58 -07001031 def find_libs(search_path):
1032 """Search for libnvinfer.so in "search_path"."""
1033 fl = set()
1034 if os.path.exists(search_path) and os.path.isdir(search_path):
1035 fl.update([
1036 os.path.realpath(os.path.join(search_path, x))
1037 for x in os.listdir(search_path) if 'libnvinfer.so' in x
1038 ])
1039 return fl
Guangda Lai76f69382018-01-25 23:59:19 -08001040
Avijitf88a6f92018-07-24 23:58:58 -07001041 possible_files = find_libs(trt_install_path)
1042 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib')))
1043 possible_files.update(
1044 find_libs(os.path.join(trt_install_path, 'lib64')))
1045 cuda_ver = convert_version_to_int(environ_cp['TF_CUDA_VERSION'])
1046 cudnn_ver = convert_version_to_int(environ_cp['TF_CUDNN_VERSION'])
1047 nvinfer_pattern = re.compile('.*libnvinfer.so.?(.*)$')
1048 highest_ver = [0, None, None]
Guangda Lai76f69382018-01-25 23:59:19 -08001049
Avijitf88a6f92018-07-24 23:58:58 -07001050 for lib_file in possible_files:
1051 if is_cuda_compatible(lib_file, cuda_ver, cudnn_ver):
1052 matches = nvinfer_pattern.search(lib_file)
1053 if len(matches.groups()) == 0:
1054 continue
1055 ver_str = matches.group(1)
1056 ver = convert_version_to_int(ver_str) if len(ver_str) else 0
1057 if ver > highest_ver[0]:
1058 highest_ver = [ver, ver_str, lib_file]
1059 if highest_ver[1] is not None:
1060 trt_install_path = os.path.dirname(highest_ver[2])
1061 tf_tensorrt_version = highest_ver[1]
1062 break
Guangda Lai76f69382018-01-25 23:59:19 -08001063
Avijitf88a6f92018-07-24 23:58:58 -07001064 # Try another alternative from ldconfig.
1065 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
1066 ldconfig_output = run_shell([ldconfig_bin, '-p'])
1067 search_result = re.search('.*libnvinfer.so\\.?([0-9.]*).* => (.*)',
1068 ldconfig_output)
1069 if search_result:
1070 libnvinfer_path_from_ldconfig = search_result.group(2)
1071 if os.path.exists(libnvinfer_path_from_ldconfig):
1072 if is_cuda_compatible(libnvinfer_path_from_ldconfig, cuda_ver,
1073 cudnn_ver):
1074 trt_install_path = os.path.dirname(
1075 libnvinfer_path_from_ldconfig)
1076 tf_tensorrt_version = search_result.group(1)
1077 break
Guangda Lai76f69382018-01-25 23:59:19 -08001078
Avijitf88a6f92018-07-24 23:58:58 -07001079 # Reset and Retry
1080 if possible_files:
1081 print(
1082 'TensorRT libraries found in one the following directories',
1083 'are not compatible with selected cuda and cudnn installations'
1084 )
1085 print(trt_install_path)
1086 print(os.path.join(trt_install_path, 'lib'))
1087 print(os.path.join(trt_install_path, 'lib64'))
1088 if search_result:
1089 print(libnvinfer_path_from_ldconfig)
Yifei Fengdce9a492018-02-22 14:24:57 -08001090 else:
Avijitf88a6f92018-07-24 23:58:58 -07001091 print(
1092 'Invalid path to TensorRT. None of the following files can be found:'
1093 )
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
Avijitf88a6f92018-07-24 23:58:58 -07001100 else:
1101 raise UserInputError(
1102 'Invalid TF_TENSORRT setting was provided %d '
1103 'times in a row. Assuming to be a scripting mistake.' %
1104 _DEFAULT_PROMPT_ASK_ATTEMPTS)
1105
1106 # Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION
1107 environ_cp['TENSORRT_INSTALL_PATH'] = trt_install_path
1108 write_action_env_to_bazelrc('TENSORRT_INSTALL_PATH', trt_install_path)
1109 environ_cp['TF_TENSORRT_VERSION'] = tf_tensorrt_version
1110 write_action_env_to_bazelrc('TF_TENSORRT_VERSION', tf_tensorrt_version)
Guangda Lai76f69382018-01-25 23:59:19 -08001111
1112
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001113def set_tf_nccl_install_path(environ_cp):
Avijitf88a6f92018-07-24 23:58:58 -07001114 """Set NCCL_INSTALL_PATH and TF_NCCL_VERSION.
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001115
Avijitf88a6f92018-07-24 23:58:58 -07001116Args:
1117 environ_cp: copy of the os.environ.
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001118
Avijitf88a6f92018-07-24 23:58:58 -07001119Raises:
1120 ValueError: if this method was called under non-Linux platform.
1121 UserInputError: if user has provided invalid input multiple times.
1122"""
1123 if not is_linux():
1124 raise ValueError(
1125 'Currently NCCL is only supported on Linux platforms.')
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001126
Avijitf88a6f92018-07-24 23:58:58 -07001127 ask_nccl_version = (
1128 'Please specify the NCCL version you want to use. '
1129 '[Leave empty to default to NCCL %s]: ') % _DEFAULT_NCCL_VERSION
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001130
Avijitf88a6f92018-07-24 23:58:58 -07001131 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
1132 tf_nccl_version = get_from_env_or_user_or_default(
1133 environ_cp, 'TF_NCCL_VERSION', ask_nccl_version,
1134 _DEFAULT_NCCL_VERSION)
1135 tf_nccl_version = reformat_version_sequence(str(tf_nccl_version), 1)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001136
Avijitf88a6f92018-07-24 23:58:58 -07001137 if tf_nccl_version == '1':
1138 break # No need to get install path, NCCL 1 is a GitHub repo.
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001139
Avijitf88a6f92018-07-24 23:58:58 -07001140 # TODO(csigg): Look with ldconfig first if we can find the library in paths
1141 # like /usr/lib/x86_64-linux-gnu and the header file in the corresponding
1142 # include directory. This is where the NCCL .deb packages install them.
1143 # Then ask the user if we should use that. Instead of a single
1144 # NCCL_INSTALL_PATH, pass separate NCCL_LIB_PATH and NCCL_HDR_PATH to
1145 # nccl_configure.bzl
1146 default_nccl_path = environ_cp.get('CUDA_TOOLKIT_PATH')
1147 ask_nccl_path = (
1148 r'Please specify the location where NCCL %s library is '
1149 'installed. Refer to README.md for more details. [Default '
1150 'is %s]:') % (tf_nccl_version, default_nccl_path)
1151 nccl_install_path = get_from_env_or_user_or_default(
1152 environ_cp, 'NCCL_INSTALL_PATH', ask_nccl_path, default_nccl_path)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001153
Avijitf88a6f92018-07-24 23:58:58 -07001154 # Result returned from "read" will be used unexpanded. That make "~"
1155 # unusable. Going through one more level of expansion to handle that.
1156 nccl_install_path = os.path.realpath(
1157 os.path.expanduser(nccl_install_path))
1158 if is_windows() or is_cygwin():
1159 nccl_install_path = cygpath(nccl_install_path)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001160
Avijitf88a6f92018-07-24 23:58:58 -07001161 if is_windows():
1162 nccl_lib_path = 'lib/x64/nccl.lib'
1163 elif is_linux():
1164 nccl_lib_path = 'lib/libnccl.so.%s' % tf_nccl_version
1165 elif is_macos():
1166 nccl_lib_path = 'lib/libnccl.%s.dylib' % tf_nccl_version
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001167
Avijitf88a6f92018-07-24 23:58:58 -07001168 nccl_lib_path = os.path.join(nccl_install_path, nccl_lib_path)
1169 nccl_hdr_path = os.path.join(nccl_install_path, 'include/nccl.h')
1170 nccl_license_path = os.path.join(nccl_install_path, 'NCCL-SLA.txt')
1171 if os.path.exists(nccl_lib_path) and os.path.exists(
1172 nccl_hdr_path) and os.path.exists(nccl_license_path):
1173 # Set NCCL_INSTALL_PATH
1174 environ_cp['NCCL_INSTALL_PATH'] = nccl_install_path
1175 write_action_env_to_bazelrc('NCCL_INSTALL_PATH', nccl_install_path)
1176 break
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001177
Avijitf88a6f92018-07-24 23:58:58 -07001178 # Reset and Retry
1179 print(
1180 'Invalid path to NCCL %s toolkit, %s or %s not found. Please use the '
1181 'O/S agnostic package of NCCL 2' % (tf_nccl_version, nccl_lib_path,
1182 nccl_hdr_path))
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001183
Avijitf88a6f92018-07-24 23:58:58 -07001184 environ_cp['TF_NCCL_VERSION'] = ''
1185 else:
1186 raise UserInputError(
1187 'Invalid TF_NCCL setting was provided %d '
1188 'times in a row. Assuming to be a scripting mistake.' %
1189 _DEFAULT_PROMPT_ASK_ATTEMPTS)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001190
Avijitf88a6f92018-07-24 23:58:58 -07001191 # Set TF_NCCL_VERSION
1192 environ_cp['TF_NCCL_VERSION'] = tf_nccl_version
1193 write_action_env_to_bazelrc('TF_NCCL_VERSION', tf_nccl_version)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001194
1195
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001196def get_native_cuda_compute_capabilities(environ_cp):
Avijitf88a6f92018-07-24 23:58:58 -07001197 """Get native cuda compute capabilities.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001198
Avijitf88a6f92018-07-24 23:58:58 -07001199Args:
1200 environ_cp: copy of the os.environ.
1201Returns:
1202 string of native cuda compute capabilities, separated by comma.
1203"""
1204 device_query_bin = os.path.join(
1205 environ_cp.get('CUDA_TOOLKIT_PATH'), 'extras/demo_suite/deviceQuery')
1206 if os.path.isfile(device_query_bin) and os.access(device_query_bin,
1207 os.X_OK):
1208 try:
1209 output = run_shell(device_query_bin).split('\n')
1210 pattern = re.compile('[0-9]*\\.[0-9]*')
1211 output = [pattern.search(x) for x in output if 'Capability' in x]
1212 output = ','.join(x.group() for x in output if x is not None)
1213 except subprocess.CalledProcessError:
1214 output = ''
1215 else:
1216 output = ''
1217 return output
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001218
1219
1220def set_tf_cuda_compute_capabilities(environ_cp):
Avijitf88a6f92018-07-24 23:58:58 -07001221 """Set TF_CUDA_COMPUTE_CAPABILITIES."""
1222 while True:
1223 native_cuda_compute_capabilities = get_native_cuda_compute_capabilities(
1224 environ_cp)
1225 if not native_cuda_compute_capabilities:
1226 default_cuda_compute_capabilities = _DEFAULT_CUDA_COMPUTE_CAPABILITIES
1227 else:
1228 default_cuda_compute_capabilities = native_cuda_compute_capabilities
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001229
Avijitf88a6f92018-07-24 23:58:58 -07001230 ask_cuda_compute_capabilities = (
1231 'Please specify a list of comma-separated '
1232 'Cuda compute capabilities you want to '
1233 'build with.\nYou can find the compute '
1234 'capability of your device at: '
1235 'https://developer.nvidia.com/cuda-gpus.\nPlease'
1236 ' note that each additional compute '
1237 'capability significantly increases your '
1238 'build time and binary size. [Default is: %s]' %
1239 default_cuda_compute_capabilities)
1240 tf_cuda_compute_capabilities = get_from_env_or_user_or_default(
1241 environ_cp, 'TF_CUDA_COMPUTE_CAPABILITIES',
1242 ask_cuda_compute_capabilities, default_cuda_compute_capabilities)
1243 # Check whether all capabilities from the input is valid
1244 all_valid = True
1245 # Remove all whitespace characters before splitting the string
1246 # that users may insert by accident, as this will result in error
1247 tf_cuda_compute_capabilities = ''.join(
1248 tf_cuda_compute_capabilities.split())
1249 for compute_capability in tf_cuda_compute_capabilities.split(','):
1250 m = re.match('[0-9]+.[0-9]+', compute_capability)
1251 if not m:
1252 print('Invalid compute capability: ' % compute_capability)
1253 all_valid = False
1254 else:
1255 ver = int(m.group(0).split('.')[0])
1256 if ver < 3:
1257 print(
1258 'Only compute capabilities 3.0 or higher are supported.'
1259 )
1260 all_valid = False
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001261
Avijitf88a6f92018-07-24 23:58:58 -07001262 if all_valid:
1263 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001264
Avijitf88a6f92018-07-24 23:58:58 -07001265 # Reset and Retry
1266 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001267
Avijitf88a6f92018-07-24 23:58:58 -07001268 # Set TF_CUDA_COMPUTE_CAPABILITIES
1269 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = tf_cuda_compute_capabilities
1270 write_action_env_to_bazelrc('TF_CUDA_COMPUTE_CAPABILITIES',
1271 tf_cuda_compute_capabilities)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001272
1273
1274def set_other_cuda_vars(environ_cp):
Avijitf88a6f92018-07-24 23:58:58 -07001275 """Set other CUDA related variables."""
1276 # If CUDA is enabled, always use GPU during build and test.
1277 if environ_cp.get('TF_CUDA_CLANG') == '1':
1278 write_to_bazelrc('build --config=cuda_clang')
1279 write_to_bazelrc('test --config=cuda_clang')
1280 else:
1281 write_to_bazelrc('build --config=cuda')
1282 write_to_bazelrc('test --config=cuda')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001283
1284
1285def set_host_cxx_compiler(environ_cp):
Avijitf88a6f92018-07-24 23:58:58 -07001286 """Set HOST_CXX_COMPILER."""
1287 default_cxx_host_compiler = which('g++') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001288
Avijitf88a6f92018-07-24 23:58:58 -07001289 host_cxx_compiler = prompt_loop_or_load_from_env(
1290 environ_cp,
1291 var_name='HOST_CXX_COMPILER',
1292 var_default=default_cxx_host_compiler,
1293 ask_for_var=('Please specify which C++ compiler should be used as the '
1294 'host C++ compiler.'),
1295 check_success=os.path.exists,
1296 error_msg='Invalid C++ compiler path. %s cannot be found.',
1297 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001298
Avijitf88a6f92018-07-24 23:58:58 -07001299 write_action_env_to_bazelrc('HOST_CXX_COMPILER', host_cxx_compiler)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001300
1301
1302def set_host_c_compiler(environ_cp):
Avijitf88a6f92018-07-24 23:58:58 -07001303 """Set HOST_C_COMPILER."""
1304 default_c_host_compiler = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001305
Avijitf88a6f92018-07-24 23:58:58 -07001306 host_c_compiler = prompt_loop_or_load_from_env(
1307 environ_cp,
1308 var_name='HOST_C_COMPILER',
1309 var_default=default_c_host_compiler,
1310 ask_for_var=(
1311 'Please specify which C compiler should be used as the host '
1312 'C compiler.'),
1313 check_success=os.path.exists,
1314 error_msg='Invalid C compiler path. %s cannot be found.',
1315 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001316
Avijitf88a6f92018-07-24 23:58:58 -07001317 write_action_env_to_bazelrc('HOST_C_COMPILER', host_c_compiler)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001318
1319
1320def set_computecpp_toolkit_path(environ_cp):
Avijitf88a6f92018-07-24 23:58:58 -07001321 """Set COMPUTECPP_TOOLKIT_PATH."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001322
Avijitf88a6f92018-07-24 23:58:58 -07001323 def toolkit_exists(toolkit_path):
1324 """Check if a computecpp toolkit path is valid."""
1325 if is_linux():
1326 sycl_rt_lib_path = 'lib/libComputeCpp.so'
1327 else:
1328 sycl_rt_lib_path = ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001329
Avijitf88a6f92018-07-24 23:58:58 -07001330 sycl_rt_lib_path_full = os.path.join(toolkit_path, sycl_rt_lib_path)
1331 exists = os.path.exists(sycl_rt_lib_path_full)
1332 if not exists:
1333 print('Invalid SYCL %s library path. %s cannot be found' %
1334 (_TF_OPENCL_VERSION, sycl_rt_lib_path_full))
1335 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001336
Avijitf88a6f92018-07-24 23:58:58 -07001337 computecpp_toolkit_path = prompt_loop_or_load_from_env(
1338 environ_cp,
1339 var_name='COMPUTECPP_TOOLKIT_PATH',
1340 var_default=_DEFAULT_COMPUTECPP_TOOLKIT_PATH,
1341 ask_for_var=(
1342 'Please specify the location where ComputeCpp for SYCL %s is '
1343 'installed.' % _TF_OPENCL_VERSION),
1344 check_success=toolkit_exists,
1345 error_msg='Invalid SYCL compiler path. %s cannot be found.',
1346 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001347
Avijitf88a6f92018-07-24 23:58:58 -07001348 write_action_env_to_bazelrc('COMPUTECPP_TOOLKIT_PATH',
1349 computecpp_toolkit_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001350
Michael Cased31531a2018-01-05 14:09:41 -08001351
Dandelion Man?90e42f32017-12-15 18:15:07 -08001352def set_trisycl_include_dir(environ_cp):
Avijitf88a6f92018-07-24 23:58:58 -07001353 """Set TRISYCL_INCLUDE_DIR."""
Frank Chenc4ef9272018-01-10 11:36:52 -08001354
Avijitf88a6f92018-07-24 23:58:58 -07001355 ask_trisycl_include_dir = ('Please specify the location of the triSYCL '
1356 'include directory. (Use --config=sycl_trisycl '
1357 'when building with Bazel) '
1358 '[Default is %s]: ') % (
1359 _DEFAULT_TRISYCL_INCLUDE_DIR)
Frank Chenc4ef9272018-01-10 11:36:52 -08001360
Avijitf88a6f92018-07-24 23:58:58 -07001361 while True:
1362 trisycl_include_dir = get_from_env_or_user_or_default(
1363 environ_cp, 'TRISYCL_INCLUDE_DIR', ask_trisycl_include_dir,
1364 _DEFAULT_TRISYCL_INCLUDE_DIR)
1365 if os.path.exists(trisycl_include_dir):
1366 break
Dandelion Man?90e42f32017-12-15 18:15:07 -08001367
Avijitf88a6f92018-07-24 23:58:58 -07001368 print('Invalid triSYCL include directory, %s cannot be found' %
1369 (trisycl_include_dir))
Dandelion Man?90e42f32017-12-15 18:15:07 -08001370
Avijitf88a6f92018-07-24 23:58:58 -07001371 # Set TRISYCL_INCLUDE_DIR
1372 environ_cp['TRISYCL_INCLUDE_DIR'] = trisycl_include_dir
1373 write_action_env_to_bazelrc('TRISYCL_INCLUDE_DIR', trisycl_include_dir)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001374
Yifei Fengb1d8c592017-11-22 13:42:21 -08001375
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001376def set_mpi_home(environ_cp):
Avijitf88a6f92018-07-24 23:58:58 -07001377 """Set MPI_HOME."""
Austin Anderson6afface2017-12-05 11:59:17 -08001378
Avijitf88a6f92018-07-24 23:58:58 -07001379 default_mpi_home = which('mpirun') or which('mpiexec') or ''
1380 default_mpi_home = os.path.dirname(os.path.dirname(default_mpi_home))
Jonathan Hseu008910f2017-08-25 14:01:05 -07001381
Avijitf88a6f92018-07-24 23:58:58 -07001382 def valid_mpi_path(mpi_home):
1383 exists = (os.path.exists(os.path.join(mpi_home, 'include'))
1384 and os.path.exists(os.path.join(mpi_home, 'lib')))
1385 if not exists:
1386 print('Invalid path to the MPI Toolkit. %s or %s cannot be found' %
1387 (os.path.join(mpi_home, 'include'),
1388 os.path.exists(os.path.join(mpi_home, 'lib'))))
1389 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001390
Avijitf88a6f92018-07-24 23:58:58 -07001391 _ = prompt_loop_or_load_from_env(
1392 environ_cp,
1393 var_name='MPI_HOME',
1394 var_default=default_mpi_home,
1395 ask_for_var='Please specify the MPI toolkit folder.',
1396 check_success=valid_mpi_path,
1397 error_msg='',
1398 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001399
1400
1401def set_other_mpi_vars(environ_cp):
Avijitf88a6f92018-07-24 23:58:58 -07001402 """Set other MPI related variables."""
1403 # Link the MPI header files
1404 mpi_home = environ_cp.get('MPI_HOME')
1405 symlink_force('%s/include/mpi.h' % mpi_home, 'third_party/mpi/mpi.h')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001406
Avijitf88a6f92018-07-24 23:58:58 -07001407 # Determine if we use OpenMPI or MVAPICH, these require different header files
1408 # to be included here to make bazel dependency checker happy
1409 if os.path.exists(
1410 os.path.join(mpi_home, 'include/mpi_portable_platform.h')):
1411 symlink_force(
1412 os.path.join(mpi_home, 'include/mpi_portable_platform.h'),
1413 'third_party/mpi/mpi_portable_platform.h')
1414 # TODO(gunan): avoid editing files in configure
1415 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=False',
1416 'MPI_LIB_IS_OPENMPI=True')
1417 else:
1418 # MVAPICH / MPICH
1419 symlink_force(
1420 os.path.join(mpi_home, 'include/mpio.h'), 'third_party/mpi/mpio.h')
1421 symlink_force(
1422 os.path.join(mpi_home, 'include/mpicxx.h'),
1423 'third_party/mpi/mpicxx.h')
1424 # TODO(gunan): avoid editing files in configure
1425 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=True',
1426 'MPI_LIB_IS_OPENMPI=False')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001427
Avijitf88a6f92018-07-24 23:58:58 -07001428 if os.path.exists(os.path.join(mpi_home, 'lib/libmpi.so')):
1429 symlink_force(
1430 os.path.join(mpi_home, 'lib/libmpi.so'),
1431 'third_party/mpi/libmpi.so')
1432 else:
1433 raise ValueError(
1434 'Cannot find the MPI library file in %s/lib' % mpi_home)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001435
1436
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001437def set_grpc_build_flags():
Avijitf88a6f92018-07-24 23:58:58 -07001438 write_to_bazelrc('build --define grpc_no_ares=true')
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001439
Michael Cased31531a2018-01-05 14:09:41 -08001440
Akshay Modi6070ae02018-06-18 21:00:34 -07001441def set_build_strip_flag():
Avijitf88a6f92018-07-24 23:58:58 -07001442 write_to_bazelrc('build --strip=always')
Akshay Modi6070ae02018-06-18 21:00:34 -07001443
1444
Dandelion Man?90e42f32017-12-15 18:15:07 -08001445def set_windows_build_flags():
Avijitf88a6f92018-07-24 23:58:58 -07001446 if is_windows():
1447 # The non-monolithic build is not supported yet
1448 write_to_bazelrc('build --config monolithic')
1449 # Suppress warning messages
1450 write_to_bazelrc('build --copt=-w --host_copt=-w')
1451 # Output more verbose information when something goes wrong
1452 write_to_bazelrc('build --verbose_failures')
Dandelion Man?90e42f32017-12-15 18:15:07 -08001453
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001454
Michael Cased31531a2018-01-05 14:09:41 -08001455def config_info_line(name, help_text):
Avijitf88a6f92018-07-24 23:58:58 -07001456 """Helper function to print formatted help text for Bazel config options."""
1457 print('\t--config=%-12s\t# %s' % (name, help_text))
Michael Cased31531a2018-01-05 14:09:41 -08001458
1459
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001460def main():
Avijitf88a6f92018-07-24 23:58:58 -07001461 parser = argparse.ArgumentParser()
1462 parser.add_argument(
1463 "--workspace",
1464 type=str,
1465 default=_TF_WORKSPACE_ROOT,
1466 help="The absolute path to your active Bazel workspace.")
1467 args = parser.parse_args()
Shanqing Cai71445712018-03-12 19:33:52 -07001468
Avijitf88a6f92018-07-24 23:58:58 -07001469 # Make a copy of os.environ to be clear when functions and getting and setting
1470 # environment variables.
1471 environ_cp = dict(os.environ)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001472
Avijitf88a6f92018-07-24 23:58:58 -07001473 check_bazel_version('0.10.0')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001474
Avijitf88a6f92018-07-24 23:58:58 -07001475 reset_tf_configure_bazelrc(args.workspace)
1476 cleanup_makefile()
1477 setup_python(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001478
Avijitf88a6f92018-07-24 23:58:58 -07001479 if is_windows():
1480 environ_cp['TF_NEED_AWS'] = '0'
1481 environ_cp['TF_NEED_GCP'] = '0'
1482 environ_cp['TF_NEED_HDFS'] = '0'
1483 environ_cp['TF_NEED_JEMALLOC'] = '0'
1484 environ_cp['TF_NEED_KAFKA'] = '0'
1485 environ_cp['TF_NEED_OPENCL_SYCL'] = '0'
1486 environ_cp['TF_NEED_COMPUTECPP'] = '0'
1487 environ_cp['TF_NEED_OPENCL'] = '0'
1488 environ_cp['TF_CUDA_CLANG'] = '0'
1489 environ_cp['TF_NEED_TENSORRT'] = '0'
1490 # TODO(ibiryukov): Investigate using clang as a cpu or cuda compiler on
1491 # Windows.
1492 environ_cp['TF_DOWNLOAD_CLANG'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001493
Avijitf88a6f92018-07-24 23:58:58 -07001494 if is_macos():
1495 environ_cp['TF_NEED_JEMALLOC'] = '0'
1496 environ_cp['TF_NEED_TENSORRT'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001497
Avijitf88a6f92018-07-24 23:58:58 -07001498 set_build_var(environ_cp, 'TF_NEED_JEMALLOC', 'jemalloc as malloc',
1499 'with_jemalloc', True)
1500 set_build_var(environ_cp, 'TF_NEED_GCP', 'Google Cloud Platform',
1501 'with_gcp_support', True, 'gcp')
1502 set_build_var(environ_cp, 'TF_NEED_HDFS', 'Hadoop File System',
1503 'with_hdfs_support', True, 'hdfs')
1504 set_build_var(environ_cp, 'TF_NEED_AWS', 'Amazon AWS Platform',
1505 'with_aws_support', True, 'aws')
1506 set_build_var(environ_cp, 'TF_NEED_KAFKA', 'Apache Kafka Platform',
1507 'with_kafka_support', True, 'kafka')
1508 set_build_var(environ_cp, 'TF_ENABLE_XLA', 'XLA JIT', 'with_xla_support',
1509 False, 'xla')
1510 set_build_var(environ_cp, 'TF_NEED_GDR', 'GDR', 'with_gdr_support', False,
1511 'gdr')
1512 set_build_var(environ_cp, 'TF_NEED_VERBS', 'VERBS', 'with_verbs_support',
1513 False, 'verbs')
1514 set_build_var(environ_cp, 'TF_NEED_NGRAPH', 'nGraph',
1515 'with_ngraph_support', False, 'ngraph')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001516
Avijitf88a6f92018-07-24 23:58:58 -07001517 set_action_env_var(environ_cp, 'TF_NEED_OPENCL_SYCL', 'OpenCL SYCL', False)
1518 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
1519 set_host_cxx_compiler(environ_cp)
1520 set_host_c_compiler(environ_cp)
1521 set_action_env_var(environ_cp, 'TF_NEED_COMPUTECPP', 'ComputeCPP',
1522 True)
1523 if environ_cp.get('TF_NEED_COMPUTECPP') == '1':
1524 set_computecpp_toolkit_path(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001525 else:
Avijitf88a6f92018-07-24 23:58:58 -07001526 set_trisycl_include_dir(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001527
Avijitf88a6f92018-07-24 23:58:58 -07001528 set_action_env_var(environ_cp, 'TF_NEED_CUDA', 'CUDA', False)
1529 if (environ_cp.get('TF_NEED_CUDA') == '1'
1530 and 'TF_CUDA_CONFIG_REPO' not in environ_cp):
1531 set_tf_cuda_version(environ_cp)
1532 set_tf_cudnn_version(environ_cp)
1533 if is_linux():
1534 set_tf_tensorrt_install_path(environ_cp)
1535 set_tf_nccl_install_path(environ_cp)
Michael Case0073d132018-04-11 09:34:44 -07001536
Avijitf88a6f92018-07-24 23:58:58 -07001537 set_tf_cuda_compute_capabilities(environ_cp)
1538 if 'LD_LIBRARY_PATH' in environ_cp and environ_cp.get(
1539 'LD_LIBRARY_PATH') != '1':
1540 write_action_env_to_bazelrc('LD_LIBRARY_PATH',
1541 environ_cp.get('LD_LIBRARY_PATH'))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001542
Avijitf88a6f92018-07-24 23:58:58 -07001543 set_tf_cuda_clang(environ_cp)
1544 if environ_cp.get('TF_CUDA_CLANG') == '1':
1545 # Ask whether we should download the clang toolchain.
1546 set_tf_download_clang(environ_cp)
1547 if environ_cp.get('TF_DOWNLOAD_CLANG') != '1':
1548 # Set up which clang we should use as the cuda / host compiler.
1549 set_clang_cuda_compiler_path(environ_cp)
1550 else:
1551 # Set up which gcc nvcc should use as the host compiler
1552 # No need to set this on Windows
1553 if not is_windows():
1554 set_gcc_host_compiler_path(environ_cp)
1555 set_other_cuda_vars(environ_cp)
1556 else:
1557 # CUDA not required. Ask whether we should download the clang toolchain and
1558 # use it for the CPU build.
1559 set_tf_download_clang(environ_cp)
1560 if environ_cp.get('TF_DOWNLOAD_CLANG') == '1':
1561 write_to_bazelrc('build --config=download_clang')
1562 write_to_bazelrc('test --config=download_clang')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001563
Avijitf88a6f92018-07-24 23:58:58 -07001564 set_build_var(environ_cp, 'TF_NEED_MPI', 'MPI', 'with_mpi_support', False)
1565 if environ_cp.get('TF_NEED_MPI') == '1':
1566 set_mpi_home(environ_cp)
1567 set_other_mpi_vars(environ_cp)
1568
1569 set_grpc_build_flags()
1570 set_cc_opt_flags(environ_cp)
1571 set_build_strip_flag()
1572 set_windows_build_flags()
1573
1574 if get_var(environ_cp, 'TF_SET_ANDROID_WORKSPACE', 'android workspace',
1575 False,
1576 ('Would you like to interactively configure ./WORKSPACE for '
1577 'Android builds?'), 'Searching for NDK and SDK installations.',
1578 'Not configuring the WORKSPACE for Android builds.'):
1579 create_android_ndk_rule(environ_cp)
1580 create_android_sdk_rule(environ_cp)
1581
1582 print('Preconfigured Bazel build configs. You can use any of the below by '
1583 'adding "--config=<>" to your build command. See tools/bazel.rc for '
1584 'more details.')
1585 config_info_line('mkl', 'Build with MKL support.')
1586 config_info_line('monolithic',
1587 'Config for mostly static monolithic build.')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001588
Austin Anderson6afface2017-12-05 11:59:17 -08001589
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001590if __name__ == '__main__':
Avijitf88a6f92018-07-24 23:58:58 -07001591 main()