blob: 3bbbee7abfa70c0212b5d4399231781c602f938a [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:
Avijit121e0162018-07-24 23:35:27 -070031 from shutil import which
Jonathan Hseu008910f2017-08-25 14:01:05 -070032except ImportError:
Avijit121e0162018-07-24 23:35:27 -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):
Avijit121e0162018-07-24 23:35:27 -070059 pass
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070060
61
62def is_windows():
Avijit121e0162018-07-24 23:35:27 -070063 return platform.system() == 'Windows'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070064
65
66def is_linux():
Avijit121e0162018-07-24 23:35:27 -070067 return platform.system() == 'Linux'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070068
69
70def is_macos():
Avijit121e0162018-07-24 23:35:27 -070071 return platform.system() == 'Darwin'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070072
73
74def is_ppc64le():
Avijit121e0162018-07-24 23:35:27 -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():
Avijit121e0162018-07-24 23:35:27 -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):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070083 try:
Avijit121e0162018-07-24 23:35:27 -070084 try:
85 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):
Avijit121e0162018-07-24 23:35:27 -070094 """Force symlink, equivalent of 'ln -sf'.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070095
96 Args:
97 target: items to link to.
98 link_name: name of the link.
99 """
Avijit121e0162018-07-24 23:35:27 -0700100 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):
Avijit121e0162018-07-24 23:35:27 -0700111 """Replace old string with new string in file.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700112
113 Args:
114 filename: string for filename.
115 old: string to replace.
116 new: new string to replace to.
117 """
Avijit121e0162018-07-24 23:35:27 -0700118 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):
Avijit121e0162018-07-24 23:35:27 -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):
Avijit121e0162018-07-24 23:35:27 -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):
Avijit121e0162018-07-24 23:35:27 -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):
Avijit121e0162018-07-24 23:35:27 -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):
Avijit121e0162018-07-24 23:35:27 -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([
163 python_bin_path, '-c',
164 'from distutils.sysconfig import get_python_lib;'
165 'print(get_python_lib())'
166 ])
167 ]
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700168
Avijit121e0162018-07-24 23:35:27 -0700169 all_paths = set(python_paths + library_paths)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700170
Avijit121e0162018-07-24 23:35:27 -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):
Avijit121e0162018-07-24 23:35:27 -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):
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -0700227 python_major_version = get_python_major_version(python_bin_path)
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700228
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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):
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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():
Avijit121e0162018-07-24 23:35:27 -0700268 """Delete any leftover BUILD files from the Makefile build.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700269
270 These files could interfere with Bazel parsing.
271 """
Avijit121e0162018-07-24 23:35:27 -0700272 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):
Avijit121e0162018-07-24 23:35:27 -0700288 """Get boolean input from user.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700289
290 If var_name is not set in env, ask user to enable query_item or not. If the
291 response is empty, use the default.
292
293 Args:
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.
Michael Cased90054e2018-02-07 14:36:00 -0800300 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700301 no_reply: optional string for reply when feature is disabled.
302
303 Returns:
304 boolean value of the variable.
Frank Chenc4ef9272018-01-10 11:36:52 -0800305
306 Raises:
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.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700311 """
Avijit121e0162018-07-24 23:35:27 -0700312 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
Avijit121e0162018-07-24 23:35:27 -0700319 yes_reply += '\n'
320 no_reply += '\n'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700321
Avijit121e0162018-07-24 23:35:27 -0700322 if enabled_by_default:
323 question += ' [Y/n]: '
Frank Chenc4ef9272018-01-10 11:36:52 -0800324 else:
Avijit121e0162018-07-24 23:35:27 -0700325 question += ' [y/N]: '
Frank Chenc4ef9272018-01-10 11:36:52 -0800326
Avijit121e0162018-07-24 23:35:27 -0700327 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
336 else:
337 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))
343
344 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):
371 """Set if query_item will be enabled for the build.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700372
373 Ask user if query_item will be enabled. Default is used if no input is given.
374 Set subprocess environment variable and write to .bazelrc if enabled.
375
376 Args:
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.
Michael Case98850a52017-09-14 13:35:57 -0700383 bazel_config_name: Name for Bazel --config argument to enable build feature.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700384 """
385
Avijit121e0162018-07-24 23:35:27 -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):
Avijit121e0162018-07-24 23:35:27 -0700405 """Set boolean action_env variable.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700406
407 Ask user if query_item will be enabled. Default is used if no input is given.
408 Set environment variable and write to .bazelrc.
409
410 Args:
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.
Michael Cased90054e2018-02-07 14:36:00 -0800417 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700418 no_reply: optional string for reply when feature is disabled.
419 """
Avijit121e0162018-07-24 23:35:27 -0700420 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
Avijit121e0162018-07-24 23:35:27 -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):
Avijit121e0162018-07-24 23:35:27 -0700429 """Convert a version number to a integer that can be used to compare.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700430
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700431 Version 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.
433
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700434 Args:
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700435 version: a version to be converted
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700436
437 Returns:
438 An integer if converted successfully, otherwise return None.
439 """
Avijit121e0162018-07-24 23:35:27 -0700440 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
Avijit121e0162018-07-24 23:35:27 -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):
Avijit121e0162018-07-24 23:35:27 -0700451 """Check installed bazel version is at least min_version.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700452
453 Args:
454 min_version: string for minimum bazel version.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700455
456 Returns:
457 The bazel version detected.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700458 """
Avijit121e0162018-07-24 23:35:27 -0700459 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
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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)
477 return curr_version
478
479 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)
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700486 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700487
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700488
489def set_cc_opt_flags(environ_cp):
Avijit121e0162018-07-24 23:35:27 -0700490 """Set up architecture-dependent optimization flags.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700491
492 Also append CC optimization flags to bazel.rc..
493
494 Args:
495 environ_cp: copy of the os.environ.
496 """
Avijit121e0162018-07-24 23:35:27 -0700497 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')
516
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700517
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700518def set_tf_cuda_clang(environ_cp):
Avijit121e0162018-07-24 23:35:27 -0700519 """set TF_CUDA_CLANG action_env.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700520
521 Args:
522 environ_cp: copy of the os.environ.
523 """
Avijit121e0162018-07-24 23:35:27 -0700524 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):
Avijit121e0162018-07-24 23:35:27 -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):
Avijit121e0162018-07-24 23:35:27 -0700554 """Get var_name either from env, or user or default.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700555
556 If var_name has been set as environment variable, use the preset value, else
557 ask for user input. If no input is provided, the default is used.
558
559 Args:
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.
564
565 Returns:
566 string value for var_name
567 """
Avijit121e0162018-07-24 23:35:27 -0700568 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):
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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):
610 """Loop over user prompts for an ENV param until receiving a valid response.
Austin Anderson6afface2017-12-05 11:59:17 -0800611
612 For the env param var_name, read from the environment or verify user input
613 until receiving valid input. When done, set var_name in the environ_cp to its
614 new value.
615
616 Args:
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.
631
632 Returns:
633 [String] The value of var_name after querying for input.
634
635 Raises:
636 UserInputError: if a query has been attempted n_ask_attempts times without
Frank Chenc4ef9272018-01-10 11:36:52 -0800637 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.
Austin Anderson6afface2017-12-05 11:59:17 -0800640 """
Avijit121e0162018-07-24 23:35:27 -0700641 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
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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):
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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):
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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):
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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):
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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
Avijit121e0162018-07-24 23:35:27 -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=
792 'Please specify which gcc should be used by nvcc as the host compiler.',
793 check_success=os.path.exists,
794 error_msg='Invalid gcc path. %s cannot be found.',
795 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700796
Avijit121e0162018-07-24 23:35:27 -0700797 write_action_env_to_bazelrc('GCC_HOST_COMPILER_PATH',
798 gcc_host_compiler_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700799
800
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800801def reformat_version_sequence(version_str, sequence_count):
Avijit121e0162018-07-24 23:35:27 -0700802 """Reformat the version string to have the given number of sequences.
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800803
804 For example:
805 Given (7, 2) -> 7.0
806 (7.0.1, 2) -> 7.0
807 (5, 1) -> 5
808 (5.0.3.2, 1) -> 5
809
810 Args:
811 version_str: String, the version string.
812 sequence_count: int, an integer.
813 Returns:
814 string, reformatted version string.
815 """
Avijit121e0162018-07-24 23:35:27 -0700816 v = version_str.split('.')
817 if len(v) < sequence_count:
818 v = v + (['0'] * (sequence_count - len(v)))
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800819
Avijit121e0162018-07-24 23:35:27 -0700820 return '.'.join(v[:sequence_count])
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800821
822
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700823def set_tf_cuda_version(environ_cp):
Avijit121e0162018-07-24 23:35:27 -0700824 """Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION."""
825 ask_cuda_version = (
826 'Please specify the CUDA SDK version you want to use. '
827 '[Leave empty to default to CUDA %s]: ') % _DEFAULT_CUDA_VERSION
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700828
Avijit121e0162018-07-24 23:35:27 -0700829 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
830 # Configure the Cuda SDK version to use.
831 tf_cuda_version = get_from_env_or_user_or_default(
832 environ_cp, 'TF_CUDA_VERSION', ask_cuda_version,
833 _DEFAULT_CUDA_VERSION)
834 tf_cuda_version = reformat_version_sequence(str(tf_cuda_version), 2)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700835
Avijit121e0162018-07-24 23:35:27 -0700836 # Find out where the CUDA toolkit is installed
837 default_cuda_path = _DEFAULT_CUDA_PATH
838 if is_windows() or is_cygwin():
839 default_cuda_path = cygpath(
840 environ_cp.get('CUDA_PATH', _DEFAULT_CUDA_PATH_WIN))
841 elif is_linux():
842 # If the default doesn't exist, try an alternative default.
843 if (not os.path.exists(default_cuda_path)
844 ) and os.path.exists(_DEFAULT_CUDA_PATH_LINUX):
845 default_cuda_path = _DEFAULT_CUDA_PATH_LINUX
846 ask_cuda_path = ('Please specify the location where CUDA %s toolkit is'
847 ' installed. Refer to README.md for more details. '
848 '[Default is %s]: ') % (tf_cuda_version,
849 default_cuda_path)
850 cuda_toolkit_path = get_from_env_or_user_or_default(
851 environ_cp, 'CUDA_TOOLKIT_PATH', ask_cuda_path, default_cuda_path)
852 if is_windows() or is_cygwin():
853 cuda_toolkit_path = cygpath(cuda_toolkit_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700854
Avijit121e0162018-07-24 23:35:27 -0700855 if is_windows():
856 cuda_rt_lib_path = 'lib/x64/cudart.lib'
857 elif is_linux():
858 cuda_rt_lib_path = 'lib64/libcudart.so.%s' % tf_cuda_version
859 elif is_macos():
860 cuda_rt_lib_path = 'lib/libcudart.%s.dylib' % tf_cuda_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700861
Avijit121e0162018-07-24 23:35:27 -0700862 cuda_toolkit_path_full = os.path.join(cuda_toolkit_path,
863 cuda_rt_lib_path)
864 if os.path.exists(cuda_toolkit_path_full):
865 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700866
Avijit121e0162018-07-24 23:35:27 -0700867 # Reset and retry
868 print('Invalid path to CUDA %s toolkit. %s cannot be found' %
869 (tf_cuda_version, cuda_toolkit_path_full))
870 environ_cp['TF_CUDA_VERSION'] = ''
871 environ_cp['CUDA_TOOLKIT_PATH'] = ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700872
Avijit121e0162018-07-24 23:35:27 -0700873 else:
874 raise UserInputError(
875 'Invalid TF_CUDA_SETTING setting was provided %d '
876 'times in a row. Assuming to be a scripting mistake.' %
877 _DEFAULT_PROMPT_ASK_ATTEMPTS)
Austin Andersonf9a88f82017-12-13 11:49:40 -0800878
Avijit121e0162018-07-24 23:35:27 -0700879 # Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION
880 environ_cp['CUDA_TOOLKIT_PATH'] = cuda_toolkit_path
881 write_action_env_to_bazelrc('CUDA_TOOLKIT_PATH', cuda_toolkit_path)
882 environ_cp['TF_CUDA_VERSION'] = tf_cuda_version
883 write_action_env_to_bazelrc('TF_CUDA_VERSION', tf_cuda_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700884
885
Yifei Fengb1d8c592017-11-22 13:42:21 -0800886def set_tf_cudnn_version(environ_cp):
Avijit121e0162018-07-24 23:35:27 -0700887 """Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION."""
888 ask_cudnn_version = (
889 'Please specify the cuDNN version you want to use. '
890 '[Leave empty to default to cuDNN %s.0]: ') % _DEFAULT_CUDNN_VERSION
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700891
Avijit121e0162018-07-24 23:35:27 -0700892 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
893 tf_cudnn_version = get_from_env_or_user_or_default(
894 environ_cp, 'TF_CUDNN_VERSION', ask_cudnn_version,
895 _DEFAULT_CUDNN_VERSION)
896 tf_cudnn_version = reformat_version_sequence(str(tf_cudnn_version), 1)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700897
Avijit121e0162018-07-24 23:35:27 -0700898 default_cudnn_path = environ_cp.get('CUDA_TOOLKIT_PATH')
899 ask_cudnn_path = (
900 r'Please specify the location where cuDNN %s library is '
901 'installed. Refer to README.md for more details. [Default'
902 ' is %s]:') % (tf_cudnn_version, default_cudnn_path)
903 cudnn_install_path = get_from_env_or_user_or_default(
904 environ_cp, 'CUDNN_INSTALL_PATH', ask_cudnn_path,
905 default_cudnn_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700906
Avijit121e0162018-07-24 23:35:27 -0700907 # Result returned from "read" will be used unexpanded. That make "~"
908 # unusable. Going through one more level of expansion to handle that.
909 cudnn_install_path = os.path.realpath(
910 os.path.expanduser(cudnn_install_path))
911 if is_windows() or is_cygwin():
912 cudnn_install_path = cygpath(cudnn_install_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700913
Avijit121e0162018-07-24 23:35:27 -0700914 if is_windows():
915 cuda_dnn_lib_path = 'lib/x64/cudnn.lib'
916 cuda_dnn_lib_alt_path = 'lib/x64/cudnn.lib'
917 elif is_linux():
918 cuda_dnn_lib_path = 'lib64/libcudnn.so.%s' % tf_cudnn_version
919 cuda_dnn_lib_alt_path = 'libcudnn.so.%s' % tf_cudnn_version
920 elif is_macos():
921 cuda_dnn_lib_path = 'lib/libcudnn.%s.dylib' % tf_cudnn_version
922 cuda_dnn_lib_alt_path = 'libcudnn.%s.dylib' % tf_cudnn_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700923
Avijit121e0162018-07-24 23:35:27 -0700924 cuda_dnn_lib_path_full = os.path.join(cudnn_install_path,
925 cuda_dnn_lib_path)
926 cuda_dnn_lib_alt_path_full = os.path.join(cudnn_install_path,
927 cuda_dnn_lib_alt_path)
928 if os.path.exists(cuda_dnn_lib_path_full) or os.path.exists(
929 cuda_dnn_lib_alt_path_full):
930 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700931
Avijit121e0162018-07-24 23:35:27 -0700932 # Try another alternative for Linux
933 if is_linux():
934 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
935 cudnn_path_from_ldconfig = run_shell([ldconfig_bin, '-p'])
936 cudnn_path_from_ldconfig = re.search('.*libcudnn.so .* => (.*)',
937 cudnn_path_from_ldconfig)
938 if cudnn_path_from_ldconfig:
939 cudnn_path_from_ldconfig = cudnn_path_from_ldconfig.group(1)
940 if os.path.exists('%s.%s' % (cudnn_path_from_ldconfig,
941 tf_cudnn_version)):
942 cudnn_install_path = os.path.dirname(
943 cudnn_path_from_ldconfig)
944 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700945
Avijit121e0162018-07-24 23:35:27 -0700946 # Reset and Retry
947 print(
948 'Invalid path to cuDNN %s toolkit. None of the following files can be '
949 'found:' % tf_cudnn_version)
950 print(cuda_dnn_lib_path_full)
951 print(cuda_dnn_lib_alt_path_full)
952 if is_linux():
953 print('%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700954
Avijit121e0162018-07-24 23:35:27 -0700955 environ_cp['TF_CUDNN_VERSION'] = ''
956 else:
957 raise UserInputError(
958 'Invalid TF_CUDNN setting was provided %d '
959 'times in a row. Assuming to be a scripting mistake.' %
960 _DEFAULT_PROMPT_ASK_ATTEMPTS)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700961
Avijit121e0162018-07-24 23:35:27 -0700962 # Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION
963 environ_cp['CUDNN_INSTALL_PATH'] = cudnn_install_path
964 write_action_env_to_bazelrc('CUDNN_INSTALL_PATH', cudnn_install_path)
965 environ_cp['TF_CUDNN_VERSION'] = tf_cudnn_version
966 write_action_env_to_bazelrc('TF_CUDNN_VERSION', tf_cudnn_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700967
968
Mingxing Tan1e7b0e42018-06-28 19:13:20 -0700969def is_cuda_compatible(lib, cuda_ver, cudnn_ver):
Avijit121e0162018-07-24 23:35:27 -0700970 """Check compatibility between given library and cudnn/cudart libraries."""
971 ldd_bin = which('ldd') or '/usr/bin/ldd'
972 ldd_out = run_shell([ldd_bin, lib], True)
973 ldd_out = ldd_out.split(os.linesep)
974 cudnn_pattern = re.compile('.*libcudnn.so\\.?(.*) =>.*$')
975 cuda_pattern = re.compile('.*libcudart.so\\.?(.*) =>.*$')
976 cudnn = None
977 cudart = None
978 cudnn_ok = True # assume no cudnn dependency by default
979 cuda_ok = True # assume no cuda dependency by default
980 for line in ldd_out:
981 if 'libcudnn.so' in line:
982 cudnn = cudnn_pattern.search(line)
983 cudnn_ok = False
984 elif 'libcudart.so' in line:
985 cudart = cuda_pattern.search(line)
986 cuda_ok = False
987 if cudnn and len(cudnn.group(1)):
988 cudnn = convert_version_to_int(cudnn.group(1))
989 if cudart and len(cudart.group(1)):
990 cudart = convert_version_to_int(cudart.group(1))
991 if cudnn is not None:
992 cudnn_ok = (cudnn == cudnn_ver)
993 if cudart is not None:
994 cuda_ok = (cudart == cuda_ver)
995 return cudnn_ok and cuda_ok
Mingxing Tan1e7b0e42018-06-28 19:13:20 -0700996
997
Guangda Lai76f69382018-01-25 23:59:19 -0800998def set_tf_tensorrt_install_path(environ_cp):
Avijit121e0162018-07-24 23:35:27 -0700999 """Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION.
Guangda Lai76f69382018-01-25 23:59:19 -08001000
1001 Adapted from code contributed by Sami Kama (https://github.com/samikama).
1002
1003 Args:
1004 environ_cp: copy of the os.environ.
1005
1006 Raises:
1007 ValueError: if this method was called under non-Linux platform.
1008 UserInputError: if user has provided invalid input multiple times.
1009 """
Avijit121e0162018-07-24 23:35:27 -07001010 if not is_linux():
1011 raise ValueError(
1012 'Currently TensorRT is only supported on Linux platform.')
Guangda Lai76f69382018-01-25 23:59:19 -08001013
Avijit121e0162018-07-24 23:35:27 -07001014 # Ask user whether to add TensorRT support.
1015 if str(int(get_var(environ_cp, 'TF_NEED_TENSORRT', 'TensorRT',
1016 False))) != '1':
1017 return
Guangda Lai76f69382018-01-25 23:59:19 -08001018
Avijit121e0162018-07-24 23:35:27 -07001019 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
1020 ask_tensorrt_path = (r'Please specify the location where TensorRT is '
1021 'installed. [Default is %s]:') % (
1022 _DEFAULT_TENSORRT_PATH_LINUX)
1023 trt_install_path = get_from_env_or_user_or_default(
1024 environ_cp, 'TENSORRT_INSTALL_PATH', ask_tensorrt_path,
1025 _DEFAULT_TENSORRT_PATH_LINUX)
Guangda Lai76f69382018-01-25 23:59:19 -08001026
Avijit121e0162018-07-24 23:35:27 -07001027 # Result returned from "read" will be used unexpanded. That make "~"
1028 # unusable. Going through one more level of expansion to handle that.
1029 trt_install_path = os.path.realpath(
1030 os.path.expanduser(trt_install_path))
Guangda Lai76f69382018-01-25 23:59:19 -08001031
Avijit121e0162018-07-24 23:35:27 -07001032 def find_libs(search_path):
1033 """Search for libnvinfer.so in "search_path"."""
1034 fl = set()
1035 if os.path.exists(search_path) and os.path.isdir(search_path):
1036 fl.update([
1037 os.path.realpath(os.path.join(search_path, x))
1038 for x in os.listdir(search_path) if 'libnvinfer.so' in x
1039 ])
1040 return fl
Guangda Lai76f69382018-01-25 23:59:19 -08001041
Avijit121e0162018-07-24 23:35:27 -07001042 possible_files = find_libs(trt_install_path)
1043 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib')))
1044 possible_files.update(
1045 find_libs(os.path.join(trt_install_path, 'lib64')))
1046 cuda_ver = convert_version_to_int(environ_cp['TF_CUDA_VERSION'])
1047 cudnn_ver = convert_version_to_int(environ_cp['TF_CUDNN_VERSION'])
1048 nvinfer_pattern = re.compile('.*libnvinfer.so.?(.*)$')
1049 highest_ver = [0, None, None]
Guangda Lai76f69382018-01-25 23:59:19 -08001050
Avijit121e0162018-07-24 23:35:27 -07001051 for lib_file in possible_files:
1052 if is_cuda_compatible(lib_file, cuda_ver, cudnn_ver):
1053 matches = nvinfer_pattern.search(lib_file)
1054 if len(matches.groups()) == 0:
1055 continue
1056 ver_str = matches.group(1)
1057 ver = convert_version_to_int(ver_str) if len(ver_str) else 0
1058 if ver > highest_ver[0]:
1059 highest_ver = [ver, ver_str, lib_file]
1060 if highest_ver[1] is not None:
1061 trt_install_path = os.path.dirname(highest_ver[2])
1062 tf_tensorrt_version = highest_ver[1]
1063 break
Guangda Lai76f69382018-01-25 23:59:19 -08001064
Avijit121e0162018-07-24 23:35:27 -07001065 # Try another alternative from ldconfig.
1066 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
1067 ldconfig_output = run_shell([ldconfig_bin, '-p'])
1068 search_result = re.search('.*libnvinfer.so\\.?([0-9.]*).* => (.*)',
1069 ldconfig_output)
1070 if search_result:
1071 libnvinfer_path_from_ldconfig = search_result.group(2)
1072 if os.path.exists(libnvinfer_path_from_ldconfig):
1073 if is_cuda_compatible(libnvinfer_path_from_ldconfig, cuda_ver,
1074 cudnn_ver):
1075 trt_install_path = os.path.dirname(
1076 libnvinfer_path_from_ldconfig)
1077 tf_tensorrt_version = search_result.group(1)
1078 break
Guangda Lai76f69382018-01-25 23:59:19 -08001079
Avijit121e0162018-07-24 23:35:27 -07001080 # Reset and Retry
1081 if possible_files:
1082 print(
1083 'TensorRT libraries found in one the following directories',
1084 'are not compatible with selected cuda and cudnn installations'
1085 )
1086 print(trt_install_path)
1087 print(os.path.join(trt_install_path, 'lib'))
1088 print(os.path.join(trt_install_path, 'lib64'))
1089 if search_result:
1090 print(libnvinfer_path_from_ldconfig)
1091 else:
1092 print(
1093 'Invalid path to TensorRT. None of the following files can be found:'
1094 )
1095 print(trt_install_path)
1096 print(os.path.join(trt_install_path, 'lib'))
1097 print(os.path.join(trt_install_path, 'lib64'))
1098 if search_result:
1099 print(libnvinfer_path_from_ldconfig)
1100
Yifei Fengdce9a492018-02-22 14:24:57 -08001101 else:
Avijit121e0162018-07-24 23:35:27 -07001102 raise UserInputError(
1103 'Invalid TF_TENSORRT setting was provided %d '
1104 'times in a row. Assuming to be a scripting mistake.' %
1105 _DEFAULT_PROMPT_ASK_ATTEMPTS)
Guangda Lai76f69382018-01-25 23:59:19 -08001106
Avijit121e0162018-07-24 23:35:27 -07001107 # Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION
1108 environ_cp['TENSORRT_INSTALL_PATH'] = trt_install_path
1109 write_action_env_to_bazelrc('TENSORRT_INSTALL_PATH', trt_install_path)
1110 environ_cp['TF_TENSORRT_VERSION'] = tf_tensorrt_version
1111 write_action_env_to_bazelrc('TF_TENSORRT_VERSION', tf_tensorrt_version)
Guangda Lai76f69382018-01-25 23:59:19 -08001112
1113
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001114def set_tf_nccl_install_path(environ_cp):
Avijit121e0162018-07-24 23:35:27 -07001115 """Set NCCL_INSTALL_PATH and TF_NCCL_VERSION.
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001116
1117 Args:
1118 environ_cp: copy of the os.environ.
1119
1120 Raises:
1121 ValueError: if this method was called under non-Linux platform.
1122 UserInputError: if user has provided invalid input multiple times.
1123 """
Avijit121e0162018-07-24 23:35:27 -07001124 if not is_linux():
1125 raise ValueError(
1126 'Currently NCCL is only supported on Linux platforms.')
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001127
Avijit121e0162018-07-24 23:35:27 -07001128 ask_nccl_version = (
1129 'Please specify the NCCL version you want to use. '
1130 '[Leave empty to default to NCCL %s]: ') % _DEFAULT_NCCL_VERSION
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001131
Avijit121e0162018-07-24 23:35:27 -07001132 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
1133 tf_nccl_version = get_from_env_or_user_or_default(
1134 environ_cp, 'TF_NCCL_VERSION', ask_nccl_version,
1135 _DEFAULT_NCCL_VERSION)
1136 tf_nccl_version = reformat_version_sequence(str(tf_nccl_version), 1)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001137
Avijit121e0162018-07-24 23:35:27 -07001138 if tf_nccl_version == '1':
1139 break # No need to get install path, NCCL 1 is a GitHub repo.
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001140
Avijit121e0162018-07-24 23:35:27 -07001141 # TODO(csigg): Look with ldconfig first if we can find the library in paths
1142 # like /usr/lib/x86_64-linux-gnu and the header file in the corresponding
1143 # include directory. This is where the NCCL .deb packages install them.
1144 # Then ask the user if we should use that. Instead of a single
1145 # NCCL_INSTALL_PATH, pass separate NCCL_LIB_PATH and NCCL_HDR_PATH to
1146 # nccl_configure.bzl
1147 default_nccl_path = environ_cp.get('CUDA_TOOLKIT_PATH')
1148 ask_nccl_path = (
1149 r'Please specify the location where NCCL %s library is '
1150 'installed. Refer to README.md for more details. [Default '
1151 'is %s]:') % (tf_nccl_version, default_nccl_path)
1152 nccl_install_path = get_from_env_or_user_or_default(
1153 environ_cp, 'NCCL_INSTALL_PATH', ask_nccl_path, default_nccl_path)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001154
Avijit121e0162018-07-24 23:35:27 -07001155 # Result returned from "read" will be used unexpanded. That make "~"
1156 # unusable. Going through one more level of expansion to handle that.
1157 nccl_install_path = os.path.realpath(
1158 os.path.expanduser(nccl_install_path))
1159 if is_windows() or is_cygwin():
1160 nccl_install_path = cygpath(nccl_install_path)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001161
Avijit121e0162018-07-24 23:35:27 -07001162 if is_windows():
1163 nccl_lib_path = 'lib/x64/nccl.lib'
1164 elif is_linux():
1165 nccl_lib_path = 'lib/libnccl.so.%s' % tf_nccl_version
1166 elif is_macos():
1167 nccl_lib_path = 'lib/libnccl.%s.dylib' % tf_nccl_version
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001168
Avijit121e0162018-07-24 23:35:27 -07001169 nccl_lib_path = os.path.join(nccl_install_path, nccl_lib_path)
1170 nccl_hdr_path = os.path.join(nccl_install_path, 'include/nccl.h')
1171 nccl_license_path = os.path.join(nccl_install_path, 'NCCL-SLA.txt')
1172 if os.path.exists(nccl_lib_path) and os.path.exists(
1173 nccl_hdr_path) and os.path.exists(nccl_license_path):
1174 # Set NCCL_INSTALL_PATH
1175 environ_cp['NCCL_INSTALL_PATH'] = nccl_install_path
1176 write_action_env_to_bazelrc('NCCL_INSTALL_PATH', nccl_install_path)
1177 break
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001178
Avijit121e0162018-07-24 23:35:27 -07001179 # Reset and Retry
1180 print(
1181 'Invalid path to NCCL %s toolkit, %s or %s not found. Please use the '
1182 'O/S agnostic package of NCCL 2' % (tf_nccl_version, nccl_lib_path,
1183 nccl_hdr_path))
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001184
Avijit121e0162018-07-24 23:35:27 -07001185 environ_cp['TF_NCCL_VERSION'] = ''
1186 else:
1187 raise UserInputError(
1188 'Invalid TF_NCCL setting was provided %d '
1189 'times in a row. Assuming to be a scripting mistake.' %
1190 _DEFAULT_PROMPT_ASK_ATTEMPTS)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001191
Avijit121e0162018-07-24 23:35:27 -07001192 # Set TF_NCCL_VERSION
1193 environ_cp['TF_NCCL_VERSION'] = tf_nccl_version
1194 write_action_env_to_bazelrc('TF_NCCL_VERSION', tf_nccl_version)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001195
1196
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001197def get_native_cuda_compute_capabilities(environ_cp):
Avijit121e0162018-07-24 23:35:27 -07001198 """Get native cuda compute capabilities.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001199
1200 Args:
1201 environ_cp: copy of the os.environ.
1202 Returns:
1203 string of native cuda compute capabilities, separated by comma.
1204 """
Avijit121e0162018-07-24 23:35:27 -07001205 device_query_bin = os.path.join(
1206 environ_cp.get('CUDA_TOOLKIT_PATH'), 'extras/demo_suite/deviceQuery')
1207 if os.path.isfile(device_query_bin) and os.access(device_query_bin,
1208 os.X_OK):
1209 try:
1210 output = run_shell(device_query_bin).split('\n')
1211 pattern = re.compile('[0-9]*\\.[0-9]*')
1212 output = [pattern.search(x) for x in output if 'Capability' in x]
1213 output = ','.join(x.group() for x in output if x is not None)
1214 except subprocess.CalledProcessError:
1215 output = ''
1216 else:
1217 output = ''
1218 return output
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001219
1220
1221def set_tf_cuda_compute_capabilities(environ_cp):
Avijit121e0162018-07-24 23:35:27 -07001222 """Set TF_CUDA_COMPUTE_CAPABILITIES."""
1223 while True:
1224 native_cuda_compute_capabilities = get_native_cuda_compute_capabilities(
1225 environ_cp)
1226 if not native_cuda_compute_capabilities:
1227 default_cuda_compute_capabilities = _DEFAULT_CUDA_COMPUTE_CAPABILITIES
1228 else:
1229 default_cuda_compute_capabilities = native_cuda_compute_capabilities
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001230
Avijit121e0162018-07-24 23:35:27 -07001231 ask_cuda_compute_capabilities = (
1232 'Please specify a list of comma-separated '
1233 'Cuda compute capabilities you want to '
1234 'build with.\nYou can find the compute '
1235 'capability of your device at: '
1236 'https://developer.nvidia.com/cuda-gpus.\nPlease'
1237 ' note that each additional compute '
1238 'capability significantly increases your '
1239 'build time and binary size. [Default is: %s]' %
1240 default_cuda_compute_capabilities)
1241 tf_cuda_compute_capabilities = get_from_env_or_user_or_default(
1242 environ_cp, 'TF_CUDA_COMPUTE_CAPABILITIES',
1243 ask_cuda_compute_capabilities, default_cuda_compute_capabilities)
1244 # Check whether all capabilities from the input is valid
1245 all_valid = True
1246 # Remove all whitespace characters before splitting the string
1247 # that users may insert by accident, as this will result in error
1248 tf_cuda_compute_capabilities = ''.join(
1249 tf_cuda_compute_capabilities.split())
1250 for compute_capability in tf_cuda_compute_capabilities.split(','):
1251 m = re.match('[0-9]+.[0-9]+', compute_capability)
1252 if not m:
1253 print('Invalid compute capability: ' % compute_capability)
1254 all_valid = False
1255 else:
1256 ver = int(m.group(0).split('.')[0])
1257 if ver < 3:
1258 print(
1259 'Only compute capabilities 3.0 or higher are supported.'
1260 )
1261 all_valid = False
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001262
Avijit121e0162018-07-24 23:35:27 -07001263 if all_valid:
1264 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001265
Avijit121e0162018-07-24 23:35:27 -07001266 # Reset and Retry
1267 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001268
Avijit121e0162018-07-24 23:35:27 -07001269 # Set TF_CUDA_COMPUTE_CAPABILITIES
1270 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = tf_cuda_compute_capabilities
1271 write_action_env_to_bazelrc('TF_CUDA_COMPUTE_CAPABILITIES',
1272 tf_cuda_compute_capabilities)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001273
1274
1275def set_other_cuda_vars(environ_cp):
Avijit121e0162018-07-24 23:35:27 -07001276 """Set other CUDA related variables."""
1277 # If CUDA is enabled, always use GPU during build and test.
1278 if environ_cp.get('TF_CUDA_CLANG') == '1':
1279 write_to_bazelrc('build --config=cuda_clang')
1280 write_to_bazelrc('test --config=cuda_clang')
1281 else:
1282 write_to_bazelrc('build --config=cuda')
1283 write_to_bazelrc('test --config=cuda')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001284
1285
1286def set_host_cxx_compiler(environ_cp):
Avijit121e0162018-07-24 23:35:27 -07001287 """Set HOST_CXX_COMPILER."""
1288 default_cxx_host_compiler = which('g++') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001289
Avijit121e0162018-07-24 23:35:27 -07001290 host_cxx_compiler = prompt_loop_or_load_from_env(
1291 environ_cp,
1292 var_name='HOST_CXX_COMPILER',
1293 var_default=default_cxx_host_compiler,
1294 ask_for_var=('Please specify which C++ compiler should be used as the '
1295 'host C++ compiler.'),
1296 check_success=os.path.exists,
1297 error_msg='Invalid C++ compiler path. %s cannot be found.',
1298 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001299
Avijit121e0162018-07-24 23:35:27 -07001300 write_action_env_to_bazelrc('HOST_CXX_COMPILER', host_cxx_compiler)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001301
1302
1303def set_host_c_compiler(environ_cp):
Avijit121e0162018-07-24 23:35:27 -07001304 """Set HOST_C_COMPILER."""
1305 default_c_host_compiler = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001306
Avijit121e0162018-07-24 23:35:27 -07001307 host_c_compiler = prompt_loop_or_load_from_env(
1308 environ_cp,
1309 var_name='HOST_C_COMPILER',
1310 var_default=default_c_host_compiler,
1311 ask_for_var=(
1312 'Please specify which C compiler should be used as the host '
1313 'C compiler.'),
1314 check_success=os.path.exists,
1315 error_msg='Invalid C compiler path. %s cannot be found.',
1316 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001317
Avijit121e0162018-07-24 23:35:27 -07001318 write_action_env_to_bazelrc('HOST_C_COMPILER', host_c_compiler)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001319
1320
1321def set_computecpp_toolkit_path(environ_cp):
Avijit121e0162018-07-24 23:35:27 -07001322 """Set COMPUTECPP_TOOLKIT_PATH."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001323
Avijit121e0162018-07-24 23:35:27 -07001324 def toolkit_exists(toolkit_path):
1325 """Check if a computecpp toolkit path is valid."""
1326 if is_linux():
1327 sycl_rt_lib_path = 'lib/libComputeCpp.so'
1328 else:
1329 sycl_rt_lib_path = ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001330
Avijit121e0162018-07-24 23:35:27 -07001331 sycl_rt_lib_path_full = os.path.join(toolkit_path, sycl_rt_lib_path)
1332 exists = os.path.exists(sycl_rt_lib_path_full)
1333 if not exists:
1334 print('Invalid SYCL %s library path. %s cannot be found' %
1335 (_TF_OPENCL_VERSION, sycl_rt_lib_path_full))
1336 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001337
Avijit121e0162018-07-24 23:35:27 -07001338 computecpp_toolkit_path = prompt_loop_or_load_from_env(
1339 environ_cp,
1340 var_name='COMPUTECPP_TOOLKIT_PATH',
1341 var_default=_DEFAULT_COMPUTECPP_TOOLKIT_PATH,
1342 ask_for_var=(
1343 'Please specify the location where ComputeCpp for SYCL %s is '
1344 'installed.' % _TF_OPENCL_VERSION),
1345 check_success=toolkit_exists,
1346 error_msg='Invalid SYCL compiler path. %s cannot be found.',
1347 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001348
Avijit121e0162018-07-24 23:35:27 -07001349 write_action_env_to_bazelrc('COMPUTECPP_TOOLKIT_PATH',
1350 computecpp_toolkit_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001351
Michael Cased31531a2018-01-05 14:09:41 -08001352
Dandelion Man?90e42f32017-12-15 18:15:07 -08001353def set_trisycl_include_dir(environ_cp):
Avijit121e0162018-07-24 23:35:27 -07001354 """Set TRISYCL_INCLUDE_DIR."""
Frank Chenc4ef9272018-01-10 11:36:52 -08001355
Avijit121e0162018-07-24 23:35:27 -07001356 ask_trisycl_include_dir = ('Please specify the location of the triSYCL '
1357 'include directory. (Use --config=sycl_trisycl '
1358 'when building with Bazel) '
1359 '[Default is %s]: ') % (
1360 _DEFAULT_TRISYCL_INCLUDE_DIR)
Frank Chenc4ef9272018-01-10 11:36:52 -08001361
Avijit121e0162018-07-24 23:35:27 -07001362 while True:
1363 trisycl_include_dir = get_from_env_or_user_or_default(
1364 environ_cp, 'TRISYCL_INCLUDE_DIR', ask_trisycl_include_dir,
1365 _DEFAULT_TRISYCL_INCLUDE_DIR)
1366 if os.path.exists(trisycl_include_dir):
1367 break
Dandelion Man?90e42f32017-12-15 18:15:07 -08001368
Avijit121e0162018-07-24 23:35:27 -07001369 print('Invalid triSYCL include directory, %s cannot be found' %
1370 (trisycl_include_dir))
Dandelion Man?90e42f32017-12-15 18:15:07 -08001371
Avijit121e0162018-07-24 23:35:27 -07001372 # Set TRISYCL_INCLUDE_DIR
1373 environ_cp['TRISYCL_INCLUDE_DIR'] = trisycl_include_dir
1374 write_action_env_to_bazelrc('TRISYCL_INCLUDE_DIR', trisycl_include_dir)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001375
Yifei Fengb1d8c592017-11-22 13:42:21 -08001376
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001377def set_mpi_home(environ_cp):
Avijit121e0162018-07-24 23:35:27 -07001378 """Set MPI_HOME."""
Austin Anderson6afface2017-12-05 11:59:17 -08001379
Avijit121e0162018-07-24 23:35:27 -07001380 default_mpi_home = which('mpirun') or which('mpiexec') or ''
1381 default_mpi_home = os.path.dirname(os.path.dirname(default_mpi_home))
Jonathan Hseu008910f2017-08-25 14:01:05 -07001382
Avijit121e0162018-07-24 23:35:27 -07001383 def valid_mpi_path(mpi_home):
1384 exists = (os.path.exists(os.path.join(mpi_home, 'include'))
1385 and os.path.exists(os.path.join(mpi_home, 'lib')))
1386 if not exists:
1387 print('Invalid path to the MPI Toolkit. %s or %s cannot be found' %
1388 (os.path.join(mpi_home, 'include'),
1389 os.path.exists(os.path.join(mpi_home, 'lib'))))
1390 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001391
Avijit121e0162018-07-24 23:35:27 -07001392 _ = prompt_loop_or_load_from_env(
1393 environ_cp,
1394 var_name='MPI_HOME',
1395 var_default=default_mpi_home,
1396 ask_for_var='Please specify the MPI toolkit folder.',
1397 check_success=valid_mpi_path,
1398 error_msg='',
1399 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001400
1401
1402def set_other_mpi_vars(environ_cp):
Avijit121e0162018-07-24 23:35:27 -07001403 """Set other MPI related variables."""
1404 # Link the MPI header files
1405 mpi_home = environ_cp.get('MPI_HOME')
1406 symlink_force('%s/include/mpi.h' % mpi_home, 'third_party/mpi/mpi.h')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001407
Avijit121e0162018-07-24 23:35:27 -07001408 # Determine if we use OpenMPI or MVAPICH, these require different header files
1409 # to be included here to make bazel dependency checker happy
1410 if os.path.exists(
1411 os.path.join(mpi_home, 'include/mpi_portable_platform.h')):
1412 symlink_force(
1413 os.path.join(mpi_home, 'include/mpi_portable_platform.h'),
1414 'third_party/mpi/mpi_portable_platform.h')
1415 # TODO(gunan): avoid editing files in configure
1416 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=False',
1417 'MPI_LIB_IS_OPENMPI=True')
1418 else:
1419 # MVAPICH / MPICH
1420 symlink_force(
1421 os.path.join(mpi_home, 'include/mpio.h'), 'third_party/mpi/mpio.h')
1422 symlink_force(
1423 os.path.join(mpi_home, 'include/mpicxx.h'),
1424 'third_party/mpi/mpicxx.h')
1425 # TODO(gunan): avoid editing files in configure
1426 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=True',
1427 'MPI_LIB_IS_OPENMPI=False')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001428
Avijit121e0162018-07-24 23:35:27 -07001429 if os.path.exists(os.path.join(mpi_home, 'lib/libmpi.so')):
1430 symlink_force(
1431 os.path.join(mpi_home, 'lib/libmpi.so'),
1432 'third_party/mpi/libmpi.so')
1433 else:
1434 raise ValueError(
1435 'Cannot find the MPI library file in %s/lib' % mpi_home)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001436
1437
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001438def set_grpc_build_flags():
Avijit121e0162018-07-24 23:35:27 -07001439 write_to_bazelrc('build --define grpc_no_ares=true')
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001440
Michael Cased31531a2018-01-05 14:09:41 -08001441
Akshay Modi6070ae02018-06-18 21:00:34 -07001442def set_build_strip_flag():
Avijit121e0162018-07-24 23:35:27 -07001443 write_to_bazelrc('build --strip=always')
Akshay Modi6070ae02018-06-18 21:00:34 -07001444
1445
Dandelion Man?90e42f32017-12-15 18:15:07 -08001446def set_windows_build_flags():
Avijit121e0162018-07-24 23:35:27 -07001447 if is_windows():
1448 # The non-monolithic build is not supported yet
1449 write_to_bazelrc('build --config monolithic')
1450 # Suppress warning messages
1451 write_to_bazelrc('build --copt=-w --host_copt=-w')
1452 # Output more verbose information when something goes wrong
1453 write_to_bazelrc('build --verbose_failures')
Dandelion Man?90e42f32017-12-15 18:15:07 -08001454
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001455
Michael Cased31531a2018-01-05 14:09:41 -08001456def config_info_line(name, help_text):
Avijit121e0162018-07-24 23:35:27 -07001457 """Helper function to print formatted help text for Bazel config options."""
1458 print('\t--config=%-12s\t# %s' % (name, help_text))
Michael Cased31531a2018-01-05 14:09:41 -08001459
1460
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001461def main():
Avijit121e0162018-07-24 23:35:27 -07001462 parser = argparse.ArgumentParser()
1463 parser.add_argument(
1464 "--workspace",
1465 type=str,
1466 default=_TF_WORKSPACE_ROOT,
1467 help="The absolute path to your active Bazel workspace.")
1468 args = parser.parse_args()
Shanqing Cai71445712018-03-12 19:33:52 -07001469
Avijit121e0162018-07-24 23:35:27 -07001470 # Make a copy of os.environ to be clear when functions and getting and setting
1471 # environment variables.
1472 environ_cp = dict(os.environ)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001473
Avijit121e0162018-07-24 23:35:27 -07001474 check_bazel_version('0.10.0')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001475
Avijit121e0162018-07-24 23:35:27 -07001476 reset_tf_configure_bazelrc(args.workspace)
1477 cleanup_makefile()
1478 setup_python(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001479
Avijit121e0162018-07-24 23:35:27 -07001480 if is_windows():
1481 environ_cp['TF_NEED_AWS'] = '0'
1482 environ_cp['TF_NEED_GCP'] = '0'
1483 environ_cp['TF_NEED_HDFS'] = '0'
1484 environ_cp['TF_NEED_JEMALLOC'] = '0'
1485 environ_cp['TF_NEED_KAFKA'] = '0'
1486 environ_cp['TF_NEED_OPENCL_SYCL'] = '0'
1487 environ_cp['TF_NEED_COMPUTECPP'] = '0'
1488 environ_cp['TF_NEED_OPENCL'] = '0'
1489 environ_cp['TF_CUDA_CLANG'] = '0'
1490 environ_cp['TF_NEED_TENSORRT'] = '0'
1491 # TODO(ibiryukov): Investigate using clang as a cpu or cuda compiler on
1492 # Windows.
1493 environ_cp['TF_DOWNLOAD_CLANG'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001494
Avijit121e0162018-07-24 23:35:27 -07001495 if is_macos():
1496 environ_cp['TF_NEED_JEMALLOC'] = '0'
1497 environ_cp['TF_NEED_TENSORRT'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001498
Avijit121e0162018-07-24 23:35:27 -07001499 set_build_var(environ_cp, 'TF_NEED_JEMALLOC', 'jemalloc as malloc',
1500 'with_jemalloc', True)
1501 set_build_var(environ_cp, 'TF_NEED_GCP', 'Google Cloud Platform',
1502 'with_gcp_support', True, 'gcp')
1503 set_build_var(environ_cp, 'TF_NEED_HDFS', 'Hadoop File System',
1504 'with_hdfs_support', True, 'hdfs')
1505 set_build_var(environ_cp, 'TF_NEED_AWS', 'Amazon AWS Platform',
1506 'with_aws_support', True, 'aws')
1507 set_build_var(environ_cp, 'TF_NEED_KAFKA', 'Apache Kafka Platform',
1508 'with_kafka_support', True, 'kafka')
1509 set_build_var(environ_cp, 'TF_ENABLE_XLA', 'XLA JIT', 'with_xla_support',
1510 False, 'xla')
1511 set_build_var(environ_cp, 'TF_NEED_GDR', 'GDR', 'with_gdr_support', False,
1512 'gdr')
1513 set_build_var(environ_cp, 'TF_NEED_VERBS', 'VERBS', 'with_verbs_support',
1514 False, 'verbs')
1515 set_build_var(environ_cp, 'TF_NEED_NGRAPH', 'nGraph',
1516 'with_ngraph_support', False, 'ngraph')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001517
Avijit121e0162018-07-24 23:35:27 -07001518 set_action_env_var(environ_cp, 'TF_NEED_OPENCL_SYCL', 'OpenCL SYCL', False)
1519 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
1520 set_host_cxx_compiler(environ_cp)
1521 set_host_c_compiler(environ_cp)
1522 set_action_env_var(environ_cp, 'TF_NEED_COMPUTECPP', 'ComputeCPP',
1523 True)
1524 if environ_cp.get('TF_NEED_COMPUTECPP') == '1':
1525 set_computecpp_toolkit_path(environ_cp)
1526 else:
1527 set_trisycl_include_dir(environ_cp)
1528
1529 set_action_env_var(environ_cp, 'TF_NEED_CUDA', 'CUDA', False)
1530 if (environ_cp.get('TF_NEED_CUDA') == '1'
1531 and 'TF_CUDA_CONFIG_REPO' not in environ_cp):
1532 set_tf_cuda_version(environ_cp)
1533 set_tf_cudnn_version(environ_cp)
1534 if is_linux():
1535 set_tf_tensorrt_install_path(environ_cp)
1536 set_tf_nccl_install_path(environ_cp)
1537
1538 set_tf_cuda_compute_capabilities(environ_cp)
1539 if 'LD_LIBRARY_PATH' in environ_cp and environ_cp.get(
1540 'LD_LIBRARY_PATH') != '1':
1541 write_action_env_to_bazelrc('LD_LIBRARY_PATH',
1542 environ_cp.get('LD_LIBRARY_PATH'))
1543
1544 set_tf_cuda_clang(environ_cp)
1545 if environ_cp.get('TF_CUDA_CLANG') == '1':
1546 # Ask whether we should download the clang toolchain.
1547 set_tf_download_clang(environ_cp)
1548 if environ_cp.get('TF_DOWNLOAD_CLANG') != '1':
1549 # Set up which clang we should use as the cuda / host compiler.
1550 set_clang_cuda_compiler_path(environ_cp)
1551 else:
1552 # Set up which gcc nvcc should use as the host compiler
1553 # No need to set this on Windows
1554 if not is_windows():
1555 set_gcc_host_compiler_path(environ_cp)
1556 set_other_cuda_vars(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001557 else:
Avijit121e0162018-07-24 23:35:27 -07001558 # CUDA not required. Ask whether we should download the clang toolchain and
1559 # use it for the CPU build.
1560 set_tf_download_clang(environ_cp)
1561 if environ_cp.get('TF_DOWNLOAD_CLANG') == '1':
1562 write_to_bazelrc('build --config=download_clang')
1563 write_to_bazelrc('test --config=download_clang')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001564
Avijit121e0162018-07-24 23:35:27 -07001565 set_build_var(environ_cp, 'TF_NEED_MPI', 'MPI', 'with_mpi_support', False)
1566 if environ_cp.get('TF_NEED_MPI') == '1':
1567 set_mpi_home(environ_cp)
1568 set_other_mpi_vars(environ_cp)
Michael Case0073d132018-04-11 09:34:44 -07001569
Avijit121e0162018-07-24 23:35:27 -07001570 set_grpc_build_flags()
1571 set_cc_opt_flags(environ_cp)
1572 set_build_strip_flag()
1573 set_windows_build_flags()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001574
Avijit121e0162018-07-24 23:35:27 -07001575 if get_var(environ_cp, 'TF_SET_ANDROID_WORKSPACE', 'android workspace',
1576 False,
1577 ('Would you like to interactively configure ./WORKSPACE for '
1578 'Android builds?'), 'Searching for NDK and SDK installations.',
1579 'Not configuring the WORKSPACE for Android builds.'):
1580 create_android_ndk_rule(environ_cp)
1581 create_android_sdk_rule(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001582
Avijit121e0162018-07-24 23:35:27 -07001583 print('Preconfigured Bazel build configs. You can use any of the below by '
1584 'adding "--config=<>" to your build command. See tools/bazel.rc for '
1585 'more details.')
1586 config_info_line('mkl', 'Build with MKL support.')
1587 config_info_line('monolithic',
1588 'Config for mostly static monolithic build.')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001589
Austin Anderson6afface2017-12-05 11:59:17 -08001590
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001591if __name__ == '__main__':
Avijit121e0162018-07-24 23:35:27 -07001592 main()