blob: 7e47175b98866f8d6ed6e0592de99baa6600b8a3 [file] [log] [blame]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ==============================================================================
15"""configure script to get build parameters from user."""
16
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import print_function
20
Shanqing Cai71445712018-03-12 19:33:52 -070021import argparse
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070022import errno
23import os
24import platform
25import re
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070026import subprocess
27import sys
28
Andrew Sellec9885ea2017-11-06 09:37:03 -080029# pylint: disable=g-import-not-at-top
Jonathan Hseu008910f2017-08-25 14:01:05 -070030try:
31 from shutil import which
32except ImportError:
33 from distutils.spawn import find_executable as which
Andrew Sellec9885ea2017-11-06 09:37:03 -080034# pylint: enable=g-import-not-at-top
Jonathan Hseu008910f2017-08-25 14:01:05 -070035
Dandelion Man?90e42f32017-12-15 18:15:07 -080036_DEFAULT_CUDA_VERSION = '9.0'
37_DEFAULT_CUDNN_VERSION = '7'
Smit Hinsu63e6b9b2018-07-13 12:46:24 -070038_DEFAULT_NCCL_VERSION = '2.2'
Smit Hinsufe7d1d92018-07-14 13:16:58 -070039_DEFAULT_CUDA_COMPUTE_CAPABILITIES = '3.5,7.0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070040_DEFAULT_CUDA_PATH = '/usr/local/cuda'
41_DEFAULT_CUDA_PATH_LINUX = '/opt/cuda'
42_DEFAULT_CUDA_PATH_WIN = ('C:/Program Files/NVIDIA GPU Computing '
43 'Toolkit/CUDA/v%s' % _DEFAULT_CUDA_VERSION)
44_TF_OPENCL_VERSION = '1.2'
45_DEFAULT_COMPUTECPP_TOOLKIT_PATH = '/usr/local/computecpp'
Yifei Fengb1d8c592017-11-22 13:42:21 -080046_DEFAULT_TRISYCL_INCLUDE_DIR = '/usr/local/triSYCL/include'
A. Unique TensorFlowerd340f472018-08-30 14:00:41 -070047_SUPPORTED_ANDROID_NDK_VERSIONS = [10, 11, 12, 13, 14, 15, 16]
Austin Anderson6afface2017-12-05 11:59:17 -080048
49_DEFAULT_PROMPT_ASK_ATTEMPTS = 10
50
Shanqing Cai71445712018-03-12 19:33:52 -070051_TF_BAZELRC_FILENAME = '.tf_configure.bazelrc'
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -070052_TF_WORKSPACE_ROOT = ''
53_TF_BAZELRC = ''
Shanqing Cai71445712018-03-12 19:33:52 -070054
Jason Furmanek7c234152018-09-26 04:44:12 +000055NCCL_LIB_PATHS = [
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -070056 'lib64/', 'lib/powerpc64le-linux-gnu/', 'lib/x86_64-linux-gnu/', ''
Jason Furmanek7c234152018-09-26 04:44:12 +000057]
Austin Anderson6afface2017-12-05 11:59:17 -080058
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -070059if platform.machine() == 'ppc64le':
60 _DEFAULT_TENSORRT_PATH_LINUX = '/usr/lib/powerpc64le-linux-gnu/'
61else:
62 _DEFAULT_TENSORRT_PATH_LINUX = '/usr/lib/%s-linux-gnu' % platform.machine()
63
Austin Anderson6afface2017-12-05 11:59:17 -080064
65class UserInputError(Exception):
66 pass
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070067
68
69def is_windows():
70 return platform.system() == 'Windows'
71
72
73def is_linux():
74 return platform.system() == 'Linux'
75
76
77def is_macos():
78 return platform.system() == 'Darwin'
79
80
81def is_ppc64le():
82 return platform.machine() == 'ppc64le'
83
84
Jonathan Hseu008910f2017-08-25 14:01:05 -070085def is_cygwin():
86 return platform.system().startswith('CYGWIN_NT')
87
88
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070089def get_input(question):
90 try:
91 try:
92 answer = raw_input(question)
93 except NameError:
94 answer = input(question) # pylint: disable=bad-builtin
95 except EOFError:
96 answer = ''
97 return answer
98
99
100def symlink_force(target, link_name):
101 """Force symlink, equivalent of 'ln -sf'.
102
103 Args:
104 target: items to link to.
105 link_name: name of the link.
106 """
107 try:
108 os.symlink(target, link_name)
109 except OSError as e:
110 if e.errno == errno.EEXIST:
111 os.remove(link_name)
112 os.symlink(target, link_name)
113 else:
114 raise e
115
116
117def sed_in_place(filename, old, new):
118 """Replace old string with new string in file.
119
120 Args:
121 filename: string for filename.
122 old: string to replace.
123 new: new string to replace to.
124 """
125 with open(filename, 'r') as f:
126 filedata = f.read()
127 newdata = filedata.replace(old, new)
128 with open(filename, 'w') as f:
129 f.write(newdata)
130
131
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700132def write_to_bazelrc(line):
133 with open(_TF_BAZELRC, 'a') as f:
134 f.write(line + '\n')
135
136
137def write_action_env_to_bazelrc(var_name, var):
138 write_to_bazelrc('build --action_env %s="%s"' % (var_name, str(var)))
139
140
Jonathan Hseu008910f2017-08-25 14:01:05 -0700141def run_shell(cmd, allow_non_zero=False):
142 if allow_non_zero:
143 try:
144 output = subprocess.check_output(cmd)
145 except subprocess.CalledProcessError as e:
146 output = e.output
147 else:
148 output = subprocess.check_output(cmd)
149 return output.decode('UTF-8').strip()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700150
151
152def cygpath(path):
153 """Convert path from posix to windows."""
Martin Wicked57572e2017-09-02 19:21:45 -0700154 return os.path.abspath(path).replace('\\', '/')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700155
156
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700157def get_python_path(environ_cp, python_bin_path):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700158 """Get the python site package paths."""
159 python_paths = []
160 if environ_cp.get('PYTHONPATH'):
161 python_paths = environ_cp.get('PYTHONPATH').split(':')
162 try:
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700163 library_paths = run_shell([
164 python_bin_path, '-c',
165 'import site; print("\\n".join(site.getsitepackages()))'
166 ]).split('\n')
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700167 except subprocess.CalledProcessError:
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700168 library_paths = [
169 run_shell([
170 python_bin_path, '-c',
171 'from distutils.sysconfig import get_python_lib;'
172 'print(get_python_lib())'
173 ])
174 ]
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700175
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700176 all_paths = set(python_paths + library_paths)
177
178 paths = []
179 for path in all_paths:
180 if os.path.isdir(path):
181 paths.append(path)
182 return paths
183
184
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700185def get_python_major_version(python_bin_path):
186 """Get the python major version."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700187 return run_shell([python_bin_path, '-c', 'import sys; print(sys.version[0])'])
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700188
189
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700190def setup_python(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700191 """Setup python related env variables."""
192 # Get PYTHON_BIN_PATH, default is the current running python.
193 default_python_bin_path = sys.executable
194 ask_python_bin_path = ('Please specify the location of python. [Default is '
195 '%s]: ') % default_python_bin_path
196 while True:
197 python_bin_path = get_from_env_or_user_or_default(
198 environ_cp, 'PYTHON_BIN_PATH', ask_python_bin_path,
199 default_python_bin_path)
200 # Check if the path is valid
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700201 if os.path.isfile(python_bin_path) and os.access(python_bin_path, os.X_OK):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700202 break
203 elif not os.path.exists(python_bin_path):
204 print('Invalid python path: %s cannot be found.' % python_bin_path)
205 else:
206 print('%s is not executable. Is it the python binary?' % python_bin_path)
207 environ_cp['PYTHON_BIN_PATH'] = ''
208
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700209 # Convert python path to Windows style before checking lib and version
Martin Wicked57572e2017-09-02 19:21:45 -0700210 if is_windows() or is_cygwin():
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700211 python_bin_path = cygpath(python_bin_path)
212
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700213 # Get PYTHON_LIB_PATH
214 python_lib_path = environ_cp.get('PYTHON_LIB_PATH')
215 if not python_lib_path:
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700216 python_lib_paths = get_python_path(environ_cp, python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700217 if environ_cp.get('USE_DEFAULT_PYTHON_LIB_PATH') == '1':
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700218 python_lib_path = python_lib_paths[0]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700219 else:
Jonathan Hseu008910f2017-08-25 14:01:05 -0700220 print('Found possible Python library paths:\n %s' %
221 '\n '.join(python_lib_paths))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700222 default_python_lib_path = python_lib_paths[0]
223 python_lib_path = get_input(
Jonathan Hseu008910f2017-08-25 14:01:05 -0700224 'Please input the desired Python library path to use. '
225 'Default is [%s]\n' % python_lib_paths[0])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700226 if not python_lib_path:
227 python_lib_path = default_python_lib_path
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700228 environ_cp['PYTHON_LIB_PATH'] = python_lib_path
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700229
TensorFlower Gardener61a87202018-10-01 12:25:39 -0700230 _ = get_python_major_version(python_bin_path)
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700231
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700232 # Convert python path to Windows style before writing into bazel.rc
Martin Wicked57572e2017-09-02 19:21:45 -0700233 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700234 python_lib_path = cygpath(python_lib_path)
235
236 # Set-up env variables used by python_configure.bzl
237 write_action_env_to_bazelrc('PYTHON_BIN_PATH', python_bin_path)
238 write_action_env_to_bazelrc('PYTHON_LIB_PATH', python_lib_path)
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700239 write_to_bazelrc('build --python_path=\"%s"' % python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700240 environ_cp['PYTHON_BIN_PATH'] = python_bin_path
241
242 # Write tools/python_bin_path.sh
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700243 with open(
244 os.path.join(_TF_WORKSPACE_ROOT, 'tools', 'python_bin_path.sh'),
245 'w') as f:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700246 f.write('export PYTHON_BIN_PATH="%s"' % python_bin_path)
247
248
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -0700249def reset_tf_configure_bazelrc():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700250 """Reset file that contains customized config settings."""
251 open(_TF_BAZELRC, 'w').close()
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -0700252 bazelrc_path = os.path.join(_TF_WORKSPACE_ROOT, '.bazelrc')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700253
Shanqing Cai71445712018-03-12 19:33:52 -0700254 data = []
255 if os.path.exists(bazelrc_path):
256 with open(bazelrc_path, 'r') as f:
257 data = f.read().splitlines()
258 with open(bazelrc_path, 'w') as f:
259 for l in data:
260 if _TF_BAZELRC_FILENAME in l:
261 continue
262 f.write('%s\n' % l)
263 if is_windows():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700264 tf_bazelrc_path = _TF_BAZELRC.replace('\\', '/')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700265 else:
Shanqing Cai71445712018-03-12 19:33:52 -0700266 tf_bazelrc_path = _TF_BAZELRC
267 f.write('import %s\n' % tf_bazelrc_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700268
269
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700270def cleanup_makefile():
271 """Delete any leftover BUILD files from the Makefile build.
272
273 These files could interfere with Bazel parsing.
274 """
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700275 makefile_download_dir = os.path.join(_TF_WORKSPACE_ROOT, 'tensorflow',
276 'contrib', 'makefile', 'downloads')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700277 if os.path.isdir(makefile_download_dir):
278 for root, _, filenames in os.walk(makefile_download_dir):
279 for f in filenames:
280 if f.endswith('BUILD'):
281 os.remove(os.path.join(root, f))
282
283
284def get_var(environ_cp,
285 var_name,
286 query_item,
287 enabled_by_default,
288 question=None,
289 yes_reply=None,
290 no_reply=None):
291 """Get boolean input from user.
292
293 If var_name is not set in env, ask user to enable query_item or not. If the
294 response is empty, use the default.
295
296 Args:
297 environ_cp: copy of the os.environ.
298 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
299 query_item: string for feature related to the variable, e.g. "Hadoop File
300 System".
301 enabled_by_default: boolean for default behavior.
302 question: optional string for how to ask for user input.
Michael Cased90054e2018-02-07 14:36:00 -0800303 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700304 no_reply: optional string for reply when feature is disabled.
305
306 Returns:
307 boolean value of the variable.
Frank Chenc4ef9272018-01-10 11:36:52 -0800308
309 Raises:
310 UserInputError: if an environment variable is set, but it cannot be
311 interpreted as a boolean indicator, assume that the user has made a
312 scripting error, and will continue to provide invalid input.
313 Raise the error to avoid infinitely looping.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700314 """
315 if not question:
316 question = 'Do you wish to build TensorFlow with %s support?' % query_item
317 if not yes_reply:
318 yes_reply = '%s support will be enabled for TensorFlow.' % query_item
319 if not no_reply:
320 no_reply = 'No %s' % yes_reply
321
322 yes_reply += '\n'
323 no_reply += '\n'
324
325 if enabled_by_default:
326 question += ' [Y/n]: '
327 else:
328 question += ' [y/N]: '
329
330 var = environ_cp.get(var_name)
Frank Chenc4ef9272018-01-10 11:36:52 -0800331 if var is not None:
332 var_content = var.strip().lower()
333 true_strings = ('1', 't', 'true', 'y', 'yes')
334 false_strings = ('0', 'f', 'false', 'n', 'no')
335 if var_content in true_strings:
336 var = True
337 elif var_content in false_strings:
338 var = False
339 else:
340 raise UserInputError(
341 'Environment variable %s must be set as a boolean indicator.\n'
342 'The following are accepted as TRUE : %s.\n'
343 'The following are accepted as FALSE: %s.\n'
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700344 'Current value is %s.' % (var_name, ', '.join(true_strings),
345 ', '.join(false_strings), var))
Frank Chenc4ef9272018-01-10 11:36:52 -0800346
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700347 while var is None:
348 user_input_origin = get_input(question)
349 user_input = user_input_origin.strip().lower()
350 if user_input == 'y':
351 print(yes_reply)
352 var = True
353 elif user_input == 'n':
354 print(no_reply)
355 var = False
356 elif not user_input:
357 if enabled_by_default:
358 print(yes_reply)
359 var = True
360 else:
361 print(no_reply)
362 var = False
363 else:
364 print('Invalid selection: %s' % user_input_origin)
365 return var
366
367
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700368def set_build_var(environ_cp,
369 var_name,
370 query_item,
371 option_name,
372 enabled_by_default,
373 bazel_config_name=None):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700374 """Set if query_item will be enabled for the build.
375
376 Ask user if query_item will be enabled. Default is used if no input is given.
377 Set subprocess environment variable and write to .bazelrc if enabled.
378
379 Args:
380 environ_cp: copy of the os.environ.
381 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
382 query_item: string for feature related to the variable, e.g. "Hadoop File
383 System".
384 option_name: string for option to define in .bazelrc.
385 enabled_by_default: boolean for default behavior.
Michael Case98850a52017-09-14 13:35:57 -0700386 bazel_config_name: Name for Bazel --config argument to enable build feature.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700387 """
388
389 var = str(int(get_var(environ_cp, var_name, query_item, enabled_by_default)))
390 environ_cp[var_name] = var
391 if var == '1':
392 write_to_bazelrc('build --define %s=true' % option_name)
Michael Case98850a52017-09-14 13:35:57 -0700393 elif bazel_config_name is not None:
394 # TODO(mikecase): Migrate all users of configure.py to use --config Bazel
395 # options and not to set build configs through environment variables.
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700396 write_to_bazelrc(
397 'build:%s --define %s=true' % (bazel_config_name, option_name))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700398
399
400def set_action_env_var(environ_cp,
401 var_name,
402 query_item,
403 enabled_by_default,
404 question=None,
405 yes_reply=None,
406 no_reply=None):
407 """Set boolean action_env variable.
408
409 Ask user if query_item will be enabled. Default is used if no input is given.
410 Set environment variable and write to .bazelrc.
411
412 Args:
413 environ_cp: copy of the os.environ.
414 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
415 query_item: string for feature related to the variable, e.g. "Hadoop File
416 System".
417 enabled_by_default: boolean for default behavior.
418 question: optional string for how to ask for user input.
Michael Cased90054e2018-02-07 14:36:00 -0800419 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700420 no_reply: optional string for reply when feature is disabled.
421 """
422 var = int(
423 get_var(environ_cp, var_name, query_item, enabled_by_default, question,
424 yes_reply, no_reply))
425
426 write_action_env_to_bazelrc(var_name, var)
427 environ_cp[var_name] = str(var)
428
429
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700430def convert_version_to_int(version):
431 """Convert a version number to a integer that can be used to compare.
432
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700433 Version strings of the form X.YZ and X.Y.Z-xxxxx are supported. The
434 'xxxxx' part, for instance 'homebrew' on OS/X, is ignored.
435
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700436 Args:
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700437 version: a version to be converted
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700438
439 Returns:
440 An integer if converted successfully, otherwise return None.
441 """
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700442 version = version.split('-')[0]
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700443 version_segments = version.split('.')
444 for seg in version_segments:
445 if not seg.isdigit():
446 return None
447
448 version_str = ''.join(['%03d' % int(seg) for seg in version_segments])
449 return int(version_str)
450
451
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700452def check_bazel_version(min_version):
Yifei Fengdce9a492018-02-22 14:24:57 -0800453 """Check installed bazel version is at least min_version.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700454
455 Args:
456 min_version: string for minimum bazel version.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700457
458 Returns:
459 The bazel version detected.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700460 """
Jonathan Hseu008910f2017-08-25 14:01:05 -0700461 if which('bazel') is None:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700462 print('Cannot find bazel. Please install bazel.')
463 sys.exit(0)
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700464 curr_version = run_shell(
465 ['bazel', '--batch', '--bazelrc=/dev/null', 'version'])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700466
467 for line in curr_version.split('\n'):
468 if 'Build label: ' in line:
469 curr_version = line.split('Build label: ')[1]
470 break
471
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700472 min_version_int = convert_version_to_int(min_version)
473 curr_version_int = convert_version_to_int(curr_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700474
475 # Check if current bazel version can be detected properly.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700476 if not curr_version_int:
477 print('WARNING: current bazel installation is not a release version.')
478 print('Make sure you are running at least bazel %s' % min_version)
479 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700480
Michael Cased94271a2017-08-22 17:26:52 -0700481 print('You have bazel %s installed.' % curr_version)
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700482
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700483 if curr_version_int < min_version_int:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700484 print('Please upgrade your bazel installation to version %s or higher to '
485 'build TensorFlow!' % min_version)
486 sys.exit(0)
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700487 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700488
489
490def set_cc_opt_flags(environ_cp):
491 """Set up architecture-dependent optimization flags.
492
493 Also append CC optimization flags to bazel.rc..
494
495 Args:
496 environ_cp: copy of the os.environ.
497 """
498 if is_ppc64le():
499 # gcc on ppc64le does not support -march, use mcpu instead
500 default_cc_opt_flags = '-mcpu=native'
A. Unique TensorFlower1bba94a2018-04-04 15:45:20 -0700501 elif is_windows():
502 default_cc_opt_flags = '/arch:AVX'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700503 else:
504 default_cc_opt_flags = '-march=native'
505 question = ('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(environ_cp, 'CC_OPT_FLAGS',
509 question, default_cc_opt_flags)
510 for opt in cc_opt_flags.split():
Michael Case00177422017-11-10 13:14:03 -0800511 write_to_bazelrc('build:opt --copt=%s' % opt)
512 # It should be safe on the same build host.
A. Unique TensorFlower1bba94a2018-04-04 15:45:20 -0700513 if not is_ppc64le() and not is_windows():
Shanqing Cai71445712018-03-12 19:33:52 -0700514 write_to_bazelrc('build:opt --host_copt=-march=native')
Michael Casebb3355d2017-11-09 08:46:31 -0800515 write_to_bazelrc('build:opt --define with_default_optimizations=true')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700516
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700517
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700518def set_tf_cuda_clang(environ_cp):
519 """set TF_CUDA_CLANG action_env.
520
521 Args:
522 environ_cp: copy of the os.environ.
523 """
524 question = 'Do you want to use clang as CUDA compiler?'
525 yes_reply = 'Clang will be used as CUDA compiler.'
526 no_reply = 'nvcc will be used as CUDA compiler.'
527 set_action_env_var(
528 environ_cp,
529 'TF_CUDA_CLANG',
530 None,
531 False,
532 question=question,
533 yes_reply=yes_reply,
534 no_reply=no_reply)
535
536
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800537def set_tf_download_clang(environ_cp):
538 """Set TF_DOWNLOAD_CLANG action_env."""
Ilya Biryukov9e651e42018-03-22 05:33:42 -0700539 question = 'Do you wish to download a fresh release of clang? (Experimental)'
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800540 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)
550
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):
554 """Get var_name either from env, or user or default.
555
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 """
568 var = environ_cp.get(var_name)
569 if not var:
570 var = get_input(ask_for_var)
Michael Cased94271a2017-08-22 17:26:52 -0700571 print('\n')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700572 if not var:
573 var = var_default
574 return var
575
576
577def set_clang_cuda_compiler_path(environ_cp):
578 """Set CLANG_CUDA_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700579 default_clang_path = which('clang') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700580 ask_clang_path = ('Please specify which clang should be used as device and '
581 'host compiler. [Default is %s]: ') % default_clang_path
582
583 while True:
584 clang_cuda_compiler_path = get_from_env_or_user_or_default(
585 environ_cp, 'CLANG_CUDA_COMPILER_PATH', ask_clang_path,
586 default_clang_path)
587 if os.path.exists(clang_cuda_compiler_path):
588 break
589
590 # Reset and retry
591 print('Invalid clang path: %s cannot be found.' % clang_cuda_compiler_path)
592 environ_cp['CLANG_CUDA_COMPILER_PATH'] = ''
593
594 # Set CLANG_CUDA_COMPILER_PATH
595 environ_cp['CLANG_CUDA_COMPILER_PATH'] = clang_cuda_compiler_path
596 write_action_env_to_bazelrc('CLANG_CUDA_COMPILER_PATH',
597 clang_cuda_compiler_path)
598
599
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700600def prompt_loop_or_load_from_env(environ_cp,
601 var_name,
602 var_default,
603 ask_for_var,
604 check_success,
605 error_msg,
606 suppress_default_error=False,
607 n_ask_attempts=_DEFAULT_PROMPT_ASK_ATTEMPTS):
Austin Anderson6afface2017-12-05 11:59:17 -0800608 """Loop over user prompts for an ENV param until receiving a valid response.
609
610 For the env param var_name, read from the environment or verify user input
611 until receiving valid input. When done, set var_name in the environ_cp to its
612 new value.
613
614 Args:
615 environ_cp: (Dict) copy of the os.environ.
616 var_name: (String) string for name of environment variable, e.g. "TF_MYVAR".
617 var_default: (String) default value string.
618 ask_for_var: (String) string for how to ask for user input.
619 check_success: (Function) function that takes one argument and returns a
620 boolean. Should return True if the value provided is considered valid. May
621 contain a complex error message if error_msg does not provide enough
622 information. In that case, set suppress_default_error to True.
623 error_msg: (String) String with one and only one '%s'. Formatted with each
624 invalid response upon check_success(input) failure.
625 suppress_default_error: (Bool) Suppress the above error message in favor of
626 one from the check_success function.
627 n_ask_attempts: (Integer) Number of times to query for valid input before
628 raising an error and quitting.
629
630 Returns:
631 [String] The value of var_name after querying for input.
632
633 Raises:
634 UserInputError: if a query has been attempted n_ask_attempts times without
Frank Chenc4ef9272018-01-10 11:36:52 -0800635 success, assume that the user has made a scripting error, and will
636 continue to provide invalid input. Raise the error to avoid infinitely
637 looping.
Austin Anderson6afface2017-12-05 11:59:17 -0800638 """
639 default = environ_cp.get(var_name) or var_default
640 full_query = '%s [Default is %s]: ' % (
641 ask_for_var,
642 default,
643 )
644
645 for _ in range(n_ask_attempts):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700646 val = get_from_env_or_user_or_default(environ_cp, var_name, full_query,
Austin Anderson6afface2017-12-05 11:59:17 -0800647 default)
648 if check_success(val):
649 break
650 if not suppress_default_error:
651 print(error_msg % val)
652 environ_cp[var_name] = ''
653 else:
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700654 raise UserInputError(
655 'Invalid %s setting was provided %d times in a row. '
656 'Assuming to be a scripting mistake.' % (var_name, n_ask_attempts))
Austin Anderson6afface2017-12-05 11:59:17 -0800657
658 environ_cp[var_name] = val
659 return val
660
661
662def create_android_ndk_rule(environ_cp):
663 """Set ANDROID_NDK_HOME and write Android NDK WORKSPACE rule."""
664 if is_windows() or is_cygwin():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700665 default_ndk_path = cygpath(
666 '%s/Android/Sdk/ndk-bundle' % environ_cp['APPDATA'])
Austin Anderson6afface2017-12-05 11:59:17 -0800667 elif is_macos():
668 default_ndk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
669 else:
670 default_ndk_path = '%s/Android/Sdk/ndk-bundle' % environ_cp['HOME']
671
672 def valid_ndk_path(path):
673 return (os.path.exists(path) and
674 os.path.exists(os.path.join(path, 'source.properties')))
675
676 android_ndk_home_path = prompt_loop_or_load_from_env(
677 environ_cp,
678 var_name='ANDROID_NDK_HOME',
679 var_default=default_ndk_path,
680 ask_for_var='Please specify the home path of the Android NDK to use.',
681 check_success=valid_ndk_path,
682 error_msg=('The path %s or its child file "source.properties" '
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700683 'does not exist.'))
Michael Case51053502018-06-05 17:47:19 -0700684 write_action_env_to_bazelrc('ANDROID_NDK_HOME', android_ndk_home_path)
685 write_action_env_to_bazelrc('ANDROID_NDK_API_LEVEL',
686 check_ndk_level(android_ndk_home_path))
Austin Anderson6afface2017-12-05 11:59:17 -0800687
688
689def create_android_sdk_rule(environ_cp):
690 """Set Android variables and write Android SDK WORKSPACE rule."""
691 if is_windows() or is_cygwin():
692 default_sdk_path = cygpath('%s/Android/Sdk' % environ_cp['APPDATA'])
693 elif is_macos():
Shashi Shekharc0ff0cc2018-07-17 09:00:24 -0700694 default_sdk_path = '%s/library/Android/Sdk' % environ_cp['HOME']
Austin Anderson6afface2017-12-05 11:59:17 -0800695 else:
696 default_sdk_path = '%s/Android/Sdk' % environ_cp['HOME']
697
698 def valid_sdk_path(path):
699 return (os.path.exists(path) and
700 os.path.exists(os.path.join(path, 'platforms')) and
701 os.path.exists(os.path.join(path, 'build-tools')))
702
703 android_sdk_home_path = prompt_loop_or_load_from_env(
704 environ_cp,
705 var_name='ANDROID_SDK_HOME',
706 var_default=default_sdk_path,
707 ask_for_var='Please specify the home path of the Android SDK to use.',
708 check_success=valid_sdk_path,
709 error_msg=('Either %s does not exist, or it does not contain the '
710 'subdirectories "platforms" and "build-tools".'))
711
712 platforms = os.path.join(android_sdk_home_path, 'platforms')
713 api_levels = sorted(os.listdir(platforms))
714 api_levels = [x.replace('android-', '') for x in api_levels]
715
716 def valid_api_level(api_level):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700717 return os.path.exists(
718 os.path.join(android_sdk_home_path, 'platforms',
719 'android-' + api_level))
Austin Anderson6afface2017-12-05 11:59:17 -0800720
721 android_api_level = prompt_loop_or_load_from_env(
722 environ_cp,
723 var_name='ANDROID_API_LEVEL',
724 var_default=api_levels[-1],
725 ask_for_var=('Please specify the Android SDK API level to use. '
726 '[Available levels: %s]') % api_levels,
727 check_success=valid_api_level,
728 error_msg='Android-%s is not present in the SDK path.')
729
730 build_tools = os.path.join(android_sdk_home_path, 'build-tools')
731 versions = sorted(os.listdir(build_tools))
732
733 def valid_build_tools(version):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700734 return os.path.exists(
735 os.path.join(android_sdk_home_path, 'build-tools', version))
Austin Anderson6afface2017-12-05 11:59:17 -0800736
737 android_build_tools_version = prompt_loop_or_load_from_env(
738 environ_cp,
739 var_name='ANDROID_BUILD_TOOLS_VERSION',
740 var_default=versions[-1],
741 ask_for_var=('Please specify an Android build tools version to use. '
742 '[Available versions: %s]') % versions,
743 check_success=valid_build_tools,
744 error_msg=('The selected SDK does not have build-tools version %s '
745 'available.'))
746
Michael Case51053502018-06-05 17:47:19 -0700747 write_action_env_to_bazelrc('ANDROID_BUILD_TOOLS_VERSION',
748 android_build_tools_version)
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700749 write_action_env_to_bazelrc('ANDROID_SDK_API_LEVEL', android_api_level)
750 write_action_env_to_bazelrc('ANDROID_SDK_HOME', android_sdk_home_path)
Austin Anderson6afface2017-12-05 11:59:17 -0800751
752
753def check_ndk_level(android_ndk_home_path):
754 """Check the revision number of an Android NDK path."""
755 properties_path = '%s/source.properties' % android_ndk_home_path
756 if is_windows() or is_cygwin():
757 properties_path = cygpath(properties_path)
758 with open(properties_path, 'r') as f:
759 filedata = f.read()
760
761 revision = re.search(r'Pkg.Revision = (\d+)', filedata)
762 if revision:
Michael Case51053502018-06-05 17:47:19 -0700763 ndk_api_level = revision.group(1)
764 else:
765 raise Exception('Unable to parse NDK revision.')
766 if int(ndk_api_level) not in _SUPPORTED_ANDROID_NDK_VERSIONS:
767 print('WARNING: The API level of the NDK in %s is %s, which is not '
768 'supported by Bazel (officially supported versions: %s). Please use '
769 'another version. Compiling Android targets may result in confusing '
770 'errors.\n' % (android_ndk_home_path, ndk_api_level,
771 _SUPPORTED_ANDROID_NDK_VERSIONS))
772 return ndk_api_level
Austin Anderson6afface2017-12-05 11:59:17 -0800773
774
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700775def set_gcc_host_compiler_path(environ_cp):
776 """Set GCC_HOST_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700777 default_gcc_host_compiler_path = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700778 cuda_bin_symlink = '%s/bin/gcc' % environ_cp.get('CUDA_TOOLKIT_PATH')
779
780 if os.path.islink(cuda_bin_symlink):
781 # os.readlink is only available in linux
Jonathan Hseu008910f2017-08-25 14:01:05 -0700782 default_gcc_host_compiler_path = os.path.realpath(cuda_bin_symlink)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700783
Austin Anderson6afface2017-12-05 11:59:17 -0800784 gcc_host_compiler_path = prompt_loop_or_load_from_env(
785 environ_cp,
786 var_name='GCC_HOST_COMPILER_PATH',
787 var_default=default_gcc_host_compiler_path,
788 ask_for_var=
789 'Please specify which gcc should be used by nvcc as the host compiler.',
790 check_success=os.path.exists,
791 error_msg='Invalid gcc path. %s cannot be found.',
792 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700793
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700794 write_action_env_to_bazelrc('GCC_HOST_COMPILER_PATH', gcc_host_compiler_path)
795
796
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800797def reformat_version_sequence(version_str, sequence_count):
798 """Reformat the version string to have the given number of sequences.
799
800 For example:
801 Given (7, 2) -> 7.0
802 (7.0.1, 2) -> 7.0
803 (5, 1) -> 5
804 (5.0.3.2, 1) -> 5
805
806 Args:
807 version_str: String, the version string.
808 sequence_count: int, an integer.
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700809
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800810 Returns:
811 string, reformatted version string.
812 """
813 v = version_str.split('.')
814 if len(v) < sequence_count:
815 v = v + (['0'] * (sequence_count - len(v)))
816
817 return '.'.join(v[:sequence_count])
818
819
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700820def set_tf_cuda_version(environ_cp):
821 """Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION."""
822 ask_cuda_version = (
A. Unique TensorFlowerb15500b2018-05-08 12:04:38 -0700823 'Please specify the CUDA SDK version you want to use. '
824 '[Leave empty to default to CUDA %s]: ') % _DEFAULT_CUDA_VERSION
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700825
Austin Andersonf9a88f82017-12-13 11:49:40 -0800826 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700827 # Configure the Cuda SDK version to use.
828 tf_cuda_version = get_from_env_or_user_or_default(
829 environ_cp, 'TF_CUDA_VERSION', ask_cuda_version, _DEFAULT_CUDA_VERSION)
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800830 tf_cuda_version = reformat_version_sequence(str(tf_cuda_version), 2)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700831
832 # Find out where the CUDA toolkit is installed
833 default_cuda_path = _DEFAULT_CUDA_PATH
Martin Wicked57572e2017-09-02 19:21:45 -0700834 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700835 default_cuda_path = cygpath(
836 environ_cp.get('CUDA_PATH', _DEFAULT_CUDA_PATH_WIN))
837 elif is_linux():
838 # If the default doesn't exist, try an alternative default.
839 if (not os.path.exists(default_cuda_path)
840 ) and os.path.exists(_DEFAULT_CUDA_PATH_LINUX):
841 default_cuda_path = _DEFAULT_CUDA_PATH_LINUX
842 ask_cuda_path = ('Please specify the location where CUDA %s toolkit is'
843 ' installed. Refer to README.md for more details. '
844 '[Default is %s]: ') % (tf_cuda_version, default_cuda_path)
845 cuda_toolkit_path = get_from_env_or_user_or_default(
846 environ_cp, 'CUDA_TOOLKIT_PATH', ask_cuda_path, default_cuda_path)
A. Unique TensorFlower02f17fe2018-07-07 06:59:19 -0700847 if is_windows() or is_cygwin():
848 cuda_toolkit_path = cygpath(cuda_toolkit_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700849
850 if is_windows():
Niall Moranb7d97e82018-08-09 00:29:49 +0100851 cuda_rt_lib_paths = ['lib/x64/cudart.lib']
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700852 elif is_linux():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700853 cuda_rt_lib_paths = [
854 '%s/libcudart.so.%s' % (x, tf_cuda_version) for x in [
855 'lib64',
856 'lib/powerpc64le-linux-gnu',
857 'lib/x86_64-linux-gnu',
858 ]
859 ]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700860 elif is_macos():
Niall Moranb7d97e82018-08-09 00:29:49 +0100861 cuda_rt_lib_paths = ['lib/libcudart.%s.dylib' % tf_cuda_version]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700862
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700863 cuda_toolkit_paths_full = [
864 os.path.join(cuda_toolkit_path, x) for x in cuda_rt_lib_paths
865 ]
Niall Moranb7d97e82018-08-09 00:29:49 +0100866 if any([os.path.exists(x) for x in cuda_toolkit_paths_full]):
Yifei Feng5198cb82018-08-17 13:53:06 -0700867 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700868
869 # Reset and retry
870 print('Invalid path to CUDA %s toolkit. %s cannot be found' %
hellcom9a13fc32018-09-12 10:58:24 +0300871 (tf_cuda_version, cuda_toolkit_paths_full))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700872 environ_cp['TF_CUDA_VERSION'] = ''
873 environ_cp['CUDA_TOOLKIT_PATH'] = ''
874
Austin Andersonf9a88f82017-12-13 11:49:40 -0800875 else:
876 raise UserInputError('Invalid TF_CUDA_SETTING setting was provided %d '
877 'times in a row. Assuming to be a scripting mistake.' %
878 _DEFAULT_PROMPT_ASK_ATTEMPTS)
879
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700880 # Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION
881 environ_cp['CUDA_TOOLKIT_PATH'] = cuda_toolkit_path
882 write_action_env_to_bazelrc('CUDA_TOOLKIT_PATH', cuda_toolkit_path)
883 environ_cp['TF_CUDA_VERSION'] = tf_cuda_version
884 write_action_env_to_bazelrc('TF_CUDA_VERSION', tf_cuda_version)
885
886
Yifei Fengb1d8c592017-11-22 13:42:21 -0800887def set_tf_cudnn_version(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700888 """Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION."""
889 ask_cudnn_version = (
Jonathan Hseu008910f2017-08-25 14:01:05 -0700890 'Please specify the cuDNN version you want to use. '
A. Unique TensorFlower44acd832018-10-01 13:42:40 -0700891 '[Leave empty to default to cuDNN %s]: ') % _DEFAULT_CUDNN_VERSION
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700892
Austin Andersonf9a88f82017-12-13 11:49:40 -0800893 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700894 tf_cudnn_version = get_from_env_or_user_or_default(
895 environ_cp, 'TF_CUDNN_VERSION', ask_cudnn_version,
896 _DEFAULT_CUDNN_VERSION)
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800897 tf_cudnn_version = reformat_version_sequence(str(tf_cudnn_version), 1)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700898
899 default_cudnn_path = environ_cp.get('CUDA_TOOLKIT_PATH')
900 ask_cudnn_path = (r'Please specify the location where cuDNN %s library is '
901 'installed. Refer to README.md for more details. [Default'
A. Unique TensorFlower1b212352018-07-19 13:48:50 -0700902 ' is %s]: ') % (tf_cudnn_version, default_cudnn_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700903 cudnn_install_path = get_from_env_or_user_or_default(
904 environ_cp, 'CUDNN_INSTALL_PATH', ask_cudnn_path, default_cudnn_path)
905
906 # Result returned from "read" will be used unexpanded. That make "~"
907 # unusable. Going through one more level of expansion to handle that.
908 cudnn_install_path = os.path.realpath(
909 os.path.expanduser(cudnn_install_path))
Martin Wicked57572e2017-09-02 19:21:45 -0700910 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700911 cudnn_install_path = cygpath(cudnn_install_path)
912
913 if is_windows():
914 cuda_dnn_lib_path = 'lib/x64/cudnn.lib'
915 cuda_dnn_lib_alt_path = 'lib/x64/cudnn.lib'
916 elif is_linux():
917 cuda_dnn_lib_path = 'lib64/libcudnn.so.%s' % tf_cudnn_version
918 cuda_dnn_lib_alt_path = 'libcudnn.so.%s' % tf_cudnn_version
919 elif is_macos():
920 cuda_dnn_lib_path = 'lib/libcudnn.%s.dylib' % tf_cudnn_version
921 cuda_dnn_lib_alt_path = 'libcudnn.%s.dylib' % tf_cudnn_version
922
923 cuda_dnn_lib_path_full = os.path.join(cudnn_install_path, cuda_dnn_lib_path)
924 cuda_dnn_lib_alt_path_full = os.path.join(cudnn_install_path,
925 cuda_dnn_lib_alt_path)
926 if os.path.exists(cuda_dnn_lib_path_full) or os.path.exists(
927 cuda_dnn_lib_alt_path_full):
928 break
929
930 # Try another alternative for Linux
931 if is_linux():
Jonathan Hseu008910f2017-08-25 14:01:05 -0700932 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
933 cudnn_path_from_ldconfig = run_shell([ldconfig_bin, '-p'])
934 cudnn_path_from_ldconfig = re.search('.*libcudnn.so .* => (.*)',
A. Unique TensorFlowere7223582017-09-06 17:57:04 -0700935 cudnn_path_from_ldconfig)
936 if cudnn_path_from_ldconfig:
937 cudnn_path_from_ldconfig = cudnn_path_from_ldconfig.group(1)
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700938 if os.path.exists(
939 '%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version)):
A. Unique TensorFlowere7223582017-09-06 17:57:04 -0700940 cudnn_install_path = os.path.dirname(cudnn_path_from_ldconfig)
941 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700942
943 # Reset and Retry
944 print(
945 'Invalid path to cuDNN %s toolkit. None of the following files can be '
946 'found:' % tf_cudnn_version)
947 print(cuda_dnn_lib_path_full)
948 print(cuda_dnn_lib_alt_path_full)
949 if is_linux():
950 print('%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version))
951
952 environ_cp['TF_CUDNN_VERSION'] = ''
Austin Andersonf9a88f82017-12-13 11:49:40 -0800953 else:
954 raise UserInputError('Invalid TF_CUDNN setting was provided %d '
955 'times in a row. Assuming to be a scripting mistake.' %
956 _DEFAULT_PROMPT_ASK_ATTEMPTS)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700957
958 # Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION
959 environ_cp['CUDNN_INSTALL_PATH'] = cudnn_install_path
960 write_action_env_to_bazelrc('CUDNN_INSTALL_PATH', cudnn_install_path)
961 environ_cp['TF_CUDNN_VERSION'] = tf_cudnn_version
962 write_action_env_to_bazelrc('TF_CUDNN_VERSION', tf_cudnn_version)
963
964
Mingxing Tan1e7b0e42018-06-28 19:13:20 -0700965def is_cuda_compatible(lib, cuda_ver, cudnn_ver):
966 """Check compatibility between given library and cudnn/cudart libraries."""
967 ldd_bin = which('ldd') or '/usr/bin/ldd'
968 ldd_out = run_shell([ldd_bin, lib], True)
969 ldd_out = ldd_out.split(os.linesep)
970 cudnn_pattern = re.compile('.*libcudnn.so\\.?(.*) =>.*$')
971 cuda_pattern = re.compile('.*libcudart.so\\.?(.*) =>.*$')
972 cudnn = None
973 cudart = None
974 cudnn_ok = True # assume no cudnn dependency by default
975 cuda_ok = True # assume no cuda dependency by default
976 for line in ldd_out:
977 if 'libcudnn.so' in line:
978 cudnn = cudnn_pattern.search(line)
979 cudnn_ok = False
980 elif 'libcudart.so' in line:
981 cudart = cuda_pattern.search(line)
982 cuda_ok = False
983 if cudnn and len(cudnn.group(1)):
984 cudnn = convert_version_to_int(cudnn.group(1))
985 if cudart and len(cudart.group(1)):
986 cudart = convert_version_to_int(cudart.group(1))
987 if cudnn is not None:
988 cudnn_ok = (cudnn == cudnn_ver)
989 if cudart is not None:
990 cuda_ok = (cudart == cuda_ver)
991 return cudnn_ok and cuda_ok
992
993
Guangda Lai76f69382018-01-25 23:59:19 -0800994def set_tf_tensorrt_install_path(environ_cp):
995 """Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION.
996
997 Adapted from code contributed by Sami Kama (https://github.com/samikama).
998
999 Args:
1000 environ_cp: copy of the os.environ.
1001
1002 Raises:
1003 ValueError: if this method was called under non-Linux platform.
1004 UserInputError: if user has provided invalid input multiple times.
1005 """
1006 if not is_linux():
1007 raise ValueError('Currently TensorRT is only supported on Linux platform.')
1008
1009 # Ask user whether to add TensorRT support.
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001010 if str(int(get_var(environ_cp, 'TF_NEED_TENSORRT', 'TensorRT',
1011 False))) != '1':
Guangda Lai76f69382018-01-25 23:59:19 -08001012 return
1013
1014 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
1015 ask_tensorrt_path = (r'Please specify the location where TensorRT is '
1016 'installed. [Default is %s]:') % (
1017 _DEFAULT_TENSORRT_PATH_LINUX)
1018 trt_install_path = get_from_env_or_user_or_default(
1019 environ_cp, 'TENSORRT_INSTALL_PATH', ask_tensorrt_path,
1020 _DEFAULT_TENSORRT_PATH_LINUX)
1021
1022 # Result returned from "read" will be used unexpanded. That make "~"
1023 # unusable. Going through one more level of expansion to handle that.
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001024 trt_install_path = os.path.realpath(os.path.expanduser(trt_install_path))
Guangda Lai76f69382018-01-25 23:59:19 -08001025
1026 def find_libs(search_path):
1027 """Search for libnvinfer.so in "search_path"."""
1028 fl = set()
1029 if os.path.exists(search_path) and os.path.isdir(search_path):
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001030 fl.update([
1031 os.path.realpath(os.path.join(search_path, x))
1032 for x in os.listdir(search_path)
1033 if 'libnvinfer.so' in x
1034 ])
Guangda Lai76f69382018-01-25 23:59:19 -08001035 return fl
1036
1037 possible_files = find_libs(trt_install_path)
1038 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib')))
1039 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib64')))
Guangda Lai76f69382018-01-25 23:59:19 -08001040 cuda_ver = convert_version_to_int(environ_cp['TF_CUDA_VERSION'])
1041 cudnn_ver = convert_version_to_int(environ_cp['TF_CUDNN_VERSION'])
1042 nvinfer_pattern = re.compile('.*libnvinfer.so.?(.*)$')
1043 highest_ver = [0, None, None]
1044
1045 for lib_file in possible_files:
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001046 if is_cuda_compatible(lib_file, cuda_ver, cudnn_ver):
Jacques Pienaar2d0531d2018-03-21 12:07:51 -07001047 matches = nvinfer_pattern.search(lib_file)
TensorFlower Gardener61a87202018-10-01 12:25:39 -07001048 if not matches.groups():
Jacques Pienaar2d0531d2018-03-21 12:07:51 -07001049 continue
1050 ver_str = matches.group(1)
Guangda Lai76f69382018-01-25 23:59:19 -08001051 ver = convert_version_to_int(ver_str) if len(ver_str) else 0
1052 if ver > highest_ver[0]:
1053 highest_ver = [ver, ver_str, lib_file]
1054 if highest_ver[1] is not None:
1055 trt_install_path = os.path.dirname(highest_ver[2])
1056 tf_tensorrt_version = highest_ver[1]
1057 break
1058
1059 # Try another alternative from ldconfig.
1060 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
1061 ldconfig_output = run_shell([ldconfig_bin, '-p'])
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001062 search_result = re.search('.*libnvinfer.so\\.?([0-9.]*).* => (.*)',
1063 ldconfig_output)
Guangda Lai76f69382018-01-25 23:59:19 -08001064 if search_result:
1065 libnvinfer_path_from_ldconfig = search_result.group(2)
1066 if os.path.exists(libnvinfer_path_from_ldconfig):
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001067 if is_cuda_compatible(libnvinfer_path_from_ldconfig, cuda_ver,
1068 cudnn_ver):
Guangda Lai76f69382018-01-25 23:59:19 -08001069 trt_install_path = os.path.dirname(libnvinfer_path_from_ldconfig)
1070 tf_tensorrt_version = search_result.group(1)
1071 break
1072
1073 # Reset and Retry
Yifei Fengdce9a492018-02-22 14:24:57 -08001074 if possible_files:
1075 print('TensorRT libraries found in one the following directories',
1076 'are not compatible with selected cuda and cudnn installations')
1077 print(trt_install_path)
1078 print(os.path.join(trt_install_path, 'lib'))
1079 print(os.path.join(trt_install_path, 'lib64'))
1080 if search_result:
1081 print(libnvinfer_path_from_ldconfig)
1082 else:
1083 print(
1084 'Invalid path to TensorRT. None of the following files can be found:')
1085 print(trt_install_path)
1086 print(os.path.join(trt_install_path, 'lib'))
1087 print(os.path.join(trt_install_path, 'lib64'))
1088 if search_result:
1089 print(libnvinfer_path_from_ldconfig)
Guangda Lai76f69382018-01-25 23:59:19 -08001090
1091 else:
1092 raise UserInputError('Invalid TF_TENSORRT setting was provided %d '
1093 'times in a row. Assuming to be a scripting mistake.' %
1094 _DEFAULT_PROMPT_ASK_ATTEMPTS)
1095
1096 # Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION
1097 environ_cp['TENSORRT_INSTALL_PATH'] = trt_install_path
1098 write_action_env_to_bazelrc('TENSORRT_INSTALL_PATH', trt_install_path)
1099 environ_cp['TF_TENSORRT_VERSION'] = tf_tensorrt_version
1100 write_action_env_to_bazelrc('TF_TENSORRT_VERSION', tf_tensorrt_version)
1101
1102
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001103def set_tf_nccl_install_path(environ_cp):
Jason Furmanek7c234152018-09-26 04:44:12 +00001104 """Set NCCL_INSTALL_PATH, NCCL_HDR_PATH and TF_NCCL_VERSION.
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001105
1106 Args:
1107 environ_cp: copy of the os.environ.
1108
1109 Raises:
1110 ValueError: if this method was called under non-Linux platform.
1111 UserInputError: if user has provided invalid input multiple times.
1112 """
1113 if not is_linux():
1114 raise ValueError('Currently NCCL is only supported on Linux platforms.')
1115
1116 ask_nccl_version = (
Smit Hinsu63e6b9b2018-07-13 12:46:24 -07001117 'Please specify the NCCL version you want to use. If NCCL %s is not '
1118 'installed, then you can use version 1.3 that can be fetched '
1119 'automatically but it may have worse performance with multiple GPUs. '
1120 '[Default is %s]: ') % (_DEFAULT_NCCL_VERSION, _DEFAULT_NCCL_VERSION)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001121
1122 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
1123 tf_nccl_version = get_from_env_or_user_or_default(
1124 environ_cp, 'TF_NCCL_VERSION', ask_nccl_version, _DEFAULT_NCCL_VERSION)
1125 tf_nccl_version = reformat_version_sequence(str(tf_nccl_version), 1)
1126
1127 if tf_nccl_version == '1':
1128 break # No need to get install path, NCCL 1 is a GitHub repo.
1129
Jason Furmanek7c234152018-09-26 04:44:12 +00001130 # Look with ldconfig first if we can find the library in paths
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001131 # like /usr/lib/x86_64-linux-gnu and the header file in the corresponding
1132 # include directory. This is where the NCCL .deb packages install them.
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001133
Jason Furmanek7c234152018-09-26 04:44:12 +00001134 # First check to see if NCCL is in the ldconfig.
1135 # If its found, use that location.
1136 if is_linux():
1137 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
1138 nccl2_path_from_ldconfig = run_shell([ldconfig_bin, '-p'])
1139 nccl2_path_from_ldconfig = re.search('.*libnccl.so .* => (.*)',
1140 nccl2_path_from_ldconfig)
1141 if nccl2_path_from_ldconfig:
1142 nccl2_path_from_ldconfig = nccl2_path_from_ldconfig.group(1)
1143 if os.path.exists('%s.%s' % (nccl2_path_from_ldconfig, tf_nccl_version)):
1144 nccl_install_path = os.path.dirname(nccl2_path_from_ldconfig)
1145 print('NCCL libraries found in ' + nccl2_path_from_ldconfig)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001146
Jason Furmanek7c234152018-09-26 04:44:12 +00001147 # Check if this is the main system lib location
1148 if re.search('.*linux-gnu', nccl_install_path):
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001149 trunc_nccl_install_path = '/usr'
1150 print('This looks like a system path.')
Jason Furmanek7c234152018-09-26 04:44:12 +00001151 else:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001152 trunc_nccl_install_path = nccl_install_path + '/..'
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001153
Jason Furmanek7c234152018-09-26 04:44:12 +00001154 # Look for header
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001155 nccl_hdr_path = trunc_nccl_install_path + '/include'
1156 print('Assuming NCCL header path is ' + nccl_hdr_path)
1157 if os.path.exists(nccl_hdr_path + '/nccl.h'):
Jason Furmanek7c234152018-09-26 04:44:12 +00001158 # Set NCCL_INSTALL_PATH
1159 environ_cp['NCCL_INSTALL_PATH'] = nccl_install_path
1160 write_action_env_to_bazelrc('NCCL_INSTALL_PATH', nccl_install_path)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001161
Jason Furmanek7c234152018-09-26 04:44:12 +00001162 # Set NCCL_HDR_PATH
1163 environ_cp['NCCL_HDR_PATH'] = nccl_hdr_path
1164 write_action_env_to_bazelrc('NCCL_HDR_PATH', nccl_hdr_path)
1165 break
1166 else:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001167 print(
1168 'The header for NCCL2 cannot be found. Please install the libnccl-dev package.'
1169 )
Jason Furmanek7c234152018-09-26 04:44:12 +00001170 else:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001171 print('NCCL2 is listed by ldconfig but the library is not found. '
1172 'Your ldconfig is out of date. Please run sudo ldconfig.')
Jason Furmanek7c234152018-09-26 04:44:12 +00001173 else:
1174 # NCCL is not found in ldconfig. Ask the user for the location.
1175 default_nccl_path = environ_cp.get('CUDA_TOOLKIT_PATH')
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001176 ask_nccl_path = (
1177 r'Please specify the location where NCCL %s library is '
1178 'installed. Refer to README.md for more details. [Default '
1179 'is %s]:') % (tf_nccl_version, default_nccl_path)
Jason Furmanek7c234152018-09-26 04:44:12 +00001180 nccl_install_path = get_from_env_or_user_or_default(
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001181 environ_cp, 'NCCL_INSTALL_PATH', ask_nccl_path, default_nccl_path)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001182
Jason Furmanek7c234152018-09-26 04:44:12 +00001183 # Result returned from "read" will be used unexpanded. That make "~"
1184 # unusable. Going through one more level of expansion to handle that.
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001185 nccl_install_path = os.path.realpath(
1186 os.path.expanduser(nccl_install_path))
Jason Furmanek7c234152018-09-26 04:44:12 +00001187 if is_windows() or is_cygwin():
1188 nccl_install_path = cygpath(nccl_install_path)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001189
Jason Furmanek7c234152018-09-26 04:44:12 +00001190 if is_windows():
1191 nccl_lib_path = 'lib/x64/nccl.lib'
1192 elif is_linux():
1193 nccl_lib_filename = 'libnccl.so.%s' % tf_nccl_version
1194 nccl_lpath = '%s/lib/%s' % (nccl_install_path, nccl_lib_filename)
1195 if not os.path.exists(nccl_lpath):
1196 for relative_path in NCCL_LIB_PATHS:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001197 path = '%s/%s%s' % (nccl_install_path, relative_path,
1198 nccl_lib_filename)
Jason Furmanek7c234152018-09-26 04:44:12 +00001199 if os.path.exists(path):
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001200 print('NCCL found at ' + path)
Jason Furmanek7c234152018-09-26 04:44:12 +00001201 nccl_lib_path = path
1202 break
1203 else:
1204 nccl_lib_path = nccl_lpath
1205 elif is_macos():
1206 nccl_lib_path = 'lib/libnccl.%s.dylib' % tf_nccl_version
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001207
Jason Furmanek7c234152018-09-26 04:44:12 +00001208 nccl_lib_path = os.path.join(nccl_install_path, nccl_lib_path)
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001209 nccl_hdr_path = os.path.join(
1210 os.path.dirname(nccl_lib_path), '../include/nccl.h')
1211 print('Assuming NCCL header path is ' + nccl_hdr_path)
Jason Furmanek7c234152018-09-26 04:44:12 +00001212 if os.path.exists(nccl_lib_path) and os.path.exists(nccl_hdr_path):
1213 # Set NCCL_INSTALL_PATH
1214 environ_cp['NCCL_INSTALL_PATH'] = os.path.dirname(nccl_lib_path)
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001215 write_action_env_to_bazelrc('NCCL_INSTALL_PATH',
1216 os.path.dirname(nccl_lib_path))
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001217
Jason Furmanek7c234152018-09-26 04:44:12 +00001218 # Set NCCL_HDR_PATH
1219 environ_cp['NCCL_HDR_PATH'] = os.path.dirname(nccl_hdr_path)
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001220 write_action_env_to_bazelrc('NCCL_HDR_PATH',
1221 os.path.dirname(nccl_hdr_path))
Jason Furmanek7c234152018-09-26 04:44:12 +00001222 break
1223
1224 # Reset and Retry
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001225 print(
1226 'Invalid path to NCCL %s toolkit, %s or %s not found. Please use the '
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001227 'O/S agnostic package of NCCL 2' % (tf_nccl_version, nccl_lib_path,
1228 nccl_hdr_path))
1229
Jason Furmanek7c234152018-09-26 04:44:12 +00001230 environ_cp['TF_NCCL_VERSION'] = ''
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001231 else:
1232 raise UserInputError('Invalid TF_NCCL setting was provided %d '
1233 'times in a row. Assuming to be a scripting mistake.' %
1234 _DEFAULT_PROMPT_ASK_ATTEMPTS)
1235
1236 # Set TF_NCCL_VERSION
1237 environ_cp['TF_NCCL_VERSION'] = tf_nccl_version
1238 write_action_env_to_bazelrc('TF_NCCL_VERSION', tf_nccl_version)
1239
1240
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001241def get_native_cuda_compute_capabilities(environ_cp):
1242 """Get native cuda compute capabilities.
1243
1244 Args:
1245 environ_cp: copy of the os.environ.
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001246
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001247 Returns:
1248 string of native cuda compute capabilities, separated by comma.
1249 """
1250 device_query_bin = os.path.join(
1251 environ_cp.get('CUDA_TOOLKIT_PATH'), 'extras/demo_suite/deviceQuery')
Jonathan Hseu008910f2017-08-25 14:01:05 -07001252 if os.path.isfile(device_query_bin) and os.access(device_query_bin, os.X_OK):
1253 try:
1254 output = run_shell(device_query_bin).split('\n')
1255 pattern = re.compile('[0-9]*\\.[0-9]*')
1256 output = [pattern.search(x) for x in output if 'Capability' in x]
1257 output = ','.join(x.group() for x in output if x is not None)
1258 except subprocess.CalledProcessError:
1259 output = ''
1260 else:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001261 output = ''
1262 return output
1263
1264
1265def set_tf_cuda_compute_capabilities(environ_cp):
1266 """Set TF_CUDA_COMPUTE_CAPABILITIES."""
1267 while True:
1268 native_cuda_compute_capabilities = get_native_cuda_compute_capabilities(
1269 environ_cp)
1270 if not native_cuda_compute_capabilities:
1271 default_cuda_compute_capabilities = _DEFAULT_CUDA_COMPUTE_CAPABILITIES
1272 else:
1273 default_cuda_compute_capabilities = native_cuda_compute_capabilities
1274
1275 ask_cuda_compute_capabilities = (
1276 'Please specify a list of comma-separated '
1277 'Cuda compute capabilities you want to '
1278 'build with.\nYou can find the compute '
1279 'capability of your device at: '
1280 'https://developer.nvidia.com/cuda-gpus.\nPlease'
1281 ' note that each additional compute '
1282 'capability significantly increases your '
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001283 'build time and binary size. [Default is: %s]: ' %
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001284 default_cuda_compute_capabilities)
1285 tf_cuda_compute_capabilities = get_from_env_or_user_or_default(
1286 environ_cp, 'TF_CUDA_COMPUTE_CAPABILITIES',
1287 ask_cuda_compute_capabilities, default_cuda_compute_capabilities)
1288 # Check whether all capabilities from the input is valid
1289 all_valid = True
Maciejd0f5bc12018-04-30 22:30:58 -05001290 # Remove all whitespace characters before splitting the string
Michael Case51053502018-06-05 17:47:19 -07001291 # that users may insert by accident, as this will result in error
Maciejd0f5bc12018-04-30 22:30:58 -05001292 tf_cuda_compute_capabilities = ''.join(tf_cuda_compute_capabilities.split())
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001293 for compute_capability in tf_cuda_compute_capabilities.split(','):
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001294 m = re.match('[0-9]+.[0-9]+', compute_capability)
1295 if not m:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001296 print('Invalid compute capability: ' % compute_capability)
1297 all_valid = False
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001298 else:
1299 ver = int(m.group(0).split('.')[0])
1300 if ver < 3:
1301 print('Only compute capabilities 3.0 or higher are supported.')
1302 all_valid = False
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001303
1304 if all_valid:
1305 break
1306
1307 # Reset and Retry
1308 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = ''
1309
1310 # Set TF_CUDA_COMPUTE_CAPABILITIES
1311 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = tf_cuda_compute_capabilities
1312 write_action_env_to_bazelrc('TF_CUDA_COMPUTE_CAPABILITIES',
1313 tf_cuda_compute_capabilities)
1314
1315
1316def set_other_cuda_vars(environ_cp):
1317 """Set other CUDA related variables."""
A. Unique TensorFlowerab391982018-07-11 04:52:49 -07001318 # If CUDA is enabled, always use GPU during build and test.
1319 if environ_cp.get('TF_CUDA_CLANG') == '1':
1320 write_to_bazelrc('build --config=cuda_clang')
1321 write_to_bazelrc('test --config=cuda_clang')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001322 else:
A. Unique TensorFlowerab391982018-07-11 04:52:49 -07001323 write_to_bazelrc('build --config=cuda')
1324 write_to_bazelrc('test --config=cuda')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001325
1326
1327def set_host_cxx_compiler(environ_cp):
1328 """Set HOST_CXX_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001329 default_cxx_host_compiler = which('g++') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001330
Austin Anderson6afface2017-12-05 11:59:17 -08001331 host_cxx_compiler = prompt_loop_or_load_from_env(
1332 environ_cp,
1333 var_name='HOST_CXX_COMPILER',
1334 var_default=default_cxx_host_compiler,
1335 ask_for_var=('Please specify which C++ compiler should be used as the '
1336 'host C++ compiler.'),
1337 check_success=os.path.exists,
1338 error_msg='Invalid C++ compiler path. %s cannot be found.',
1339 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001340
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001341 write_action_env_to_bazelrc('HOST_CXX_COMPILER', host_cxx_compiler)
1342
1343
1344def set_host_c_compiler(environ_cp):
1345 """Set HOST_C_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001346 default_c_host_compiler = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001347
Austin Anderson6afface2017-12-05 11:59:17 -08001348 host_c_compiler = prompt_loop_or_load_from_env(
1349 environ_cp,
1350 var_name='HOST_C_COMPILER',
1351 var_default=default_c_host_compiler,
Shanqing Cai71445712018-03-12 19:33:52 -07001352 ask_for_var=('Please specify which C compiler should be used as the host '
Austin Anderson6afface2017-12-05 11:59:17 -08001353 'C compiler.'),
1354 check_success=os.path.exists,
1355 error_msg='Invalid C compiler path. %s cannot be found.',
1356 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001357
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001358 write_action_env_to_bazelrc('HOST_C_COMPILER', host_c_compiler)
1359
1360
1361def set_computecpp_toolkit_path(environ_cp):
1362 """Set COMPUTECPP_TOOLKIT_PATH."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001363
Austin Anderson6afface2017-12-05 11:59:17 -08001364 def toolkit_exists(toolkit_path):
1365 """Check if a computecpp toolkit path is valid."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001366 if is_linux():
1367 sycl_rt_lib_path = 'lib/libComputeCpp.so'
1368 else:
1369 sycl_rt_lib_path = ''
1370
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001371 sycl_rt_lib_path_full = os.path.join(toolkit_path, sycl_rt_lib_path)
Austin Anderson6afface2017-12-05 11:59:17 -08001372 exists = os.path.exists(sycl_rt_lib_path_full)
1373 if not exists:
1374 print('Invalid SYCL %s library path. %s cannot be found' %
1375 (_TF_OPENCL_VERSION, sycl_rt_lib_path_full))
1376 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001377
Austin Anderson6afface2017-12-05 11:59:17 -08001378 computecpp_toolkit_path = prompt_loop_or_load_from_env(
1379 environ_cp,
1380 var_name='COMPUTECPP_TOOLKIT_PATH',
1381 var_default=_DEFAULT_COMPUTECPP_TOOLKIT_PATH,
1382 ask_for_var=(
1383 'Please specify the location where ComputeCpp for SYCL %s is '
1384 'installed.' % _TF_OPENCL_VERSION),
1385 check_success=toolkit_exists,
1386 error_msg='Invalid SYCL compiler path. %s cannot be found.',
1387 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001388
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001389 write_action_env_to_bazelrc('COMPUTECPP_TOOLKIT_PATH',
1390 computecpp_toolkit_path)
1391
Michael Cased31531a2018-01-05 14:09:41 -08001392
Dandelion Man?90e42f32017-12-15 18:15:07 -08001393def set_trisycl_include_dir(environ_cp):
Michael Cased31531a2018-01-05 14:09:41 -08001394 """Set TRISYCL_INCLUDE_DIR."""
Frank Chenc4ef9272018-01-10 11:36:52 -08001395
Dandelion Man?90e42f32017-12-15 18:15:07 -08001396 ask_trisycl_include_dir = ('Please specify the location of the triSYCL '
1397 'include directory. (Use --config=sycl_trisycl '
1398 'when building with Bazel) '
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001399 '[Default is %s]: ') % (
1400 _DEFAULT_TRISYCL_INCLUDE_DIR)
Frank Chenc4ef9272018-01-10 11:36:52 -08001401
Dandelion Man?90e42f32017-12-15 18:15:07 -08001402 while True:
1403 trisycl_include_dir = get_from_env_or_user_or_default(
Michael Cased31531a2018-01-05 14:09:41 -08001404 environ_cp, 'TRISYCL_INCLUDE_DIR', ask_trisycl_include_dir,
1405 _DEFAULT_TRISYCL_INCLUDE_DIR)
Dandelion Man?90e42f32017-12-15 18:15:07 -08001406 if os.path.exists(trisycl_include_dir):
1407 break
1408
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001409 print('Invalid triSYCL include directory, %s cannot be found' %
1410 (trisycl_include_dir))
Dandelion Man?90e42f32017-12-15 18:15:07 -08001411
1412 # Set TRISYCL_INCLUDE_DIR
1413 environ_cp['TRISYCL_INCLUDE_DIR'] = trisycl_include_dir
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001414 write_action_env_to_bazelrc('TRISYCL_INCLUDE_DIR', trisycl_include_dir)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001415
Yifei Fengb1d8c592017-11-22 13:42:21 -08001416
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001417def set_mpi_home(environ_cp):
1418 """Set MPI_HOME."""
Austin Anderson6afface2017-12-05 11:59:17 -08001419
Jonathan Hseu008910f2017-08-25 14:01:05 -07001420 default_mpi_home = which('mpirun') or which('mpiexec') or ''
1421 default_mpi_home = os.path.dirname(os.path.dirname(default_mpi_home))
1422
Austin Anderson6afface2017-12-05 11:59:17 -08001423 def valid_mpi_path(mpi_home):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001424 exists = (
1425 os.path.exists(os.path.join(mpi_home, 'include')) and
1426 os.path.exists(os.path.join(mpi_home, 'lib')))
Austin Anderson6afface2017-12-05 11:59:17 -08001427 if not exists:
1428 print('Invalid path to the MPI Toolkit. %s or %s cannot be found' %
1429 (os.path.join(mpi_home, 'include'),
1430 os.path.exists(os.path.join(mpi_home, 'lib'))))
1431 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001432
Austin Anderson6afface2017-12-05 11:59:17 -08001433 _ = prompt_loop_or_load_from_env(
1434 environ_cp,
1435 var_name='MPI_HOME',
1436 var_default=default_mpi_home,
1437 ask_for_var='Please specify the MPI toolkit folder.',
1438 check_success=valid_mpi_path,
1439 error_msg='',
1440 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001441
1442
1443def set_other_mpi_vars(environ_cp):
1444 """Set other MPI related variables."""
1445 # Link the MPI header files
1446 mpi_home = environ_cp.get('MPI_HOME')
1447 symlink_force('%s/include/mpi.h' % mpi_home, 'third_party/mpi/mpi.h')
1448
1449 # Determine if we use OpenMPI or MVAPICH, these require different header files
1450 # to be included here to make bazel dependency checker happy
1451 if os.path.exists(os.path.join(mpi_home, 'include/mpi_portable_platform.h')):
1452 symlink_force(
1453 os.path.join(mpi_home, 'include/mpi_portable_platform.h'),
1454 'third_party/mpi/mpi_portable_platform.h')
1455 # TODO(gunan): avoid editing files in configure
1456 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=False',
1457 'MPI_LIB_IS_OPENMPI=True')
1458 else:
1459 # MVAPICH / MPICH
1460 symlink_force(
1461 os.path.join(mpi_home, 'include/mpio.h'), 'third_party/mpi/mpio.h')
1462 symlink_force(
1463 os.path.join(mpi_home, 'include/mpicxx.h'), 'third_party/mpi/mpicxx.h')
1464 # TODO(gunan): avoid editing files in configure
1465 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=True',
1466 'MPI_LIB_IS_OPENMPI=False')
1467
1468 if os.path.exists(os.path.join(mpi_home, 'lib/libmpi.so')):
1469 symlink_force(
1470 os.path.join(mpi_home, 'lib/libmpi.so'), 'third_party/mpi/libmpi.so')
1471 else:
1472 raise ValueError('Cannot find the MPI library file in %s/lib' % mpi_home)
1473
1474
Yifei Feng5198cb82018-08-17 13:53:06 -07001475def set_system_libs_flag(environ_cp):
1476 syslibs = environ_cp.get('TF_SYSTEM_LIBS', '')
TensorFlower Gardener61a87202018-10-01 12:25:39 -07001477 if syslibs:
Jason Zaman5fc39bd2018-09-16 01:38:55 +08001478 if ',' in syslibs:
1479 syslibs = ','.join(sorted(syslibs.split(',')))
1480 else:
1481 syslibs = ','.join(sorted(syslibs.split()))
Yifei Feng5198cb82018-08-17 13:53:06 -07001482 write_action_env_to_bazelrc('TF_SYSTEM_LIBS', syslibs)
1483
Jason Zaman5fc39bd2018-09-16 01:38:55 +08001484 if 'PREFIX' in environ_cp:
1485 write_to_bazelrc('build --define=PREFIX=%s' % environ_cp['PREFIX'])
1486 if 'LIBDIR' in environ_cp:
1487 write_to_bazelrc('build --define=LIBDIR=%s' % environ_cp['LIBDIR'])
1488 if 'INCLUDEDIR' in environ_cp:
1489 write_to_bazelrc('build --define=INCLUDEDIR=%s' % environ_cp['INCLUDEDIR'])
1490
Yifei Feng5198cb82018-08-17 13:53:06 -07001491
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001492def set_windows_build_flags(environ_cp):
1493 """Set Windows specific build options."""
1494 # The non-monolithic build is not supported yet
1495 write_to_bazelrc('build --config monolithic')
1496 # Suppress warning messages
1497 write_to_bazelrc('build --copt=-w --host_copt=-w')
1498 # Output more verbose information when something goes wrong
1499 write_to_bazelrc('build --verbose_failures')
1500 # The host and target platforms are the same in Windows build. So we don't
1501 # have to distinct them. This avoids building the same targets twice.
1502 write_to_bazelrc('build --distinct_host_configuration=false')
1503 # Enable short object file path to avoid long path issue on Windows.
1504 # TODO(pcloudy): Remove this flag when upgrading Bazel to 0.16.0
1505 # Short object file path will be enabled by default.
1506 write_to_bazelrc('build --experimental_shortened_obj_file_path=true')
A. Unique TensorFlower77e26862018-09-27 06:19:58 -07001507 # When building zip file for some py_binary and py_test targets, don't
1508 # include its dependencies. This is for:
1509 # 1. Running python tests against the system installed TF pip package.
1510 # 2. Avoiding redundant files in
1511 # //tensorflow/tools/pip_package:simple_console_windows,
1512 # which is a py_binary used during creating TF pip package.
1513 # See https://github.com/tensorflow/tensorflow/issues/22390
1514 write_to_bazelrc('build --define=no_tensorflow_py_deps=true')
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001515
1516 if get_var(
1517 environ_cp, 'TF_OVERRIDE_EIGEN_STRONG_INLINE', 'Eigen strong inline',
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001518 True, ('Would you like to override eigen strong inline for some C++ '
1519 'compilation to reduce the compilation time?'),
1520 'Eigen strong inline overridden.', 'Not overriding eigen strong inline, '
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001521 'some compilations could take more than 20 mins.'):
1522 # Due to a known MSVC compiler issue
1523 # https://github.com/tensorflow/tensorflow/issues/10521
1524 # Overriding eigen strong inline speeds up the compiling of
1525 # conv_grad_ops_3d.cc and conv_ops_3d.cc by 20 minutes,
1526 # but this also hurts the performance. Let users decide what they want.
1527 write_to_bazelrc('build --define=override_eigen_strong_inline=true')
Dandelion Man?90e42f32017-12-15 18:15:07 -08001528
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001529
Michael Cased31531a2018-01-05 14:09:41 -08001530def config_info_line(name, help_text):
1531 """Helper function to print formatted help text for Bazel config options."""
1532 print('\t--config=%-12s\t# %s' % (name, help_text))
1533
1534
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001535def main():
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001536 global _TF_WORKSPACE_ROOT
1537 global _TF_BAZELRC
1538
Shanqing Cai71445712018-03-12 19:33:52 -07001539 parser = argparse.ArgumentParser()
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001540 parser.add_argument(
1541 '--workspace',
1542 type=str,
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001543 default=os.path.abspath(os.path.dirname(__file__)),
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001544 help='The absolute path to your active Bazel workspace.')
Shanqing Cai71445712018-03-12 19:33:52 -07001545 args = parser.parse_args()
1546
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001547 _TF_WORKSPACE_ROOT = args.workspace
1548 _TF_BAZELRC = os.path.join(_TF_WORKSPACE_ROOT, _TF_BAZELRC_FILENAME)
1549
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001550 # Make a copy of os.environ to be clear when functions and getting and setting
1551 # environment variables.
1552 environ_cp = dict(os.environ)
1553
Yifei Fengbb384112018-07-24 13:12:54 -07001554 check_bazel_version('0.15.0')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001555
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001556 reset_tf_configure_bazelrc()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001557 cleanup_makefile()
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -07001558 setup_python(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001559
1560 if is_windows():
Yifei Fengb1d8c592017-11-22 13:42:21 -08001561 environ_cp['TF_NEED_OPENCL_SYCL'] = '0'
1562 environ_cp['TF_NEED_COMPUTECPP'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001563 environ_cp['TF_NEED_OPENCL'] = '0'
1564 environ_cp['TF_CUDA_CLANG'] = '0'
Guangda Lai76f69382018-01-25 23:59:19 -08001565 environ_cp['TF_NEED_TENSORRT'] = '0'
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001566 # TODO(ibiryukov): Investigate using clang as a cpu or cuda compiler on
1567 # Windows.
1568 environ_cp['TF_DOWNLOAD_CLANG'] = '0'
A. Unique TensorFlower6e97fb32018-07-16 14:07:29 -07001569 environ_cp['TF_ENABLE_XLA'] = '0'
A. Unique TensorFlower6e97fb32018-07-16 14:07:29 -07001570 environ_cp['TF_NEED_MPI'] = '0'
1571 environ_cp['TF_SET_ANDROID_WORKSPACE'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001572
1573 if is_macos():
Guangda Lai76f69382018-01-25 23:59:19 -08001574 environ_cp['TF_NEED_TENSORRT'] = '0'
Todd Wang35459cb2018-09-28 08:56:06 -07001575 environ_cp['TF_ENABLE_XLA'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001576
Jon Triebenbach6896a742018-06-27 13:29:53 -05001577 # The numpy package on ppc64le uses OpenBLAS which has multi-threading
1578 # issues that lead to incorrect answers. Set OMP_NUM_THREADS=1 at
1579 # runtime to allow the Tensorflow testcases which compare numpy
1580 # results to Tensorflow results to succeed.
1581 if is_ppc64le():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001582 write_action_env_to_bazelrc('OMP_NUM_THREADS', 1)
Jon Triebenbach6896a742018-06-27 13:29:53 -05001583
Anton Dmitriev85301672018-08-24 16:52:07 +03001584 set_build_var(environ_cp, 'TF_NEED_IGNITE', 'Apache Ignite',
1585 'with_ignite_support', True, 'ignite')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001586 set_build_var(environ_cp, 'TF_ENABLE_XLA', 'XLA JIT', 'with_xla_support',
Todd Wang35459cb2018-09-28 08:56:06 -07001587 True, 'xla')
Gunhan Gulsoy3da0dff2018-09-26 11:55:50 -07001588
Yifei Fengb1d8c592017-11-22 13:42:21 -08001589 set_action_env_var(environ_cp, 'TF_NEED_OPENCL_SYCL', 'OpenCL SYCL', False)
1590 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001591 set_host_cxx_compiler(environ_cp)
1592 set_host_c_compiler(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001593 set_action_env_var(environ_cp, 'TF_NEED_COMPUTECPP', 'ComputeCPP', True)
1594 if environ_cp.get('TF_NEED_COMPUTECPP') == '1':
1595 set_computecpp_toolkit_path(environ_cp)
1596 else:
1597 set_trisycl_include_dir(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001598
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001599 set_action_env_var(environ_cp, 'TF_NEED_ROCM', 'ROCm', False)
1600 if (environ_cp.get('TF_NEED_ROCM') == '1' and
TensorFlower Gardener62e60162018-09-27 10:22:55 -07001601 'LD_LIBRARY_PATH' in environ_cp and
1602 environ_cp.get('LD_LIBRARY_PATH') != '1'):
1603 write_action_env_to_bazelrc('LD_LIBRARY_PATH',
1604 environ_cp.get('LD_LIBRARY_PATH'))
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001605
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001606 set_action_env_var(environ_cp, 'TF_NEED_CUDA', 'CUDA', False)
A. Unique TensorFlower24cbb2a2017-09-08 07:45:44 -07001607 if (environ_cp.get('TF_NEED_CUDA') == '1' and
1608 'TF_CUDA_CONFIG_REPO' not in environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001609 set_tf_cuda_version(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001610 set_tf_cudnn_version(environ_cp)
Guangda Lai76f69382018-01-25 23:59:19 -08001611 if is_linux():
1612 set_tf_tensorrt_install_path(environ_cp)
Michael Case0073d132018-04-11 09:34:44 -07001613 set_tf_nccl_install_path(environ_cp)
1614
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001615 set_tf_cuda_compute_capabilities(environ_cp)
Ankur Taly0e6f39d2018-02-16 18:22:55 -08001616 if 'LD_LIBRARY_PATH' in environ_cp and environ_cp.get(
1617 'LD_LIBRARY_PATH') != '1':
1618 write_action_env_to_bazelrc('LD_LIBRARY_PATH',
1619 environ_cp.get('LD_LIBRARY_PATH'))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001620
1621 set_tf_cuda_clang(environ_cp)
1622 if environ_cp.get('TF_CUDA_CLANG') == '1':
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001623 # Ask whether we should download the clang toolchain.
1624 set_tf_download_clang(environ_cp)
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -08001625 if environ_cp.get('TF_DOWNLOAD_CLANG') != '1':
1626 # Set up which clang we should use as the cuda / host compiler.
1627 set_clang_cuda_compiler_path(environ_cp)
Ilya Biryukov1c3d02e2018-09-04 03:09:52 -07001628 else:
1629 # Use downloaded LLD for linking.
1630 write_to_bazelrc('build:cuda_clang --config=download_clang_use_lld')
1631 write_to_bazelrc('test:cuda_clang --config=download_clang_use_lld')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001632 else:
1633 # Set up which gcc nvcc should use as the host compiler
1634 # No need to set this on Windows
1635 if not is_windows():
1636 set_gcc_host_compiler_path(environ_cp)
1637 set_other_cuda_vars(environ_cp)
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001638 else:
1639 # CUDA not required. Ask whether we should download the clang toolchain and
1640 # use it for the CPU build.
1641 set_tf_download_clang(environ_cp)
1642 if environ_cp.get('TF_DOWNLOAD_CLANG') == '1':
1643 write_to_bazelrc('build --config=download_clang')
1644 write_to_bazelrc('test --config=download_clang')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001645
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001646 # SYCL / ROCm / CUDA are mutually exclusive.
1647 # At most 1 GPU platform can be configured.
1648 gpu_platform_count = 0
1649 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
1650 gpu_platform_count += 1
1651 if environ_cp.get('TF_NEED_ROCM') == '1':
1652 gpu_platform_count += 1
1653 if environ_cp.get('TF_NEED_CUDA') == '1':
1654 gpu_platform_count += 1
1655 if gpu_platform_count >= 2:
1656 raise UserInputError('SYCL / CUDA / ROCm are mututally exclusive. '
1657 'At most 1 GPU platform can be configured.')
1658
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001659 set_build_var(environ_cp, 'TF_NEED_MPI', 'MPI', 'with_mpi_support', False)
1660 if environ_cp.get('TF_NEED_MPI') == '1':
1661 set_mpi_home(environ_cp)
1662 set_other_mpi_vars(environ_cp)
1663
1664 set_cc_opt_flags(environ_cp)
Yifei Feng5198cb82018-08-17 13:53:06 -07001665 set_system_libs_flag(environ_cp)
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001666 if is_windows():
1667 set_windows_build_flags(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001668
Anna Ra9a1d5a2018-09-14 12:44:31 -07001669 # Add a config option to build TensorFlow 2.0 API.
1670 write_to_bazelrc('build:v2 --define=tf_api_version=2')
1671
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001672 if get_var(environ_cp, 'TF_SET_ANDROID_WORKSPACE', 'android workspace', False,
1673 ('Would you like to interactively configure ./WORKSPACE for '
1674 'Android builds?'), 'Searching for NDK and SDK installations.',
1675 'Not configuring the WORKSPACE for Android builds.'):
Michael Case51053502018-06-05 17:47:19 -07001676 create_android_ndk_rule(environ_cp)
1677 create_android_sdk_rule(environ_cp)
Austin Anderson6afface2017-12-05 11:59:17 -08001678
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001679 # On Windows, we don't have MKL support and the build is always monolithic.
1680 # So no need to print the following message.
1681 # TODO(pcloudy): remove the following if check when they make sense on Windows
1682 if not is_windows():
1683 print('Preconfigured Bazel build configs. You can use any of the below by '
1684 'adding "--config=<>" to your build command. See tools/bazel.rc for '
1685 'more details.')
1686 config_info_line('mkl', 'Build with MKL support.')
1687 config_info_line('monolithic', 'Config for mostly static monolithic build.')
Gunhan Gulsoy3da0dff2018-09-26 11:55:50 -07001688 config_info_line('gdr', 'Build with GDR support.')
1689 config_info_line('verbs', 'Build with libverbs support.')
avijit-nervanaf172c522018-09-27 12:57:24 -07001690 config_info_line('ngraph', 'Build with Intel nGraph support.')
Austin Anderson6afface2017-12-05 11:59:17 -08001691
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001692
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001693if __name__ == '__main__':
1694 main()