blob: 65b46229955261abf923a7f2d41552ce249094a0 [file] [log] [blame]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ==============================================================================
15"""configure script to get build parameters from user."""
16
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import print_function
20
Shanqing Cai71445712018-03-12 19:33:52 -070021import argparse
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070022import errno
23import os
24import platform
25import re
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070026import subprocess
27import sys
28
Andrew Sellec9885ea2017-11-06 09:37:03 -080029# pylint: disable=g-import-not-at-top
Jonathan Hseu008910f2017-08-25 14:01:05 -070030try:
31 from shutil import which
32except ImportError:
33 from distutils.spawn import find_executable as which
Andrew Sellec9885ea2017-11-06 09:37:03 -080034# pylint: enable=g-import-not-at-top
Jonathan Hseu008910f2017-08-25 14:01:05 -070035
Dandelion Man?90e42f32017-12-15 18:15:07 -080036_DEFAULT_CUDA_VERSION = '9.0'
37_DEFAULT_CUDNN_VERSION = '7'
Smit Hinsufe7d1d92018-07-14 13:16:58 -070038_DEFAULT_CUDA_COMPUTE_CAPABILITIES = '3.5,7.0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070039_DEFAULT_CUDA_PATH = '/usr/local/cuda'
40_DEFAULT_CUDA_PATH_LINUX = '/opt/cuda'
41_DEFAULT_CUDA_PATH_WIN = ('C:/Program Files/NVIDIA GPU Computing '
42 'Toolkit/CUDA/v%s' % _DEFAULT_CUDA_VERSION)
43_TF_OPENCL_VERSION = '1.2'
44_DEFAULT_COMPUTECPP_TOOLKIT_PATH = '/usr/local/computecpp'
Yifei Fengb1d8c592017-11-22 13:42:21 -080045_DEFAULT_TRISYCL_INCLUDE_DIR = '/usr/local/triSYCL/include'
A. Unique TensorFlowerd340f472018-08-30 14:00:41 -070046_SUPPORTED_ANDROID_NDK_VERSIONS = [10, 11, 12, 13, 14, 15, 16]
Austin Anderson6afface2017-12-05 11:59:17 -080047
48_DEFAULT_PROMPT_ASK_ATTEMPTS = 10
49
Shanqing Cai71445712018-03-12 19:33:52 -070050_TF_BAZELRC_FILENAME = '.tf_configure.bazelrc'
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -070051_TF_WORKSPACE_ROOT = ''
52_TF_BAZELRC = ''
Shanqing Cai71445712018-03-12 19:33:52 -070053
Jason Furmanek7c234152018-09-26 04:44:12 +000054NCCL_LIB_PATHS = [
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -070055 'lib64/', 'lib/powerpc64le-linux-gnu/', 'lib/x86_64-linux-gnu/', ''
Jason Furmanek7c234152018-09-26 04:44:12 +000056]
Austin Anderson6afface2017-12-05 11:59:17 -080057
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -070058if platform.machine() == 'ppc64le':
59 _DEFAULT_TENSORRT_PATH_LINUX = '/usr/lib/powerpc64le-linux-gnu/'
60else:
61 _DEFAULT_TENSORRT_PATH_LINUX = '/usr/lib/%s-linux-gnu' % platform.machine()
62
Austin Anderson6afface2017-12-05 11:59:17 -080063
64class UserInputError(Exception):
65 pass
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070066
67
68def is_windows():
69 return platform.system() == 'Windows'
70
71
72def is_linux():
73 return platform.system() == 'Linux'
74
75
76def is_macos():
77 return platform.system() == 'Darwin'
78
79
80def is_ppc64le():
81 return platform.machine() == 'ppc64le'
82
83
Jonathan Hseu008910f2017-08-25 14:01:05 -070084def is_cygwin():
85 return platform.system().startswith('CYGWIN_NT')
86
87
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070088def get_input(question):
89 try:
90 try:
91 answer = raw_input(question)
92 except NameError:
93 answer = input(question) # pylint: disable=bad-builtin
94 except EOFError:
95 answer = ''
96 return answer
97
98
99def symlink_force(target, link_name):
100 """Force symlink, equivalent of 'ln -sf'.
101
102 Args:
103 target: items to link to.
104 link_name: name of the link.
105 """
106 try:
107 os.symlink(target, link_name)
108 except OSError as e:
109 if e.errno == errno.EEXIST:
110 os.remove(link_name)
111 os.symlink(target, link_name)
112 else:
113 raise e
114
115
116def sed_in_place(filename, old, new):
117 """Replace old string with new string in file.
118
119 Args:
120 filename: string for filename.
121 old: string to replace.
122 new: new string to replace to.
123 """
124 with open(filename, 'r') as f:
125 filedata = f.read()
126 newdata = filedata.replace(old, new)
127 with open(filename, 'w') as f:
128 f.write(newdata)
129
130
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700131def write_to_bazelrc(line):
132 with open(_TF_BAZELRC, 'a') as f:
133 f.write(line + '\n')
134
135
136def write_action_env_to_bazelrc(var_name, var):
137 write_to_bazelrc('build --action_env %s="%s"' % (var_name, str(var)))
138
139
Jonathan Hseu008910f2017-08-25 14:01:05 -0700140def run_shell(cmd, allow_non_zero=False):
141 if allow_non_zero:
142 try:
143 output = subprocess.check_output(cmd)
144 except subprocess.CalledProcessError as e:
145 output = e.output
146 else:
147 output = subprocess.check_output(cmd)
148 return output.decode('UTF-8').strip()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700149
150
151def cygpath(path):
152 """Convert path from posix to windows."""
Martin Wicked57572e2017-09-02 19:21:45 -0700153 return os.path.abspath(path).replace('\\', '/')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700154
155
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700156def get_python_path(environ_cp, python_bin_path):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700157 """Get the python site package paths."""
158 python_paths = []
159 if environ_cp.get('PYTHONPATH'):
160 python_paths = environ_cp.get('PYTHONPATH').split(':')
161 try:
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700162 library_paths = run_shell([
163 python_bin_path, '-c',
164 'import site; print("\\n".join(site.getsitepackages()))'
165 ]).split('\n')
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700166 except subprocess.CalledProcessError:
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700167 library_paths = [
168 run_shell([
169 python_bin_path, '-c',
170 'from distutils.sysconfig import get_python_lib;'
171 'print(get_python_lib())'
172 ])
173 ]
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700174
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700175 all_paths = set(python_paths + library_paths)
176
177 paths = []
178 for path in all_paths:
179 if os.path.isdir(path):
180 paths.append(path)
181 return paths
182
183
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700184def get_python_major_version(python_bin_path):
185 """Get the python major version."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700186 return run_shell([python_bin_path, '-c', 'import sys; print(sys.version[0])'])
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700187
188
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700189def setup_python(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700190 """Setup python related env variables."""
191 # Get PYTHON_BIN_PATH, default is the current running python.
192 default_python_bin_path = sys.executable
193 ask_python_bin_path = ('Please specify the location of python. [Default is '
194 '%s]: ') % default_python_bin_path
195 while True:
196 python_bin_path = get_from_env_or_user_or_default(
197 environ_cp, 'PYTHON_BIN_PATH', ask_python_bin_path,
198 default_python_bin_path)
199 # Check if the path is valid
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700200 if os.path.isfile(python_bin_path) and os.access(python_bin_path, os.X_OK):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700201 break
202 elif not os.path.exists(python_bin_path):
203 print('Invalid python path: %s cannot be found.' % python_bin_path)
204 else:
205 print('%s is not executable. Is it the python binary?' % python_bin_path)
206 environ_cp['PYTHON_BIN_PATH'] = ''
207
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700208 # Convert python path to Windows style before checking lib and version
Martin Wicked57572e2017-09-02 19:21:45 -0700209 if is_windows() or is_cygwin():
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700210 python_bin_path = cygpath(python_bin_path)
211
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700212 # Get PYTHON_LIB_PATH
213 python_lib_path = environ_cp.get('PYTHON_LIB_PATH')
214 if not python_lib_path:
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700215 python_lib_paths = get_python_path(environ_cp, python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700216 if environ_cp.get('USE_DEFAULT_PYTHON_LIB_PATH') == '1':
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700217 python_lib_path = python_lib_paths[0]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700218 else:
Jonathan Hseu008910f2017-08-25 14:01:05 -0700219 print('Found possible Python library paths:\n %s' %
220 '\n '.join(python_lib_paths))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700221 default_python_lib_path = python_lib_paths[0]
222 python_lib_path = get_input(
Jonathan Hseu008910f2017-08-25 14:01:05 -0700223 'Please input the desired Python library path to use. '
224 'Default is [%s]\n' % python_lib_paths[0])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700225 if not python_lib_path:
226 python_lib_path = default_python_lib_path
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700227 environ_cp['PYTHON_LIB_PATH'] = python_lib_path
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700228
TensorFlower Gardener61a87202018-10-01 12:25:39 -0700229 _ = get_python_major_version(python_bin_path)
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700230
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700231 # Convert python path to Windows style before writing into bazel.rc
Martin Wicked57572e2017-09-02 19:21:45 -0700232 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700233 python_lib_path = cygpath(python_lib_path)
234
235 # Set-up env variables used by python_configure.bzl
236 write_action_env_to_bazelrc('PYTHON_BIN_PATH', python_bin_path)
237 write_action_env_to_bazelrc('PYTHON_LIB_PATH', python_lib_path)
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700238 write_to_bazelrc('build --python_path=\"%s"' % python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700239 environ_cp['PYTHON_BIN_PATH'] = python_bin_path
240
241 # Write tools/python_bin_path.sh
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700242 with open(
243 os.path.join(_TF_WORKSPACE_ROOT, 'tools', 'python_bin_path.sh'),
244 'w') as f:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700245 f.write('export PYTHON_BIN_PATH="%s"' % python_bin_path)
246
247
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -0700248def reset_tf_configure_bazelrc():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700249 """Reset file that contains customized config settings."""
250 open(_TF_BAZELRC, 'w').close()
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -0700251 bazelrc_path = os.path.join(_TF_WORKSPACE_ROOT, '.bazelrc')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700252
Shanqing Cai71445712018-03-12 19:33:52 -0700253 data = []
254 if os.path.exists(bazelrc_path):
255 with open(bazelrc_path, 'r') as f:
256 data = f.read().splitlines()
257 with open(bazelrc_path, 'w') as f:
258 for l in data:
259 if _TF_BAZELRC_FILENAME in l:
260 continue
261 f.write('%s\n' % l)
Jason Zamand3f6b722018-08-04 14:28:02 +0800262 f.write('import %%workspace%%/%s\n' % _TF_BAZELRC_FILENAME)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700263
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700264def cleanup_makefile():
265 """Delete any leftover BUILD files from the Makefile build.
266
267 These files could interfere with Bazel parsing.
268 """
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700269 makefile_download_dir = os.path.join(_TF_WORKSPACE_ROOT, 'tensorflow',
270 'contrib', 'makefile', 'downloads')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700271 if os.path.isdir(makefile_download_dir):
272 for root, _, filenames in os.walk(makefile_download_dir):
273 for f in filenames:
274 if f.endswith('BUILD'):
275 os.remove(os.path.join(root, f))
276
277
278def get_var(environ_cp,
279 var_name,
280 query_item,
281 enabled_by_default,
282 question=None,
283 yes_reply=None,
284 no_reply=None):
285 """Get boolean input from user.
286
287 If var_name is not set in env, ask user to enable query_item or not. If the
288 response is empty, use the default.
289
290 Args:
291 environ_cp: copy of the os.environ.
292 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
293 query_item: string for feature related to the variable, e.g. "Hadoop File
294 System".
295 enabled_by_default: boolean for default behavior.
296 question: optional string for how to ask for user input.
Michael Cased90054e2018-02-07 14:36:00 -0800297 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700298 no_reply: optional string for reply when feature is disabled.
299
300 Returns:
301 boolean value of the variable.
Frank Chenc4ef9272018-01-10 11:36:52 -0800302
303 Raises:
304 UserInputError: if an environment variable is set, but it cannot be
305 interpreted as a boolean indicator, assume that the user has made a
306 scripting error, and will continue to provide invalid input.
307 Raise the error to avoid infinitely looping.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700308 """
309 if not question:
310 question = 'Do you wish to build TensorFlow with %s support?' % query_item
311 if not yes_reply:
312 yes_reply = '%s support will be enabled for TensorFlow.' % query_item
313 if not no_reply:
314 no_reply = 'No %s' % yes_reply
315
316 yes_reply += '\n'
317 no_reply += '\n'
318
319 if enabled_by_default:
320 question += ' [Y/n]: '
321 else:
322 question += ' [y/N]: '
323
324 var = environ_cp.get(var_name)
Frank Chenc4ef9272018-01-10 11:36:52 -0800325 if var is not None:
326 var_content = var.strip().lower()
327 true_strings = ('1', 't', 'true', 'y', 'yes')
328 false_strings = ('0', 'f', 'false', 'n', 'no')
329 if var_content in true_strings:
330 var = True
331 elif var_content in false_strings:
332 var = False
333 else:
334 raise UserInputError(
335 'Environment variable %s must be set as a boolean indicator.\n'
336 'The following are accepted as TRUE : %s.\n'
337 'The following are accepted as FALSE: %s.\n'
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700338 'Current value is %s.' % (var_name, ', '.join(true_strings),
339 ', '.join(false_strings), var))
Frank Chenc4ef9272018-01-10 11:36:52 -0800340
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700341 while var is None:
342 user_input_origin = get_input(question)
343 user_input = user_input_origin.strip().lower()
344 if user_input == 'y':
345 print(yes_reply)
346 var = True
347 elif user_input == 'n':
348 print(no_reply)
349 var = False
350 elif not user_input:
351 if enabled_by_default:
352 print(yes_reply)
353 var = True
354 else:
355 print(no_reply)
356 var = False
357 else:
358 print('Invalid selection: %s' % user_input_origin)
359 return var
360
361
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700362def set_build_var(environ_cp,
363 var_name,
364 query_item,
365 option_name,
366 enabled_by_default,
367 bazel_config_name=None):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700368 """Set if query_item will be enabled for the build.
369
370 Ask user if query_item will be enabled. Default is used if no input is given.
371 Set subprocess environment variable and write to .bazelrc if enabled.
372
373 Args:
374 environ_cp: copy of the os.environ.
375 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
376 query_item: string for feature related to the variable, e.g. "Hadoop File
377 System".
378 option_name: string for option to define in .bazelrc.
379 enabled_by_default: boolean for default behavior.
Michael Case98850a52017-09-14 13:35:57 -0700380 bazel_config_name: Name for Bazel --config argument to enable build feature.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700381 """
382
383 var = str(int(get_var(environ_cp, var_name, query_item, enabled_by_default)))
384 environ_cp[var_name] = var
385 if var == '1':
386 write_to_bazelrc('build --define %s=true' % option_name)
Michael Case98850a52017-09-14 13:35:57 -0700387 elif bazel_config_name is not None:
388 # TODO(mikecase): Migrate all users of configure.py to use --config Bazel
389 # options and not to set build configs through environment variables.
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700390 write_to_bazelrc(
391 'build:%s --define %s=true' % (bazel_config_name, option_name))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700392
393
394def set_action_env_var(environ_cp,
395 var_name,
396 query_item,
397 enabled_by_default,
398 question=None,
399 yes_reply=None,
400 no_reply=None):
401 """Set boolean action_env variable.
402
403 Ask user if query_item will be enabled. Default is used if no input is given.
404 Set environment variable and write to .bazelrc.
405
406 Args:
407 environ_cp: copy of the os.environ.
408 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
409 query_item: string for feature related to the variable, e.g. "Hadoop File
410 System".
411 enabled_by_default: boolean for default behavior.
412 question: optional string for how to ask for user input.
Michael Cased90054e2018-02-07 14:36:00 -0800413 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700414 no_reply: optional string for reply when feature is disabled.
415 """
416 var = int(
417 get_var(environ_cp, var_name, query_item, enabled_by_default, question,
418 yes_reply, no_reply))
419
420 write_action_env_to_bazelrc(var_name, var)
421 environ_cp[var_name] = str(var)
422
423
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700424def convert_version_to_int(version):
425 """Convert a version number to a integer that can be used to compare.
426
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700427 Version strings of the form X.YZ and X.Y.Z-xxxxx are supported. The
428 'xxxxx' part, for instance 'homebrew' on OS/X, is ignored.
429
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700430 Args:
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700431 version: a version to be converted
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700432
433 Returns:
434 An integer if converted successfully, otherwise return None.
435 """
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700436 version = version.split('-')[0]
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700437 version_segments = version.split('.')
438 for seg in version_segments:
439 if not seg.isdigit():
440 return None
441
442 version_str = ''.join(['%03d' % int(seg) for seg in version_segments])
443 return int(version_str)
444
445
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700446def check_bazel_version(min_version):
Yifei Fengdce9a492018-02-22 14:24:57 -0800447 """Check installed bazel version is at least min_version.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700448
449 Args:
450 min_version: string for minimum bazel version.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700451
452 Returns:
453 The bazel version detected.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700454 """
Jonathan Hseu008910f2017-08-25 14:01:05 -0700455 if which('bazel') is None:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700456 print('Cannot find bazel. Please install bazel.')
457 sys.exit(0)
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700458 curr_version = run_shell(
459 ['bazel', '--batch', '--bazelrc=/dev/null', 'version'])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700460
461 for line in curr_version.split('\n'):
462 if 'Build label: ' in line:
463 curr_version = line.split('Build label: ')[1]
464 break
465
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700466 min_version_int = convert_version_to_int(min_version)
467 curr_version_int = convert_version_to_int(curr_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700468
469 # Check if current bazel version can be detected properly.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700470 if not curr_version_int:
471 print('WARNING: current bazel installation is not a release version.')
472 print('Make sure you are running at least bazel %s' % min_version)
473 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700474
Michael Cased94271a2017-08-22 17:26:52 -0700475 print('You have bazel %s installed.' % curr_version)
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700476
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700477 if curr_version_int < min_version_int:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700478 print('Please upgrade your bazel installation to version %s or higher to '
479 'build TensorFlow!' % min_version)
480 sys.exit(0)
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700481 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700482
483
484def set_cc_opt_flags(environ_cp):
485 """Set up architecture-dependent optimization flags.
486
487 Also append CC optimization flags to bazel.rc..
488
489 Args:
490 environ_cp: copy of the os.environ.
491 """
492 if is_ppc64le():
493 # gcc on ppc64le does not support -march, use mcpu instead
494 default_cc_opt_flags = '-mcpu=native'
A. Unique TensorFlower1bba94a2018-04-04 15:45:20 -0700495 elif is_windows():
496 default_cc_opt_flags = '/arch:AVX'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700497 else:
498 default_cc_opt_flags = '-march=native'
499 question = ('Please specify optimization flags to use during compilation when'
500 ' bazel option "--config=opt" is specified [Default is %s]: '
501 ) % default_cc_opt_flags
502 cc_opt_flags = get_from_env_or_user_or_default(environ_cp, 'CC_OPT_FLAGS',
503 question, default_cc_opt_flags)
504 for opt in cc_opt_flags.split():
Michael Case00177422017-11-10 13:14:03 -0800505 write_to_bazelrc('build:opt --copt=%s' % opt)
506 # It should be safe on the same build host.
A. Unique TensorFlower1bba94a2018-04-04 15:45:20 -0700507 if not is_ppc64le() and not is_windows():
Shanqing Cai71445712018-03-12 19:33:52 -0700508 write_to_bazelrc('build:opt --host_copt=-march=native')
Michael Casebb3355d2017-11-09 08:46:31 -0800509 write_to_bazelrc('build:opt --define with_default_optimizations=true')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700510
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700511
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700512def set_tf_cuda_clang(environ_cp):
513 """set TF_CUDA_CLANG action_env.
514
515 Args:
516 environ_cp: copy of the os.environ.
517 """
518 question = 'Do you want to use clang as CUDA compiler?'
519 yes_reply = 'Clang will be used as CUDA compiler.'
520 no_reply = 'nvcc will be used as CUDA compiler.'
521 set_action_env_var(
522 environ_cp,
523 'TF_CUDA_CLANG',
524 None,
525 False,
526 question=question,
527 yes_reply=yes_reply,
528 no_reply=no_reply)
529
530
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800531def set_tf_download_clang(environ_cp):
532 """Set TF_DOWNLOAD_CLANG action_env."""
Ilya Biryukov9e651e42018-03-22 05:33:42 -0700533 question = 'Do you wish to download a fresh release of clang? (Experimental)'
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800534 yes_reply = 'Clang will be downloaded and used to compile tensorflow.'
535 no_reply = 'Clang will not be downloaded.'
536 set_action_env_var(
537 environ_cp,
538 'TF_DOWNLOAD_CLANG',
539 None,
540 False,
541 question=question,
542 yes_reply=yes_reply,
543 no_reply=no_reply)
544
545
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700546def get_from_env_or_user_or_default(environ_cp, var_name, ask_for_var,
547 var_default):
548 """Get var_name either from env, or user or default.
549
550 If var_name has been set as environment variable, use the preset value, else
551 ask for user input. If no input is provided, the default is used.
552
553 Args:
554 environ_cp: copy of the os.environ.
555 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
556 ask_for_var: string for how to ask for user input.
557 var_default: default value string.
558
559 Returns:
560 string value for var_name
561 """
562 var = environ_cp.get(var_name)
563 if not var:
564 var = get_input(ask_for_var)
Michael Cased94271a2017-08-22 17:26:52 -0700565 print('\n')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700566 if not var:
567 var = var_default
568 return var
569
570
571def set_clang_cuda_compiler_path(environ_cp):
572 """Set CLANG_CUDA_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700573 default_clang_path = which('clang') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700574 ask_clang_path = ('Please specify which clang should be used as device and '
575 'host compiler. [Default is %s]: ') % default_clang_path
576
577 while True:
578 clang_cuda_compiler_path = get_from_env_or_user_or_default(
579 environ_cp, 'CLANG_CUDA_COMPILER_PATH', ask_clang_path,
580 default_clang_path)
581 if os.path.exists(clang_cuda_compiler_path):
582 break
583
584 # Reset and retry
585 print('Invalid clang path: %s cannot be found.' % clang_cuda_compiler_path)
586 environ_cp['CLANG_CUDA_COMPILER_PATH'] = ''
587
588 # Set CLANG_CUDA_COMPILER_PATH
589 environ_cp['CLANG_CUDA_COMPILER_PATH'] = clang_cuda_compiler_path
590 write_action_env_to_bazelrc('CLANG_CUDA_COMPILER_PATH',
591 clang_cuda_compiler_path)
592
593
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700594def prompt_loop_or_load_from_env(environ_cp,
595 var_name,
596 var_default,
597 ask_for_var,
598 check_success,
599 error_msg,
600 suppress_default_error=False,
601 n_ask_attempts=_DEFAULT_PROMPT_ASK_ATTEMPTS):
Austin Anderson6afface2017-12-05 11:59:17 -0800602 """Loop over user prompts for an ENV param until receiving a valid response.
603
604 For the env param var_name, read from the environment or verify user input
605 until receiving valid input. When done, set var_name in the environ_cp to its
606 new value.
607
608 Args:
609 environ_cp: (Dict) copy of the os.environ.
610 var_name: (String) string for name of environment variable, e.g. "TF_MYVAR".
611 var_default: (String) default value string.
612 ask_for_var: (String) string for how to ask for user input.
613 check_success: (Function) function that takes one argument and returns a
614 boolean. Should return True if the value provided is considered valid. May
615 contain a complex error message if error_msg does not provide enough
616 information. In that case, set suppress_default_error to True.
617 error_msg: (String) String with one and only one '%s'. Formatted with each
618 invalid response upon check_success(input) failure.
619 suppress_default_error: (Bool) Suppress the above error message in favor of
620 one from the check_success function.
621 n_ask_attempts: (Integer) Number of times to query for valid input before
622 raising an error and quitting.
623
624 Returns:
625 [String] The value of var_name after querying for input.
626
627 Raises:
628 UserInputError: if a query has been attempted n_ask_attempts times without
Frank Chenc4ef9272018-01-10 11:36:52 -0800629 success, assume that the user has made a scripting error, and will
630 continue to provide invalid input. Raise the error to avoid infinitely
631 looping.
Austin Anderson6afface2017-12-05 11:59:17 -0800632 """
633 default = environ_cp.get(var_name) or var_default
634 full_query = '%s [Default is %s]: ' % (
635 ask_for_var,
636 default,
637 )
638
639 for _ in range(n_ask_attempts):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700640 val = get_from_env_or_user_or_default(environ_cp, var_name, full_query,
Austin Anderson6afface2017-12-05 11:59:17 -0800641 default)
642 if check_success(val):
643 break
644 if not suppress_default_error:
645 print(error_msg % val)
646 environ_cp[var_name] = ''
647 else:
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700648 raise UserInputError(
649 'Invalid %s setting was provided %d times in a row. '
650 'Assuming to be a scripting mistake.' % (var_name, n_ask_attempts))
Austin Anderson6afface2017-12-05 11:59:17 -0800651
652 environ_cp[var_name] = val
653 return val
654
655
656def create_android_ndk_rule(environ_cp):
657 """Set ANDROID_NDK_HOME and write Android NDK WORKSPACE rule."""
658 if is_windows() or is_cygwin():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700659 default_ndk_path = cygpath(
660 '%s/Android/Sdk/ndk-bundle' % environ_cp['APPDATA'])
Austin Anderson6afface2017-12-05 11:59:17 -0800661 elif is_macos():
662 default_ndk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
663 else:
664 default_ndk_path = '%s/Android/Sdk/ndk-bundle' % environ_cp['HOME']
665
666 def valid_ndk_path(path):
667 return (os.path.exists(path) and
668 os.path.exists(os.path.join(path, 'source.properties')))
669
670 android_ndk_home_path = prompt_loop_or_load_from_env(
671 environ_cp,
672 var_name='ANDROID_NDK_HOME',
673 var_default=default_ndk_path,
674 ask_for_var='Please specify the home path of the Android NDK to use.',
675 check_success=valid_ndk_path,
676 error_msg=('The path %s or its child file "source.properties" '
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700677 'does not exist.'))
Michael Case51053502018-06-05 17:47:19 -0700678 write_action_env_to_bazelrc('ANDROID_NDK_HOME', android_ndk_home_path)
679 write_action_env_to_bazelrc('ANDROID_NDK_API_LEVEL',
680 check_ndk_level(android_ndk_home_path))
Austin Anderson6afface2017-12-05 11:59:17 -0800681
682
683def create_android_sdk_rule(environ_cp):
684 """Set Android variables and write Android SDK WORKSPACE rule."""
685 if is_windows() or is_cygwin():
686 default_sdk_path = cygpath('%s/Android/Sdk' % environ_cp['APPDATA'])
687 elif is_macos():
Shashi Shekharc0ff0cc2018-07-17 09:00:24 -0700688 default_sdk_path = '%s/library/Android/Sdk' % environ_cp['HOME']
Austin Anderson6afface2017-12-05 11:59:17 -0800689 else:
690 default_sdk_path = '%s/Android/Sdk' % environ_cp['HOME']
691
692 def valid_sdk_path(path):
693 return (os.path.exists(path) and
694 os.path.exists(os.path.join(path, 'platforms')) and
695 os.path.exists(os.path.join(path, 'build-tools')))
696
697 android_sdk_home_path = prompt_loop_or_load_from_env(
698 environ_cp,
699 var_name='ANDROID_SDK_HOME',
700 var_default=default_sdk_path,
701 ask_for_var='Please specify the home path of the Android SDK to use.',
702 check_success=valid_sdk_path,
703 error_msg=('Either %s does not exist, or it does not contain the '
704 'subdirectories "platforms" and "build-tools".'))
705
706 platforms = os.path.join(android_sdk_home_path, 'platforms')
707 api_levels = sorted(os.listdir(platforms))
708 api_levels = [x.replace('android-', '') for x in api_levels]
709
710 def valid_api_level(api_level):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700711 return os.path.exists(
712 os.path.join(android_sdk_home_path, 'platforms',
713 'android-' + api_level))
Austin Anderson6afface2017-12-05 11:59:17 -0800714
715 android_api_level = prompt_loop_or_load_from_env(
716 environ_cp,
717 var_name='ANDROID_API_LEVEL',
718 var_default=api_levels[-1],
719 ask_for_var=('Please specify the Android SDK API level to use. '
720 '[Available levels: %s]') % api_levels,
721 check_success=valid_api_level,
722 error_msg='Android-%s is not present in the SDK path.')
723
724 build_tools = os.path.join(android_sdk_home_path, 'build-tools')
725 versions = sorted(os.listdir(build_tools))
726
727 def valid_build_tools(version):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700728 return os.path.exists(
729 os.path.join(android_sdk_home_path, 'build-tools', version))
Austin Anderson6afface2017-12-05 11:59:17 -0800730
731 android_build_tools_version = prompt_loop_or_load_from_env(
732 environ_cp,
733 var_name='ANDROID_BUILD_TOOLS_VERSION',
734 var_default=versions[-1],
735 ask_for_var=('Please specify an Android build tools version to use. '
736 '[Available versions: %s]') % versions,
737 check_success=valid_build_tools,
738 error_msg=('The selected SDK does not have build-tools version %s '
739 'available.'))
740
Michael Case51053502018-06-05 17:47:19 -0700741 write_action_env_to_bazelrc('ANDROID_BUILD_TOOLS_VERSION',
742 android_build_tools_version)
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700743 write_action_env_to_bazelrc('ANDROID_SDK_API_LEVEL', android_api_level)
744 write_action_env_to_bazelrc('ANDROID_SDK_HOME', android_sdk_home_path)
Austin Anderson6afface2017-12-05 11:59:17 -0800745
746
747def check_ndk_level(android_ndk_home_path):
748 """Check the revision number of an Android NDK path."""
749 properties_path = '%s/source.properties' % android_ndk_home_path
750 if is_windows() or is_cygwin():
751 properties_path = cygpath(properties_path)
752 with open(properties_path, 'r') as f:
753 filedata = f.read()
754
755 revision = re.search(r'Pkg.Revision = (\d+)', filedata)
756 if revision:
Michael Case51053502018-06-05 17:47:19 -0700757 ndk_api_level = revision.group(1)
758 else:
759 raise Exception('Unable to parse NDK revision.')
760 if int(ndk_api_level) not in _SUPPORTED_ANDROID_NDK_VERSIONS:
761 print('WARNING: The API level of the NDK in %s is %s, which is not '
762 'supported by Bazel (officially supported versions: %s). Please use '
763 'another version. Compiling Android targets may result in confusing '
764 'errors.\n' % (android_ndk_home_path, ndk_api_level,
765 _SUPPORTED_ANDROID_NDK_VERSIONS))
766 return ndk_api_level
Austin Anderson6afface2017-12-05 11:59:17 -0800767
768
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700769def set_gcc_host_compiler_path(environ_cp):
770 """Set GCC_HOST_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700771 default_gcc_host_compiler_path = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700772 cuda_bin_symlink = '%s/bin/gcc' % environ_cp.get('CUDA_TOOLKIT_PATH')
773
774 if os.path.islink(cuda_bin_symlink):
775 # os.readlink is only available in linux
Jonathan Hseu008910f2017-08-25 14:01:05 -0700776 default_gcc_host_compiler_path = os.path.realpath(cuda_bin_symlink)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700777
Austin Anderson6afface2017-12-05 11:59:17 -0800778 gcc_host_compiler_path = prompt_loop_or_load_from_env(
779 environ_cp,
780 var_name='GCC_HOST_COMPILER_PATH',
781 var_default=default_gcc_host_compiler_path,
782 ask_for_var=
783 'Please specify which gcc should be used by nvcc as the host compiler.',
784 check_success=os.path.exists,
785 error_msg='Invalid gcc path. %s cannot be found.',
786 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700787
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700788 write_action_env_to_bazelrc('GCC_HOST_COMPILER_PATH', gcc_host_compiler_path)
789
790
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800791def reformat_version_sequence(version_str, sequence_count):
792 """Reformat the version string to have the given number of sequences.
793
794 For example:
795 Given (7, 2) -> 7.0
796 (7.0.1, 2) -> 7.0
797 (5, 1) -> 5
798 (5.0.3.2, 1) -> 5
799
800 Args:
801 version_str: String, the version string.
802 sequence_count: int, an integer.
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700803
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800804 Returns:
805 string, reformatted version string.
806 """
807 v = version_str.split('.')
808 if len(v) < sequence_count:
809 v = v + (['0'] * (sequence_count - len(v)))
810
811 return '.'.join(v[:sequence_count])
812
813
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700814def set_tf_cuda_version(environ_cp):
815 """Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION."""
816 ask_cuda_version = (
A. Unique TensorFlowerb15500b2018-05-08 12:04:38 -0700817 'Please specify the CUDA SDK version you want to use. '
818 '[Leave empty to default to CUDA %s]: ') % _DEFAULT_CUDA_VERSION
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700819
Austin Andersonf9a88f82017-12-13 11:49:40 -0800820 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700821 # Configure the Cuda SDK version to use.
822 tf_cuda_version = get_from_env_or_user_or_default(
823 environ_cp, 'TF_CUDA_VERSION', ask_cuda_version, _DEFAULT_CUDA_VERSION)
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800824 tf_cuda_version = reformat_version_sequence(str(tf_cuda_version), 2)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700825
826 # Find out where the CUDA toolkit is installed
827 default_cuda_path = _DEFAULT_CUDA_PATH
Martin Wicked57572e2017-09-02 19:21:45 -0700828 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700829 default_cuda_path = cygpath(
830 environ_cp.get('CUDA_PATH', _DEFAULT_CUDA_PATH_WIN))
831 elif is_linux():
832 # If the default doesn't exist, try an alternative default.
833 if (not os.path.exists(default_cuda_path)
834 ) and os.path.exists(_DEFAULT_CUDA_PATH_LINUX):
835 default_cuda_path = _DEFAULT_CUDA_PATH_LINUX
836 ask_cuda_path = ('Please specify the location where CUDA %s toolkit is'
837 ' installed. Refer to README.md for more details. '
838 '[Default is %s]: ') % (tf_cuda_version, default_cuda_path)
839 cuda_toolkit_path = get_from_env_or_user_or_default(
840 environ_cp, 'CUDA_TOOLKIT_PATH', ask_cuda_path, default_cuda_path)
A. Unique TensorFlower02f17fe2018-07-07 06:59:19 -0700841 if is_windows() or is_cygwin():
842 cuda_toolkit_path = cygpath(cuda_toolkit_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700843
844 if is_windows():
Niall Moranb7d97e82018-08-09 00:29:49 +0100845 cuda_rt_lib_paths = ['lib/x64/cudart.lib']
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700846 elif is_linux():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700847 cuda_rt_lib_paths = [
848 '%s/libcudart.so.%s' % (x, tf_cuda_version) for x in [
849 'lib64',
850 'lib/powerpc64le-linux-gnu',
851 'lib/x86_64-linux-gnu',
852 ]
853 ]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700854 elif is_macos():
Niall Moranb7d97e82018-08-09 00:29:49 +0100855 cuda_rt_lib_paths = ['lib/libcudart.%s.dylib' % tf_cuda_version]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700856
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700857 cuda_toolkit_paths_full = [
858 os.path.join(cuda_toolkit_path, x) for x in cuda_rt_lib_paths
859 ]
Niall Moranb7d97e82018-08-09 00:29:49 +0100860 if any([os.path.exists(x) for x in cuda_toolkit_paths_full]):
Yifei Feng5198cb82018-08-17 13:53:06 -0700861 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700862
863 # Reset and retry
864 print('Invalid path to CUDA %s toolkit. %s cannot be found' %
hellcom9a13fc32018-09-12 10:58:24 +0300865 (tf_cuda_version, cuda_toolkit_paths_full))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700866 environ_cp['TF_CUDA_VERSION'] = ''
867 environ_cp['CUDA_TOOLKIT_PATH'] = ''
868
Austin Andersonf9a88f82017-12-13 11:49:40 -0800869 else:
870 raise UserInputError('Invalid TF_CUDA_SETTING setting was provided %d '
871 'times in a row. Assuming to be a scripting mistake.' %
872 _DEFAULT_PROMPT_ASK_ATTEMPTS)
873
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700874 # Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION
875 environ_cp['CUDA_TOOLKIT_PATH'] = cuda_toolkit_path
876 write_action_env_to_bazelrc('CUDA_TOOLKIT_PATH', cuda_toolkit_path)
877 environ_cp['TF_CUDA_VERSION'] = tf_cuda_version
878 write_action_env_to_bazelrc('TF_CUDA_VERSION', tf_cuda_version)
879
880
Yifei Fengb1d8c592017-11-22 13:42:21 -0800881def set_tf_cudnn_version(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700882 """Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION."""
883 ask_cudnn_version = (
Jonathan Hseu008910f2017-08-25 14:01:05 -0700884 'Please specify the cuDNN version you want to use. '
A. Unique TensorFlower44acd832018-10-01 13:42:40 -0700885 '[Leave empty to default to cuDNN %s]: ') % _DEFAULT_CUDNN_VERSION
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700886
Austin Andersonf9a88f82017-12-13 11:49:40 -0800887 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700888 tf_cudnn_version = get_from_env_or_user_or_default(
889 environ_cp, 'TF_CUDNN_VERSION', ask_cudnn_version,
890 _DEFAULT_CUDNN_VERSION)
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800891 tf_cudnn_version = reformat_version_sequence(str(tf_cudnn_version), 1)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700892
893 default_cudnn_path = environ_cp.get('CUDA_TOOLKIT_PATH')
894 ask_cudnn_path = (r'Please specify the location where cuDNN %s library is '
895 'installed. Refer to README.md for more details. [Default'
A. Unique TensorFlower1b212352018-07-19 13:48:50 -0700896 ' is %s]: ') % (tf_cudnn_version, default_cudnn_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700897 cudnn_install_path = get_from_env_or_user_or_default(
898 environ_cp, 'CUDNN_INSTALL_PATH', ask_cudnn_path, default_cudnn_path)
899
900 # Result returned from "read" will be used unexpanded. That make "~"
901 # unusable. Going through one more level of expansion to handle that.
902 cudnn_install_path = os.path.realpath(
903 os.path.expanduser(cudnn_install_path))
Martin Wicked57572e2017-09-02 19:21:45 -0700904 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700905 cudnn_install_path = cygpath(cudnn_install_path)
906
907 if is_windows():
908 cuda_dnn_lib_path = 'lib/x64/cudnn.lib'
909 cuda_dnn_lib_alt_path = 'lib/x64/cudnn.lib'
910 elif is_linux():
911 cuda_dnn_lib_path = 'lib64/libcudnn.so.%s' % tf_cudnn_version
912 cuda_dnn_lib_alt_path = 'libcudnn.so.%s' % tf_cudnn_version
913 elif is_macos():
914 cuda_dnn_lib_path = 'lib/libcudnn.%s.dylib' % tf_cudnn_version
915 cuda_dnn_lib_alt_path = 'libcudnn.%s.dylib' % tf_cudnn_version
916
917 cuda_dnn_lib_path_full = os.path.join(cudnn_install_path, cuda_dnn_lib_path)
918 cuda_dnn_lib_alt_path_full = os.path.join(cudnn_install_path,
919 cuda_dnn_lib_alt_path)
920 if os.path.exists(cuda_dnn_lib_path_full) or os.path.exists(
921 cuda_dnn_lib_alt_path_full):
922 break
923
924 # Try another alternative for Linux
925 if is_linux():
Jonathan Hseu008910f2017-08-25 14:01:05 -0700926 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
927 cudnn_path_from_ldconfig = run_shell([ldconfig_bin, '-p'])
928 cudnn_path_from_ldconfig = re.search('.*libcudnn.so .* => (.*)',
A. Unique TensorFlowere7223582017-09-06 17:57:04 -0700929 cudnn_path_from_ldconfig)
930 if cudnn_path_from_ldconfig:
931 cudnn_path_from_ldconfig = cudnn_path_from_ldconfig.group(1)
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700932 if os.path.exists(
933 '%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version)):
A. Unique TensorFlowere7223582017-09-06 17:57:04 -0700934 cudnn_install_path = os.path.dirname(cudnn_path_from_ldconfig)
935 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700936
937 # Reset and Retry
938 print(
939 'Invalid path to cuDNN %s toolkit. None of the following files can be '
940 'found:' % tf_cudnn_version)
941 print(cuda_dnn_lib_path_full)
942 print(cuda_dnn_lib_alt_path_full)
943 if is_linux():
944 print('%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version))
945
946 environ_cp['TF_CUDNN_VERSION'] = ''
Austin Andersonf9a88f82017-12-13 11:49:40 -0800947 else:
948 raise UserInputError('Invalid TF_CUDNN setting was provided %d '
949 'times in a row. Assuming to be a scripting mistake.' %
950 _DEFAULT_PROMPT_ASK_ATTEMPTS)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700951
952 # Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION
953 environ_cp['CUDNN_INSTALL_PATH'] = cudnn_install_path
954 write_action_env_to_bazelrc('CUDNN_INSTALL_PATH', cudnn_install_path)
955 environ_cp['TF_CUDNN_VERSION'] = tf_cudnn_version
956 write_action_env_to_bazelrc('TF_CUDNN_VERSION', tf_cudnn_version)
957
958
Mingxing Tan1e7b0e42018-06-28 19:13:20 -0700959def is_cuda_compatible(lib, cuda_ver, cudnn_ver):
960 """Check compatibility between given library and cudnn/cudart libraries."""
961 ldd_bin = which('ldd') or '/usr/bin/ldd'
962 ldd_out = run_shell([ldd_bin, lib], True)
963 ldd_out = ldd_out.split(os.linesep)
964 cudnn_pattern = re.compile('.*libcudnn.so\\.?(.*) =>.*$')
965 cuda_pattern = re.compile('.*libcudart.so\\.?(.*) =>.*$')
966 cudnn = None
967 cudart = None
968 cudnn_ok = True # assume no cudnn dependency by default
969 cuda_ok = True # assume no cuda dependency by default
970 for line in ldd_out:
971 if 'libcudnn.so' in line:
972 cudnn = cudnn_pattern.search(line)
973 cudnn_ok = False
974 elif 'libcudart.so' in line:
975 cudart = cuda_pattern.search(line)
976 cuda_ok = False
977 if cudnn and len(cudnn.group(1)):
978 cudnn = convert_version_to_int(cudnn.group(1))
979 if cudart and len(cudart.group(1)):
980 cudart = convert_version_to_int(cudart.group(1))
981 if cudnn is not None:
982 cudnn_ok = (cudnn == cudnn_ver)
983 if cudart is not None:
984 cuda_ok = (cudart == cuda_ver)
985 return cudnn_ok and cuda_ok
986
987
Guangda Lai76f69382018-01-25 23:59:19 -0800988def set_tf_tensorrt_install_path(environ_cp):
989 """Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION.
990
991 Adapted from code contributed by Sami Kama (https://github.com/samikama).
992
993 Args:
994 environ_cp: copy of the os.environ.
995
996 Raises:
997 ValueError: if this method was called under non-Linux platform.
998 UserInputError: if user has provided invalid input multiple times.
999 """
1000 if not is_linux():
1001 raise ValueError('Currently TensorRT is only supported on Linux platform.')
1002
1003 # Ask user whether to add TensorRT support.
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001004 if str(int(get_var(environ_cp, 'TF_NEED_TENSORRT', 'TensorRT',
1005 False))) != '1':
Guangda Lai76f69382018-01-25 23:59:19 -08001006 return
1007
1008 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
1009 ask_tensorrt_path = (r'Please specify the location where TensorRT is '
1010 'installed. [Default is %s]:') % (
1011 _DEFAULT_TENSORRT_PATH_LINUX)
1012 trt_install_path = get_from_env_or_user_or_default(
1013 environ_cp, 'TENSORRT_INSTALL_PATH', ask_tensorrt_path,
1014 _DEFAULT_TENSORRT_PATH_LINUX)
1015
1016 # Result returned from "read" will be used unexpanded. That make "~"
1017 # unusable. Going through one more level of expansion to handle that.
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001018 trt_install_path = os.path.realpath(os.path.expanduser(trt_install_path))
Guangda Lai76f69382018-01-25 23:59:19 -08001019
1020 def find_libs(search_path):
1021 """Search for libnvinfer.so in "search_path"."""
1022 fl = set()
1023 if os.path.exists(search_path) and os.path.isdir(search_path):
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001024 fl.update([
1025 os.path.realpath(os.path.join(search_path, x))
1026 for x in os.listdir(search_path)
1027 if 'libnvinfer.so' in x
1028 ])
Guangda Lai76f69382018-01-25 23:59:19 -08001029 return fl
1030
1031 possible_files = find_libs(trt_install_path)
1032 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib')))
1033 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib64')))
Guangda Lai76f69382018-01-25 23:59:19 -08001034 cuda_ver = convert_version_to_int(environ_cp['TF_CUDA_VERSION'])
1035 cudnn_ver = convert_version_to_int(environ_cp['TF_CUDNN_VERSION'])
1036 nvinfer_pattern = re.compile('.*libnvinfer.so.?(.*)$')
1037 highest_ver = [0, None, None]
1038
1039 for lib_file in possible_files:
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001040 if is_cuda_compatible(lib_file, cuda_ver, cudnn_ver):
Jacques Pienaar2d0531d2018-03-21 12:07:51 -07001041 matches = nvinfer_pattern.search(lib_file)
TensorFlower Gardener61a87202018-10-01 12:25:39 -07001042 if not matches.groups():
Jacques Pienaar2d0531d2018-03-21 12:07:51 -07001043 continue
1044 ver_str = matches.group(1)
Guangda Lai76f69382018-01-25 23:59:19 -08001045 ver = convert_version_to_int(ver_str) if len(ver_str) else 0
1046 if ver > highest_ver[0]:
1047 highest_ver = [ver, ver_str, lib_file]
1048 if highest_ver[1] is not None:
1049 trt_install_path = os.path.dirname(highest_ver[2])
1050 tf_tensorrt_version = highest_ver[1]
1051 break
1052
1053 # Try another alternative from ldconfig.
1054 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
1055 ldconfig_output = run_shell([ldconfig_bin, '-p'])
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001056 search_result = re.search('.*libnvinfer.so\\.?([0-9.]*).* => (.*)',
1057 ldconfig_output)
Guangda Lai76f69382018-01-25 23:59:19 -08001058 if search_result:
1059 libnvinfer_path_from_ldconfig = search_result.group(2)
1060 if os.path.exists(libnvinfer_path_from_ldconfig):
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001061 if is_cuda_compatible(libnvinfer_path_from_ldconfig, cuda_ver,
1062 cudnn_ver):
Guangda Lai76f69382018-01-25 23:59:19 -08001063 trt_install_path = os.path.dirname(libnvinfer_path_from_ldconfig)
1064 tf_tensorrt_version = search_result.group(1)
1065 break
1066
1067 # Reset and Retry
Yifei Fengdce9a492018-02-22 14:24:57 -08001068 if possible_files:
1069 print('TensorRT libraries found in one the following directories',
1070 'are not compatible with selected cuda and cudnn installations')
1071 print(trt_install_path)
1072 print(os.path.join(trt_install_path, 'lib'))
1073 print(os.path.join(trt_install_path, 'lib64'))
1074 if search_result:
1075 print(libnvinfer_path_from_ldconfig)
1076 else:
1077 print(
1078 'Invalid path to TensorRT. None of the following files can be found:')
1079 print(trt_install_path)
1080 print(os.path.join(trt_install_path, 'lib'))
1081 print(os.path.join(trt_install_path, 'lib64'))
1082 if search_result:
1083 print(libnvinfer_path_from_ldconfig)
Guangda Lai76f69382018-01-25 23:59:19 -08001084
1085 else:
1086 raise UserInputError('Invalid TF_TENSORRT setting was provided %d '
1087 'times in a row. Assuming to be a scripting mistake.' %
1088 _DEFAULT_PROMPT_ASK_ATTEMPTS)
1089
1090 # Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION
1091 environ_cp['TENSORRT_INSTALL_PATH'] = trt_install_path
1092 write_action_env_to_bazelrc('TENSORRT_INSTALL_PATH', trt_install_path)
1093 environ_cp['TF_TENSORRT_VERSION'] = tf_tensorrt_version
1094 write_action_env_to_bazelrc('TF_TENSORRT_VERSION', tf_tensorrt_version)
1095
1096
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001097def set_tf_nccl_install_path(environ_cp):
Jason Furmanek7c234152018-09-26 04:44:12 +00001098 """Set NCCL_INSTALL_PATH, NCCL_HDR_PATH and TF_NCCL_VERSION.
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001099
1100 Args:
1101 environ_cp: copy of the os.environ.
1102
1103 Raises:
1104 ValueError: if this method was called under non-Linux platform.
1105 UserInputError: if user has provided invalid input multiple times.
1106 """
1107 if not is_linux():
1108 raise ValueError('Currently NCCL is only supported on Linux platforms.')
1109
1110 ask_nccl_version = (
A. Unique TensorFlower53faa312018-10-05 08:46:54 -07001111 'Please specify the locally installed NCCL version you want to use. '
1112 '[Default is to use https://github.com/nvidia/nccl]: ')
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001113
1114 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
1115 tf_nccl_version = get_from_env_or_user_or_default(
A. Unique TensorFlower53faa312018-10-05 08:46:54 -07001116 environ_cp, 'TF_NCCL_VERSION', ask_nccl_version, '')
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001117
A. Unique TensorFlower53faa312018-10-05 08:46:54 -07001118 if not tf_nccl_version:
1119 break # No need to get install path, building the open source code.
1120
1121 tf_nccl_version = reformat_version_sequence(str(tf_nccl_version), 1)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001122
Jason Furmanek7c234152018-09-26 04:44:12 +00001123 # Look with ldconfig first if we can find the library in paths
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001124 # like /usr/lib/x86_64-linux-gnu and the header file in the corresponding
1125 # include directory. This is where the NCCL .deb packages install them.
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001126
Jason Furmanek7c234152018-09-26 04:44:12 +00001127 # First check to see if NCCL is in the ldconfig.
1128 # If its found, use that location.
1129 if is_linux():
1130 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
1131 nccl2_path_from_ldconfig = run_shell([ldconfig_bin, '-p'])
1132 nccl2_path_from_ldconfig = re.search('.*libnccl.so .* => (.*)',
1133 nccl2_path_from_ldconfig)
1134 if nccl2_path_from_ldconfig:
1135 nccl2_path_from_ldconfig = nccl2_path_from_ldconfig.group(1)
1136 if os.path.exists('%s.%s' % (nccl2_path_from_ldconfig, tf_nccl_version)):
1137 nccl_install_path = os.path.dirname(nccl2_path_from_ldconfig)
1138 print('NCCL libraries found in ' + nccl2_path_from_ldconfig)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001139
Jason Furmanek7c234152018-09-26 04:44:12 +00001140 # Check if this is the main system lib location
1141 if re.search('.*linux-gnu', nccl_install_path):
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001142 trunc_nccl_install_path = '/usr'
1143 print('This looks like a system path.')
Jason Furmanek7c234152018-09-26 04:44:12 +00001144 else:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001145 trunc_nccl_install_path = nccl_install_path + '/..'
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001146
Jason Furmanek7c234152018-09-26 04:44:12 +00001147 # Look for header
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001148 nccl_hdr_path = trunc_nccl_install_path + '/include'
1149 print('Assuming NCCL header path is ' + nccl_hdr_path)
1150 if os.path.exists(nccl_hdr_path + '/nccl.h'):
Jason Furmanek7c234152018-09-26 04:44:12 +00001151 # Set NCCL_INSTALL_PATH
1152 environ_cp['NCCL_INSTALL_PATH'] = nccl_install_path
1153 write_action_env_to_bazelrc('NCCL_INSTALL_PATH', nccl_install_path)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001154
Jason Furmanek7c234152018-09-26 04:44:12 +00001155 # Set NCCL_HDR_PATH
1156 environ_cp['NCCL_HDR_PATH'] = nccl_hdr_path
1157 write_action_env_to_bazelrc('NCCL_HDR_PATH', nccl_hdr_path)
1158 break
1159 else:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001160 print(
1161 'The header for NCCL2 cannot be found. Please install the libnccl-dev package.'
1162 )
Jason Furmanek7c234152018-09-26 04:44:12 +00001163 else:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001164 print('NCCL2 is listed by ldconfig but the library is not found. '
1165 'Your ldconfig is out of date. Please run sudo ldconfig.')
Jason Furmanek7c234152018-09-26 04:44:12 +00001166 else:
1167 # NCCL is not found in ldconfig. Ask the user for the location.
1168 default_nccl_path = environ_cp.get('CUDA_TOOLKIT_PATH')
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001169 ask_nccl_path = (
1170 r'Please specify the location where NCCL %s library is '
1171 'installed. Refer to README.md for more details. [Default '
1172 'is %s]:') % (tf_nccl_version, default_nccl_path)
Jason Furmanek7c234152018-09-26 04:44:12 +00001173 nccl_install_path = get_from_env_or_user_or_default(
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001174 environ_cp, 'NCCL_INSTALL_PATH', ask_nccl_path, default_nccl_path)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001175
Jason Furmanek7c234152018-09-26 04:44:12 +00001176 # Result returned from "read" will be used unexpanded. That make "~"
1177 # unusable. Going through one more level of expansion to handle that.
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001178 nccl_install_path = os.path.realpath(
1179 os.path.expanduser(nccl_install_path))
Jason Furmanek7c234152018-09-26 04:44:12 +00001180 if is_windows() or is_cygwin():
1181 nccl_install_path = cygpath(nccl_install_path)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001182
Jason Furmanek7c234152018-09-26 04:44:12 +00001183 if is_windows():
1184 nccl_lib_path = 'lib/x64/nccl.lib'
1185 elif is_linux():
1186 nccl_lib_filename = 'libnccl.so.%s' % tf_nccl_version
1187 nccl_lpath = '%s/lib/%s' % (nccl_install_path, nccl_lib_filename)
1188 if not os.path.exists(nccl_lpath):
1189 for relative_path in NCCL_LIB_PATHS:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001190 path = '%s/%s%s' % (nccl_install_path, relative_path,
1191 nccl_lib_filename)
Jason Furmanek7c234152018-09-26 04:44:12 +00001192 if os.path.exists(path):
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001193 print('NCCL found at ' + path)
Jason Furmanek7c234152018-09-26 04:44:12 +00001194 nccl_lib_path = path
1195 break
1196 else:
1197 nccl_lib_path = nccl_lpath
1198 elif is_macos():
1199 nccl_lib_path = 'lib/libnccl.%s.dylib' % tf_nccl_version
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001200
Jason Furmanek7c234152018-09-26 04:44:12 +00001201 nccl_lib_path = os.path.join(nccl_install_path, nccl_lib_path)
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001202 nccl_hdr_path = os.path.join(
1203 os.path.dirname(nccl_lib_path), '../include/nccl.h')
1204 print('Assuming NCCL header path is ' + nccl_hdr_path)
Jason Furmanek7c234152018-09-26 04:44:12 +00001205 if os.path.exists(nccl_lib_path) and os.path.exists(nccl_hdr_path):
1206 # Set NCCL_INSTALL_PATH
1207 environ_cp['NCCL_INSTALL_PATH'] = os.path.dirname(nccl_lib_path)
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001208 write_action_env_to_bazelrc('NCCL_INSTALL_PATH',
1209 os.path.dirname(nccl_lib_path))
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001210
Jason Furmanek7c234152018-09-26 04:44:12 +00001211 # Set NCCL_HDR_PATH
1212 environ_cp['NCCL_HDR_PATH'] = os.path.dirname(nccl_hdr_path)
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001213 write_action_env_to_bazelrc('NCCL_HDR_PATH',
1214 os.path.dirname(nccl_hdr_path))
Jason Furmanek7c234152018-09-26 04:44:12 +00001215 break
1216
1217 # Reset and Retry
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001218 print(
1219 'Invalid path to NCCL %s toolkit, %s or %s not found. Please use the '
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001220 'O/S agnostic package of NCCL 2' % (tf_nccl_version, nccl_lib_path,
1221 nccl_hdr_path))
1222
Jason Furmanek7c234152018-09-26 04:44:12 +00001223 environ_cp['TF_NCCL_VERSION'] = ''
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001224 else:
1225 raise UserInputError('Invalid TF_NCCL setting was provided %d '
1226 'times in a row. Assuming to be a scripting mistake.' %
1227 _DEFAULT_PROMPT_ASK_ATTEMPTS)
1228
1229 # Set TF_NCCL_VERSION
1230 environ_cp['TF_NCCL_VERSION'] = tf_nccl_version
1231 write_action_env_to_bazelrc('TF_NCCL_VERSION', tf_nccl_version)
1232
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001233def get_native_cuda_compute_capabilities(environ_cp):
1234 """Get native cuda compute capabilities.
1235
1236 Args:
1237 environ_cp: copy of the os.environ.
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001238
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001239 Returns:
1240 string of native cuda compute capabilities, separated by comma.
1241 """
1242 device_query_bin = os.path.join(
1243 environ_cp.get('CUDA_TOOLKIT_PATH'), 'extras/demo_suite/deviceQuery')
Jonathan Hseu008910f2017-08-25 14:01:05 -07001244 if os.path.isfile(device_query_bin) and os.access(device_query_bin, os.X_OK):
1245 try:
1246 output = run_shell(device_query_bin).split('\n')
1247 pattern = re.compile('[0-9]*\\.[0-9]*')
1248 output = [pattern.search(x) for x in output if 'Capability' in x]
1249 output = ','.join(x.group() for x in output if x is not None)
1250 except subprocess.CalledProcessError:
1251 output = ''
1252 else:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001253 output = ''
1254 return output
1255
1256
1257def set_tf_cuda_compute_capabilities(environ_cp):
1258 """Set TF_CUDA_COMPUTE_CAPABILITIES."""
1259 while True:
1260 native_cuda_compute_capabilities = get_native_cuda_compute_capabilities(
1261 environ_cp)
1262 if not native_cuda_compute_capabilities:
1263 default_cuda_compute_capabilities = _DEFAULT_CUDA_COMPUTE_CAPABILITIES
1264 else:
1265 default_cuda_compute_capabilities = native_cuda_compute_capabilities
1266
1267 ask_cuda_compute_capabilities = (
1268 'Please specify a list of comma-separated '
1269 'Cuda compute capabilities you want to '
1270 'build with.\nYou can find the compute '
1271 'capability of your device at: '
1272 'https://developer.nvidia.com/cuda-gpus.\nPlease'
1273 ' note that each additional compute '
1274 'capability significantly increases your '
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001275 'build time and binary size. [Default is: %s]: ' %
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001276 default_cuda_compute_capabilities)
1277 tf_cuda_compute_capabilities = get_from_env_or_user_or_default(
1278 environ_cp, 'TF_CUDA_COMPUTE_CAPABILITIES',
1279 ask_cuda_compute_capabilities, default_cuda_compute_capabilities)
1280 # Check whether all capabilities from the input is valid
1281 all_valid = True
Maciejd0f5bc12018-04-30 22:30:58 -05001282 # Remove all whitespace characters before splitting the string
Michael Case51053502018-06-05 17:47:19 -07001283 # that users may insert by accident, as this will result in error
Maciejd0f5bc12018-04-30 22:30:58 -05001284 tf_cuda_compute_capabilities = ''.join(tf_cuda_compute_capabilities.split())
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001285 for compute_capability in tf_cuda_compute_capabilities.split(','):
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001286 m = re.match('[0-9]+.[0-9]+', compute_capability)
1287 if not m:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001288 print('Invalid compute capability: ' % compute_capability)
1289 all_valid = False
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001290 else:
1291 ver = int(m.group(0).split('.')[0])
1292 if ver < 3:
1293 print('Only compute capabilities 3.0 or higher are supported.')
1294 all_valid = False
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001295
1296 if all_valid:
1297 break
1298
1299 # Reset and Retry
1300 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = ''
1301
1302 # Set TF_CUDA_COMPUTE_CAPABILITIES
1303 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = tf_cuda_compute_capabilities
1304 write_action_env_to_bazelrc('TF_CUDA_COMPUTE_CAPABILITIES',
1305 tf_cuda_compute_capabilities)
1306
1307
1308def set_other_cuda_vars(environ_cp):
1309 """Set other CUDA related variables."""
A. Unique TensorFlowerab391982018-07-11 04:52:49 -07001310 # If CUDA is enabled, always use GPU during build and test.
1311 if environ_cp.get('TF_CUDA_CLANG') == '1':
1312 write_to_bazelrc('build --config=cuda_clang')
1313 write_to_bazelrc('test --config=cuda_clang')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001314 else:
A. Unique TensorFlowerab391982018-07-11 04:52:49 -07001315 write_to_bazelrc('build --config=cuda')
1316 write_to_bazelrc('test --config=cuda')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001317
1318
1319def set_host_cxx_compiler(environ_cp):
1320 """Set HOST_CXX_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001321 default_cxx_host_compiler = which('g++') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001322
Austin Anderson6afface2017-12-05 11:59:17 -08001323 host_cxx_compiler = prompt_loop_or_load_from_env(
1324 environ_cp,
1325 var_name='HOST_CXX_COMPILER',
1326 var_default=default_cxx_host_compiler,
1327 ask_for_var=('Please specify which C++ compiler should be used as the '
1328 'host C++ compiler.'),
1329 check_success=os.path.exists,
1330 error_msg='Invalid C++ compiler path. %s cannot be found.',
1331 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001332
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001333 write_action_env_to_bazelrc('HOST_CXX_COMPILER', host_cxx_compiler)
1334
1335
1336def set_host_c_compiler(environ_cp):
1337 """Set HOST_C_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001338 default_c_host_compiler = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001339
Austin Anderson6afface2017-12-05 11:59:17 -08001340 host_c_compiler = prompt_loop_or_load_from_env(
1341 environ_cp,
1342 var_name='HOST_C_COMPILER',
1343 var_default=default_c_host_compiler,
Shanqing Cai71445712018-03-12 19:33:52 -07001344 ask_for_var=('Please specify which C compiler should be used as the host '
Austin Anderson6afface2017-12-05 11:59:17 -08001345 'C compiler.'),
1346 check_success=os.path.exists,
1347 error_msg='Invalid C compiler path. %s cannot be found.',
1348 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001349
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001350 write_action_env_to_bazelrc('HOST_C_COMPILER', host_c_compiler)
1351
1352
1353def set_computecpp_toolkit_path(environ_cp):
1354 """Set COMPUTECPP_TOOLKIT_PATH."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001355
Austin Anderson6afface2017-12-05 11:59:17 -08001356 def toolkit_exists(toolkit_path):
1357 """Check if a computecpp toolkit path is valid."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001358 if is_linux():
1359 sycl_rt_lib_path = 'lib/libComputeCpp.so'
1360 else:
1361 sycl_rt_lib_path = ''
1362
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001363 sycl_rt_lib_path_full = os.path.join(toolkit_path, sycl_rt_lib_path)
Austin Anderson6afface2017-12-05 11:59:17 -08001364 exists = os.path.exists(sycl_rt_lib_path_full)
1365 if not exists:
1366 print('Invalid SYCL %s library path. %s cannot be found' %
1367 (_TF_OPENCL_VERSION, sycl_rt_lib_path_full))
1368 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001369
Austin Anderson6afface2017-12-05 11:59:17 -08001370 computecpp_toolkit_path = prompt_loop_or_load_from_env(
1371 environ_cp,
1372 var_name='COMPUTECPP_TOOLKIT_PATH',
1373 var_default=_DEFAULT_COMPUTECPP_TOOLKIT_PATH,
1374 ask_for_var=(
1375 'Please specify the location where ComputeCpp for SYCL %s is '
1376 'installed.' % _TF_OPENCL_VERSION),
1377 check_success=toolkit_exists,
1378 error_msg='Invalid SYCL compiler path. %s cannot be found.',
1379 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001380
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001381 write_action_env_to_bazelrc('COMPUTECPP_TOOLKIT_PATH',
1382 computecpp_toolkit_path)
1383
Michael Cased31531a2018-01-05 14:09:41 -08001384
Dandelion Man?90e42f32017-12-15 18:15:07 -08001385def set_trisycl_include_dir(environ_cp):
Michael Cased31531a2018-01-05 14:09:41 -08001386 """Set TRISYCL_INCLUDE_DIR."""
Frank Chenc4ef9272018-01-10 11:36:52 -08001387
Dandelion Man?90e42f32017-12-15 18:15:07 -08001388 ask_trisycl_include_dir = ('Please specify the location of the triSYCL '
1389 'include directory. (Use --config=sycl_trisycl '
1390 'when building with Bazel) '
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001391 '[Default is %s]: ') % (
1392 _DEFAULT_TRISYCL_INCLUDE_DIR)
Frank Chenc4ef9272018-01-10 11:36:52 -08001393
Dandelion Man?90e42f32017-12-15 18:15:07 -08001394 while True:
1395 trisycl_include_dir = get_from_env_or_user_or_default(
Michael Cased31531a2018-01-05 14:09:41 -08001396 environ_cp, 'TRISYCL_INCLUDE_DIR', ask_trisycl_include_dir,
1397 _DEFAULT_TRISYCL_INCLUDE_DIR)
Dandelion Man?90e42f32017-12-15 18:15:07 -08001398 if os.path.exists(trisycl_include_dir):
1399 break
1400
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001401 print('Invalid triSYCL include directory, %s cannot be found' %
1402 (trisycl_include_dir))
Dandelion Man?90e42f32017-12-15 18:15:07 -08001403
1404 # Set TRISYCL_INCLUDE_DIR
1405 environ_cp['TRISYCL_INCLUDE_DIR'] = trisycl_include_dir
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001406 write_action_env_to_bazelrc('TRISYCL_INCLUDE_DIR', trisycl_include_dir)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001407
Yifei Fengb1d8c592017-11-22 13:42:21 -08001408
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001409def set_mpi_home(environ_cp):
1410 """Set MPI_HOME."""
Austin Anderson6afface2017-12-05 11:59:17 -08001411
Jonathan Hseu008910f2017-08-25 14:01:05 -07001412 default_mpi_home = which('mpirun') or which('mpiexec') or ''
1413 default_mpi_home = os.path.dirname(os.path.dirname(default_mpi_home))
1414
Austin Anderson6afface2017-12-05 11:59:17 -08001415 def valid_mpi_path(mpi_home):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001416 exists = (
1417 os.path.exists(os.path.join(mpi_home, 'include')) and
1418 os.path.exists(os.path.join(mpi_home, 'lib')))
Austin Anderson6afface2017-12-05 11:59:17 -08001419 if not exists:
1420 print('Invalid path to the MPI Toolkit. %s or %s cannot be found' %
1421 (os.path.join(mpi_home, 'include'),
1422 os.path.exists(os.path.join(mpi_home, 'lib'))))
1423 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001424
Austin Anderson6afface2017-12-05 11:59:17 -08001425 _ = prompt_loop_or_load_from_env(
1426 environ_cp,
1427 var_name='MPI_HOME',
1428 var_default=default_mpi_home,
1429 ask_for_var='Please specify the MPI toolkit folder.',
1430 check_success=valid_mpi_path,
1431 error_msg='',
1432 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001433
1434
1435def set_other_mpi_vars(environ_cp):
1436 """Set other MPI related variables."""
1437 # Link the MPI header files
1438 mpi_home = environ_cp.get('MPI_HOME')
1439 symlink_force('%s/include/mpi.h' % mpi_home, 'third_party/mpi/mpi.h')
1440
1441 # Determine if we use OpenMPI or MVAPICH, these require different header files
1442 # to be included here to make bazel dependency checker happy
1443 if os.path.exists(os.path.join(mpi_home, 'include/mpi_portable_platform.h')):
1444 symlink_force(
1445 os.path.join(mpi_home, 'include/mpi_portable_platform.h'),
1446 'third_party/mpi/mpi_portable_platform.h')
1447 # TODO(gunan): avoid editing files in configure
1448 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=False',
1449 'MPI_LIB_IS_OPENMPI=True')
1450 else:
1451 # MVAPICH / MPICH
1452 symlink_force(
1453 os.path.join(mpi_home, 'include/mpio.h'), 'third_party/mpi/mpio.h')
1454 symlink_force(
1455 os.path.join(mpi_home, 'include/mpicxx.h'), 'third_party/mpi/mpicxx.h')
1456 # TODO(gunan): avoid editing files in configure
1457 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=True',
1458 'MPI_LIB_IS_OPENMPI=False')
1459
1460 if os.path.exists(os.path.join(mpi_home, 'lib/libmpi.so')):
1461 symlink_force(
1462 os.path.join(mpi_home, 'lib/libmpi.so'), 'third_party/mpi/libmpi.so')
1463 else:
1464 raise ValueError('Cannot find the MPI library file in %s/lib' % mpi_home)
1465
1466
Yifei Feng5198cb82018-08-17 13:53:06 -07001467def set_system_libs_flag(environ_cp):
1468 syslibs = environ_cp.get('TF_SYSTEM_LIBS', '')
TensorFlower Gardener61a87202018-10-01 12:25:39 -07001469 if syslibs:
Jason Zaman5fc39bd2018-09-16 01:38:55 +08001470 if ',' in syslibs:
1471 syslibs = ','.join(sorted(syslibs.split(',')))
1472 else:
1473 syslibs = ','.join(sorted(syslibs.split()))
Yifei Feng5198cb82018-08-17 13:53:06 -07001474 write_action_env_to_bazelrc('TF_SYSTEM_LIBS', syslibs)
1475
Jason Zaman5fc39bd2018-09-16 01:38:55 +08001476 if 'PREFIX' in environ_cp:
1477 write_to_bazelrc('build --define=PREFIX=%s' % environ_cp['PREFIX'])
1478 if 'LIBDIR' in environ_cp:
1479 write_to_bazelrc('build --define=LIBDIR=%s' % environ_cp['LIBDIR'])
1480 if 'INCLUDEDIR' in environ_cp:
1481 write_to_bazelrc('build --define=INCLUDEDIR=%s' % environ_cp['INCLUDEDIR'])
1482
Yifei Feng5198cb82018-08-17 13:53:06 -07001483
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001484def set_windows_build_flags(environ_cp):
1485 """Set Windows specific build options."""
1486 # The non-monolithic build is not supported yet
1487 write_to_bazelrc('build --config monolithic')
1488 # Suppress warning messages
1489 write_to_bazelrc('build --copt=-w --host_copt=-w')
1490 # Output more verbose information when something goes wrong
1491 write_to_bazelrc('build --verbose_failures')
1492 # The host and target platforms are the same in Windows build. So we don't
1493 # have to distinct them. This avoids building the same targets twice.
1494 write_to_bazelrc('build --distinct_host_configuration=false')
1495 # Enable short object file path to avoid long path issue on Windows.
1496 # TODO(pcloudy): Remove this flag when upgrading Bazel to 0.16.0
1497 # Short object file path will be enabled by default.
1498 write_to_bazelrc('build --experimental_shortened_obj_file_path=true')
A. Unique TensorFlower77e26862018-09-27 06:19:58 -07001499 # When building zip file for some py_binary and py_test targets, don't
1500 # include its dependencies. This is for:
1501 # 1. Running python tests against the system installed TF pip package.
1502 # 2. Avoiding redundant files in
1503 # //tensorflow/tools/pip_package:simple_console_windows,
1504 # which is a py_binary used during creating TF pip package.
1505 # See https://github.com/tensorflow/tensorflow/issues/22390
1506 write_to_bazelrc('build --define=no_tensorflow_py_deps=true')
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001507
1508 if get_var(
1509 environ_cp, 'TF_OVERRIDE_EIGEN_STRONG_INLINE', 'Eigen strong inline',
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001510 True, ('Would you like to override eigen strong inline for some C++ '
1511 'compilation to reduce the compilation time?'),
1512 'Eigen strong inline overridden.', 'Not overriding eigen strong inline, '
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001513 'some compilations could take more than 20 mins.'):
1514 # Due to a known MSVC compiler issue
1515 # https://github.com/tensorflow/tensorflow/issues/10521
1516 # Overriding eigen strong inline speeds up the compiling of
1517 # conv_grad_ops_3d.cc and conv_ops_3d.cc by 20 minutes,
1518 # but this also hurts the performance. Let users decide what they want.
1519 write_to_bazelrc('build --define=override_eigen_strong_inline=true')
Dandelion Man?90e42f32017-12-15 18:15:07 -08001520
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001521
Michael Cased31531a2018-01-05 14:09:41 -08001522def config_info_line(name, help_text):
1523 """Helper function to print formatted help text for Bazel config options."""
1524 print('\t--config=%-12s\t# %s' % (name, help_text))
1525
1526
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001527def main():
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001528 global _TF_WORKSPACE_ROOT
1529 global _TF_BAZELRC
1530
Shanqing Cai71445712018-03-12 19:33:52 -07001531 parser = argparse.ArgumentParser()
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001532 parser.add_argument(
1533 '--workspace',
1534 type=str,
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001535 default=os.path.abspath(os.path.dirname(__file__)),
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001536 help='The absolute path to your active Bazel workspace.')
Shanqing Cai71445712018-03-12 19:33:52 -07001537 args = parser.parse_args()
1538
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001539 _TF_WORKSPACE_ROOT = args.workspace
1540 _TF_BAZELRC = os.path.join(_TF_WORKSPACE_ROOT, _TF_BAZELRC_FILENAME)
1541
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001542 # Make a copy of os.environ to be clear when functions and getting and setting
1543 # environment variables.
1544 environ_cp = dict(os.environ)
1545
Yifei Fengbb384112018-07-24 13:12:54 -07001546 check_bazel_version('0.15.0')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001547
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001548 reset_tf_configure_bazelrc()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001549 cleanup_makefile()
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -07001550 setup_python(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001551
1552 if is_windows():
Yifei Fengb1d8c592017-11-22 13:42:21 -08001553 environ_cp['TF_NEED_OPENCL_SYCL'] = '0'
1554 environ_cp['TF_NEED_COMPUTECPP'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001555 environ_cp['TF_NEED_OPENCL'] = '0'
1556 environ_cp['TF_CUDA_CLANG'] = '0'
Guangda Lai76f69382018-01-25 23:59:19 -08001557 environ_cp['TF_NEED_TENSORRT'] = '0'
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001558 # TODO(ibiryukov): Investigate using clang as a cpu or cuda compiler on
1559 # Windows.
1560 environ_cp['TF_DOWNLOAD_CLANG'] = '0'
A. Unique TensorFlower6e97fb32018-07-16 14:07:29 -07001561 environ_cp['TF_ENABLE_XLA'] = '0'
A. Unique TensorFlower6e97fb32018-07-16 14:07:29 -07001562 environ_cp['TF_NEED_MPI'] = '0'
1563 environ_cp['TF_SET_ANDROID_WORKSPACE'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001564
1565 if is_macos():
Guangda Lai76f69382018-01-25 23:59:19 -08001566 environ_cp['TF_NEED_TENSORRT'] = '0'
Todd Wang35459cb2018-09-28 08:56:06 -07001567 environ_cp['TF_ENABLE_XLA'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001568
Jon Triebenbach6896a742018-06-27 13:29:53 -05001569 # The numpy package on ppc64le uses OpenBLAS which has multi-threading
1570 # issues that lead to incorrect answers. Set OMP_NUM_THREADS=1 at
1571 # runtime to allow the Tensorflow testcases which compare numpy
1572 # results to Tensorflow results to succeed.
1573 if is_ppc64le():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001574 write_action_env_to_bazelrc('OMP_NUM_THREADS', 1)
Jon Triebenbach6896a742018-06-27 13:29:53 -05001575
Anton Dmitriev85301672018-08-24 16:52:07 +03001576 set_build_var(environ_cp, 'TF_NEED_IGNITE', 'Apache Ignite',
1577 'with_ignite_support', True, 'ignite')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001578 set_build_var(environ_cp, 'TF_ENABLE_XLA', 'XLA JIT', 'with_xla_support',
Todd Wang35459cb2018-09-28 08:56:06 -07001579 True, 'xla')
Gunhan Gulsoy3da0dff2018-09-26 11:55:50 -07001580
Yifei Fengb1d8c592017-11-22 13:42:21 -08001581 set_action_env_var(environ_cp, 'TF_NEED_OPENCL_SYCL', 'OpenCL SYCL', False)
1582 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001583 set_host_cxx_compiler(environ_cp)
1584 set_host_c_compiler(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001585 set_action_env_var(environ_cp, 'TF_NEED_COMPUTECPP', 'ComputeCPP', True)
1586 if environ_cp.get('TF_NEED_COMPUTECPP') == '1':
1587 set_computecpp_toolkit_path(environ_cp)
1588 else:
1589 set_trisycl_include_dir(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001590
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001591 set_action_env_var(environ_cp, 'TF_NEED_ROCM', 'ROCm', False)
1592 if (environ_cp.get('TF_NEED_ROCM') == '1' and
TensorFlower Gardener62e60162018-09-27 10:22:55 -07001593 'LD_LIBRARY_PATH' in environ_cp and
1594 environ_cp.get('LD_LIBRARY_PATH') != '1'):
1595 write_action_env_to_bazelrc('LD_LIBRARY_PATH',
1596 environ_cp.get('LD_LIBRARY_PATH'))
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001597
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001598 set_action_env_var(environ_cp, 'TF_NEED_CUDA', 'CUDA', False)
A. Unique TensorFlower24cbb2a2017-09-08 07:45:44 -07001599 if (environ_cp.get('TF_NEED_CUDA') == '1' and
1600 'TF_CUDA_CONFIG_REPO' not in environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001601 set_tf_cuda_version(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001602 set_tf_cudnn_version(environ_cp)
Guangda Lai76f69382018-01-25 23:59:19 -08001603 if is_linux():
1604 set_tf_tensorrt_install_path(environ_cp)
Michael Case0073d132018-04-11 09:34:44 -07001605 set_tf_nccl_install_path(environ_cp)
1606
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001607 set_tf_cuda_compute_capabilities(environ_cp)
Ankur Taly0e6f39d2018-02-16 18:22:55 -08001608 if 'LD_LIBRARY_PATH' in environ_cp and environ_cp.get(
1609 'LD_LIBRARY_PATH') != '1':
1610 write_action_env_to_bazelrc('LD_LIBRARY_PATH',
1611 environ_cp.get('LD_LIBRARY_PATH'))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001612
1613 set_tf_cuda_clang(environ_cp)
1614 if environ_cp.get('TF_CUDA_CLANG') == '1':
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001615 # Ask whether we should download the clang toolchain.
1616 set_tf_download_clang(environ_cp)
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -08001617 if environ_cp.get('TF_DOWNLOAD_CLANG') != '1':
1618 # Set up which clang we should use as the cuda / host compiler.
1619 set_clang_cuda_compiler_path(environ_cp)
Ilya Biryukov1c3d02e2018-09-04 03:09:52 -07001620 else:
1621 # Use downloaded LLD for linking.
1622 write_to_bazelrc('build:cuda_clang --config=download_clang_use_lld')
1623 write_to_bazelrc('test:cuda_clang --config=download_clang_use_lld')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001624 else:
1625 # Set up which gcc nvcc should use as the host compiler
1626 # No need to set this on Windows
1627 if not is_windows():
1628 set_gcc_host_compiler_path(environ_cp)
1629 set_other_cuda_vars(environ_cp)
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001630 else:
1631 # CUDA not required. Ask whether we should download the clang toolchain and
1632 # use it for the CPU build.
1633 set_tf_download_clang(environ_cp)
1634 if environ_cp.get('TF_DOWNLOAD_CLANG') == '1':
1635 write_to_bazelrc('build --config=download_clang')
1636 write_to_bazelrc('test --config=download_clang')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001637
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001638 # SYCL / ROCm / CUDA are mutually exclusive.
1639 # At most 1 GPU platform can be configured.
1640 gpu_platform_count = 0
1641 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
1642 gpu_platform_count += 1
1643 if environ_cp.get('TF_NEED_ROCM') == '1':
1644 gpu_platform_count += 1
1645 if environ_cp.get('TF_NEED_CUDA') == '1':
1646 gpu_platform_count += 1
1647 if gpu_platform_count >= 2:
1648 raise UserInputError('SYCL / CUDA / ROCm are mututally exclusive. '
1649 'At most 1 GPU platform can be configured.')
1650
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001651 set_build_var(environ_cp, 'TF_NEED_MPI', 'MPI', 'with_mpi_support', False)
1652 if environ_cp.get('TF_NEED_MPI') == '1':
1653 set_mpi_home(environ_cp)
1654 set_other_mpi_vars(environ_cp)
1655
1656 set_cc_opt_flags(environ_cp)
Yifei Feng5198cb82018-08-17 13:53:06 -07001657 set_system_libs_flag(environ_cp)
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001658 if is_windows():
1659 set_windows_build_flags(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001660
Anna Ra9a1d5a2018-09-14 12:44:31 -07001661 # Add a config option to build TensorFlow 2.0 API.
1662 write_to_bazelrc('build:v2 --define=tf_api_version=2')
1663
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001664 if get_var(environ_cp, 'TF_SET_ANDROID_WORKSPACE', 'android workspace', False,
1665 ('Would you like to interactively configure ./WORKSPACE for '
1666 'Android builds?'), 'Searching for NDK and SDK installations.',
1667 'Not configuring the WORKSPACE for Android builds.'):
Michael Case51053502018-06-05 17:47:19 -07001668 create_android_ndk_rule(environ_cp)
1669 create_android_sdk_rule(environ_cp)
Austin Anderson6afface2017-12-05 11:59:17 -08001670
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001671 # On Windows, we don't have MKL support and the build is always monolithic.
1672 # So no need to print the following message.
1673 # TODO(pcloudy): remove the following if check when they make sense on Windows
1674 if not is_windows():
1675 print('Preconfigured Bazel build configs. You can use any of the below by '
Yifei Fenged904612018-10-03 14:01:16 -07001676 'adding "--config=<>" to your build command. See .bazelrc for more '
1677 'details.')
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001678 config_info_line('mkl', 'Build with MKL support.')
1679 config_info_line('monolithic', 'Config for mostly static monolithic build.')
Gunhan Gulsoy3da0dff2018-09-26 11:55:50 -07001680 config_info_line('gdr', 'Build with GDR support.')
1681 config_info_line('verbs', 'Build with libverbs support.')
avijit-nervanaf172c522018-09-27 12:57:24 -07001682 config_info_line('ngraph', 'Build with Intel nGraph support.')
Austin Anderson6afface2017-12-05 11:59:17 -08001683
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001684
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001685if __name__ == '__main__':
1686 main()