blob: 796c6231e8b7433606f06e008980f68ce06609f0 [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
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -070055if platform.machine() == 'ppc64le':
56 _DEFAULT_TENSORRT_PATH_LINUX = '/usr/lib/powerpc64le-linux-gnu/'
57else:
58 _DEFAULT_TENSORRT_PATH_LINUX = '/usr/lib/%s-linux-gnu' % platform.machine()
59
Austin Anderson6afface2017-12-05 11:59:17 -080060
61class UserInputError(Exception):
62 pass
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070063
64
65def is_windows():
66 return platform.system() == 'Windows'
67
68
69def is_linux():
70 return platform.system() == 'Linux'
71
72
73def is_macos():
74 return platform.system() == 'Darwin'
75
76
77def is_ppc64le():
78 return platform.machine() == 'ppc64le'
79
80
Jonathan Hseu008910f2017-08-25 14:01:05 -070081def is_cygwin():
82 return platform.system().startswith('CYGWIN_NT')
83
84
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070085def get_input(question):
86 try:
87 try:
88 answer = raw_input(question)
89 except NameError:
90 answer = input(question) # pylint: disable=bad-builtin
91 except EOFError:
92 answer = ''
93 return answer
94
95
96def symlink_force(target, link_name):
97 """Force symlink, equivalent of 'ln -sf'.
98
99 Args:
100 target: items to link to.
101 link_name: name of the link.
102 """
103 try:
104 os.symlink(target, link_name)
105 except OSError as e:
106 if e.errno == errno.EEXIST:
107 os.remove(link_name)
108 os.symlink(target, link_name)
109 else:
110 raise e
111
112
113def sed_in_place(filename, old, new):
114 """Replace old string with new string in file.
115
116 Args:
117 filename: string for filename.
118 old: string to replace.
119 new: new string to replace to.
120 """
121 with open(filename, 'r') as f:
122 filedata = f.read()
123 newdata = filedata.replace(old, new)
124 with open(filename, 'w') as f:
125 f.write(newdata)
126
127
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700128def write_to_bazelrc(line):
129 with open(_TF_BAZELRC, 'a') as f:
130 f.write(line + '\n')
131
132
133def write_action_env_to_bazelrc(var_name, var):
134 write_to_bazelrc('build --action_env %s="%s"' % (var_name, str(var)))
135
136
Jonathan Hseu008910f2017-08-25 14:01:05 -0700137def run_shell(cmd, allow_non_zero=False):
138 if allow_non_zero:
139 try:
140 output = subprocess.check_output(cmd)
141 except subprocess.CalledProcessError as e:
142 output = e.output
143 else:
144 output = subprocess.check_output(cmd)
145 return output.decode('UTF-8').strip()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700146
147
148def cygpath(path):
149 """Convert path from posix to windows."""
Martin Wicked57572e2017-09-02 19:21:45 -0700150 return os.path.abspath(path).replace('\\', '/')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700151
152
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700153def get_python_path(environ_cp, python_bin_path):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700154 """Get the python site package paths."""
155 python_paths = []
156 if environ_cp.get('PYTHONPATH'):
157 python_paths = environ_cp.get('PYTHONPATH').split(':')
158 try:
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700159 library_paths = run_shell([
160 python_bin_path, '-c',
161 'import site; print("\\n".join(site.getsitepackages()))'
162 ]).split('\n')
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700163 except subprocess.CalledProcessError:
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700164 library_paths = [
165 run_shell([
166 python_bin_path, '-c',
167 'from distutils.sysconfig import get_python_lib;'
168 'print(get_python_lib())'
169 ])
170 ]
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700171
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700172 all_paths = set(python_paths + library_paths)
173
174 paths = []
175 for path in all_paths:
176 if os.path.isdir(path):
177 paths.append(path)
178 return paths
179
180
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700181def get_python_major_version(python_bin_path):
182 """Get the python major version."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700183 return run_shell([python_bin_path, '-c', 'import sys; print(sys.version[0])'])
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700184
185
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700186def setup_python(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700187 """Setup python related env variables."""
188 # Get PYTHON_BIN_PATH, default is the current running python.
189 default_python_bin_path = sys.executable
190 ask_python_bin_path = ('Please specify the location of python. [Default is '
191 '%s]: ') % default_python_bin_path
192 while True:
193 python_bin_path = get_from_env_or_user_or_default(
194 environ_cp, 'PYTHON_BIN_PATH', ask_python_bin_path,
195 default_python_bin_path)
196 # Check if the path is valid
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700197 if os.path.isfile(python_bin_path) and os.access(python_bin_path, os.X_OK):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700198 break
199 elif not os.path.exists(python_bin_path):
200 print('Invalid python path: %s cannot be found.' % python_bin_path)
201 else:
202 print('%s is not executable. Is it the python binary?' % python_bin_path)
203 environ_cp['PYTHON_BIN_PATH'] = ''
204
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700205 # Convert python path to Windows style before checking lib and version
Martin Wicked57572e2017-09-02 19:21:45 -0700206 if is_windows() or is_cygwin():
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700207 python_bin_path = cygpath(python_bin_path)
208
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700209 # Get PYTHON_LIB_PATH
210 python_lib_path = environ_cp.get('PYTHON_LIB_PATH')
211 if not python_lib_path:
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700212 python_lib_paths = get_python_path(environ_cp, python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700213 if environ_cp.get('USE_DEFAULT_PYTHON_LIB_PATH') == '1':
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700214 python_lib_path = python_lib_paths[0]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700215 else:
Jonathan Hseu008910f2017-08-25 14:01:05 -0700216 print('Found possible Python library paths:\n %s' %
217 '\n '.join(python_lib_paths))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700218 default_python_lib_path = python_lib_paths[0]
219 python_lib_path = get_input(
Jonathan Hseu008910f2017-08-25 14:01:05 -0700220 'Please input the desired Python library path to use. '
221 'Default is [%s]\n' % python_lib_paths[0])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700222 if not python_lib_path:
223 python_lib_path = default_python_lib_path
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700224 environ_cp['PYTHON_LIB_PATH'] = python_lib_path
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700225
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700226 python_major_version = get_python_major_version(python_bin_path)
227
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700228 # Convert python path to Windows style before writing into bazel.rc
Martin Wicked57572e2017-09-02 19:21:45 -0700229 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700230 python_lib_path = cygpath(python_lib_path)
231
232 # Set-up env variables used by python_configure.bzl
233 write_action_env_to_bazelrc('PYTHON_BIN_PATH', python_bin_path)
234 write_action_env_to_bazelrc('PYTHON_LIB_PATH', python_lib_path)
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700235 write_to_bazelrc('build --python_path=\"%s"' % python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700236 environ_cp['PYTHON_BIN_PATH'] = python_bin_path
237
238 # Write tools/python_bin_path.sh
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700239 with open(
240 os.path.join(_TF_WORKSPACE_ROOT, 'tools', 'python_bin_path.sh'),
241 'w') as f:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700242 f.write('export PYTHON_BIN_PATH="%s"' % python_bin_path)
243
244
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -0700245def reset_tf_configure_bazelrc():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700246 """Reset file that contains customized config settings."""
247 open(_TF_BAZELRC, 'w').close()
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -0700248 bazelrc_path = os.path.join(_TF_WORKSPACE_ROOT, '.bazelrc')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700249
Shanqing Cai71445712018-03-12 19:33:52 -0700250 data = []
251 if os.path.exists(bazelrc_path):
252 with open(bazelrc_path, 'r') as f:
253 data = f.read().splitlines()
254 with open(bazelrc_path, 'w') as f:
255 for l in data:
256 if _TF_BAZELRC_FILENAME in l:
257 continue
258 f.write('%s\n' % l)
259 if is_windows():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700260 tf_bazelrc_path = _TF_BAZELRC.replace('\\', '/')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700261 else:
Shanqing Cai71445712018-03-12 19:33:52 -0700262 tf_bazelrc_path = _TF_BAZELRC
263 f.write('import %s\n' % tf_bazelrc_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700264
265
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700266def cleanup_makefile():
267 """Delete any leftover BUILD files from the Makefile build.
268
269 These files could interfere with Bazel parsing.
270 """
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700271 makefile_download_dir = os.path.join(_TF_WORKSPACE_ROOT, 'tensorflow',
272 'contrib', 'makefile', 'downloads')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700273 if os.path.isdir(makefile_download_dir):
274 for root, _, filenames in os.walk(makefile_download_dir):
275 for f in filenames:
276 if f.endswith('BUILD'):
277 os.remove(os.path.join(root, f))
278
279
280def get_var(environ_cp,
281 var_name,
282 query_item,
283 enabled_by_default,
284 question=None,
285 yes_reply=None,
286 no_reply=None):
287 """Get boolean input from user.
288
289 If var_name is not set in env, ask user to enable query_item or not. If the
290 response is empty, use the default.
291
292 Args:
293 environ_cp: copy of the os.environ.
294 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
295 query_item: string for feature related to the variable, e.g. "Hadoop File
296 System".
297 enabled_by_default: boolean for default behavior.
298 question: optional string for how to ask for user input.
Michael Cased90054e2018-02-07 14:36:00 -0800299 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700300 no_reply: optional string for reply when feature is disabled.
301
302 Returns:
303 boolean value of the variable.
Frank Chenc4ef9272018-01-10 11:36:52 -0800304
305 Raises:
306 UserInputError: if an environment variable is set, but it cannot be
307 interpreted as a boolean indicator, assume that the user has made a
308 scripting error, and will continue to provide invalid input.
309 Raise the error to avoid infinitely looping.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700310 """
311 if not question:
312 question = 'Do you wish to build TensorFlow with %s support?' % query_item
313 if not yes_reply:
314 yes_reply = '%s support will be enabled for TensorFlow.' % query_item
315 if not no_reply:
316 no_reply = 'No %s' % yes_reply
317
318 yes_reply += '\n'
319 no_reply += '\n'
320
321 if enabled_by_default:
322 question += ' [Y/n]: '
323 else:
324 question += ' [y/N]: '
325
326 var = environ_cp.get(var_name)
Frank Chenc4ef9272018-01-10 11:36:52 -0800327 if var is not None:
328 var_content = var.strip().lower()
329 true_strings = ('1', 't', 'true', 'y', 'yes')
330 false_strings = ('0', 'f', 'false', 'n', 'no')
331 if var_content in true_strings:
332 var = True
333 elif var_content in false_strings:
334 var = False
335 else:
336 raise UserInputError(
337 'Environment variable %s must be set as a boolean indicator.\n'
338 'The following are accepted as TRUE : %s.\n'
339 'The following are accepted as FALSE: %s.\n'
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700340 'Current value is %s.' % (var_name, ', '.join(true_strings),
341 ', '.join(false_strings), var))
Frank Chenc4ef9272018-01-10 11:36:52 -0800342
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700343 while var is None:
344 user_input_origin = get_input(question)
345 user_input = user_input_origin.strip().lower()
346 if user_input == 'y':
347 print(yes_reply)
348 var = True
349 elif user_input == 'n':
350 print(no_reply)
351 var = False
352 elif not user_input:
353 if enabled_by_default:
354 print(yes_reply)
355 var = True
356 else:
357 print(no_reply)
358 var = False
359 else:
360 print('Invalid selection: %s' % user_input_origin)
361 return var
362
363
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700364def set_build_var(environ_cp,
365 var_name,
366 query_item,
367 option_name,
368 enabled_by_default,
369 bazel_config_name=None):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700370 """Set if query_item will be enabled for the build.
371
372 Ask user if query_item will be enabled. Default is used if no input is given.
373 Set subprocess environment variable and write to .bazelrc if enabled.
374
375 Args:
376 environ_cp: copy of the os.environ.
377 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
378 query_item: string for feature related to the variable, e.g. "Hadoop File
379 System".
380 option_name: string for option to define in .bazelrc.
381 enabled_by_default: boolean for default behavior.
Michael Case98850a52017-09-14 13:35:57 -0700382 bazel_config_name: Name for Bazel --config argument to enable build feature.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700383 """
384
385 var = str(int(get_var(environ_cp, var_name, query_item, enabled_by_default)))
386 environ_cp[var_name] = var
387 if var == '1':
388 write_to_bazelrc('build --define %s=true' % option_name)
Michael Case98850a52017-09-14 13:35:57 -0700389 elif bazel_config_name is not None:
390 # TODO(mikecase): Migrate all users of configure.py to use --config Bazel
391 # options and not to set build configs through environment variables.
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700392 write_to_bazelrc(
393 'build:%s --define %s=true' % (bazel_config_name, option_name))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700394
395
396def set_action_env_var(environ_cp,
397 var_name,
398 query_item,
399 enabled_by_default,
400 question=None,
401 yes_reply=None,
402 no_reply=None):
403 """Set boolean action_env variable.
404
405 Ask user if query_item will be enabled. Default is used if no input is given.
406 Set environment variable and write to .bazelrc.
407
408 Args:
409 environ_cp: copy of the os.environ.
410 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
411 query_item: string for feature related to the variable, e.g. "Hadoop File
412 System".
413 enabled_by_default: boolean for default behavior.
414 question: optional string for how to ask for user input.
Michael Cased90054e2018-02-07 14:36:00 -0800415 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700416 no_reply: optional string for reply when feature is disabled.
417 """
418 var = int(
419 get_var(environ_cp, var_name, query_item, enabled_by_default, question,
420 yes_reply, no_reply))
421
422 write_action_env_to_bazelrc(var_name, var)
423 environ_cp[var_name] = str(var)
424
425
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700426def convert_version_to_int(version):
427 """Convert a version number to a integer that can be used to compare.
428
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700429 Version strings of the form X.YZ and X.Y.Z-xxxxx are supported. The
430 'xxxxx' part, for instance 'homebrew' on OS/X, is ignored.
431
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700432 Args:
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700433 version: a version to be converted
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700434
435 Returns:
436 An integer if converted successfully, otherwise return None.
437 """
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700438 version = version.split('-')[0]
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700439 version_segments = version.split('.')
440 for seg in version_segments:
441 if not seg.isdigit():
442 return None
443
444 version_str = ''.join(['%03d' % int(seg) for seg in version_segments])
445 return int(version_str)
446
447
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700448def check_bazel_version(min_version):
Yifei Fengdce9a492018-02-22 14:24:57 -0800449 """Check installed bazel version is at least min_version.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700450
451 Args:
452 min_version: string for minimum bazel version.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700453
454 Returns:
455 The bazel version detected.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700456 """
Jonathan Hseu008910f2017-08-25 14:01:05 -0700457 if which('bazel') is None:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700458 print('Cannot find bazel. Please install bazel.')
459 sys.exit(0)
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700460 curr_version = run_shell(
461 ['bazel', '--batch', '--bazelrc=/dev/null', 'version'])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700462
463 for line in curr_version.split('\n'):
464 if 'Build label: ' in line:
465 curr_version = line.split('Build label: ')[1]
466 break
467
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700468 min_version_int = convert_version_to_int(min_version)
469 curr_version_int = convert_version_to_int(curr_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700470
471 # Check if current bazel version can be detected properly.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700472 if not curr_version_int:
473 print('WARNING: current bazel installation is not a release version.')
474 print('Make sure you are running at least bazel %s' % min_version)
475 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700476
Michael Cased94271a2017-08-22 17:26:52 -0700477 print('You have bazel %s installed.' % curr_version)
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700478
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700479 if curr_version_int < min_version_int:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700480 print('Please upgrade your bazel installation to version %s or higher to '
481 'build TensorFlow!' % min_version)
482 sys.exit(0)
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700483 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700484
485
486def set_cc_opt_flags(environ_cp):
487 """Set up architecture-dependent optimization flags.
488
489 Also append CC optimization flags to bazel.rc..
490
491 Args:
492 environ_cp: copy of the os.environ.
493 """
494 if is_ppc64le():
495 # gcc on ppc64le does not support -march, use mcpu instead
496 default_cc_opt_flags = '-mcpu=native'
A. Unique TensorFlower1bba94a2018-04-04 15:45:20 -0700497 elif is_windows():
498 default_cc_opt_flags = '/arch:AVX'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700499 else:
500 default_cc_opt_flags = '-march=native'
501 question = ('Please specify optimization flags to use during compilation when'
502 ' bazel option "--config=opt" is specified [Default is %s]: '
503 ) % default_cc_opt_flags
504 cc_opt_flags = get_from_env_or_user_or_default(environ_cp, 'CC_OPT_FLAGS',
505 question, default_cc_opt_flags)
506 for opt in cc_opt_flags.split():
Michael Case00177422017-11-10 13:14:03 -0800507 write_to_bazelrc('build:opt --copt=%s' % opt)
508 # It should be safe on the same build host.
A. Unique TensorFlower1bba94a2018-04-04 15:45:20 -0700509 if not is_ppc64le() and not is_windows():
Shanqing Cai71445712018-03-12 19:33:52 -0700510 write_to_bazelrc('build:opt --host_copt=-march=native')
Michael Casebb3355d2017-11-09 08:46:31 -0800511 write_to_bazelrc('build:opt --define with_default_optimizations=true')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700512
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700513
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700514def set_tf_cuda_clang(environ_cp):
515 """set TF_CUDA_CLANG action_env.
516
517 Args:
518 environ_cp: copy of the os.environ.
519 """
520 question = 'Do you want to use clang as CUDA compiler?'
521 yes_reply = 'Clang will be used as CUDA compiler.'
522 no_reply = 'nvcc will be used as CUDA compiler.'
523 set_action_env_var(
524 environ_cp,
525 'TF_CUDA_CLANG',
526 None,
527 False,
528 question=question,
529 yes_reply=yes_reply,
530 no_reply=no_reply)
531
532
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800533def set_tf_download_clang(environ_cp):
534 """Set TF_DOWNLOAD_CLANG action_env."""
Ilya Biryukov9e651e42018-03-22 05:33:42 -0700535 question = 'Do you wish to download a fresh release of clang? (Experimental)'
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800536 yes_reply = 'Clang will be downloaded and used to compile tensorflow.'
537 no_reply = 'Clang will not be downloaded.'
538 set_action_env_var(
539 environ_cp,
540 'TF_DOWNLOAD_CLANG',
541 None,
542 False,
543 question=question,
544 yes_reply=yes_reply,
545 no_reply=no_reply)
546
547
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700548def get_from_env_or_user_or_default(environ_cp, var_name, ask_for_var,
549 var_default):
550 """Get var_name either from env, or user or default.
551
552 If var_name has been set as environment variable, use the preset value, else
553 ask for user input. If no input is provided, the default is used.
554
555 Args:
556 environ_cp: copy of the os.environ.
557 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
558 ask_for_var: string for how to ask for user input.
559 var_default: default value string.
560
561 Returns:
562 string value for var_name
563 """
564 var = environ_cp.get(var_name)
565 if not var:
566 var = get_input(ask_for_var)
Michael Cased94271a2017-08-22 17:26:52 -0700567 print('\n')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700568 if not var:
569 var = var_default
570 return var
571
572
573def set_clang_cuda_compiler_path(environ_cp):
574 """Set CLANG_CUDA_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700575 default_clang_path = which('clang') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700576 ask_clang_path = ('Please specify which clang should be used as device and '
577 'host compiler. [Default is %s]: ') % default_clang_path
578
579 while True:
580 clang_cuda_compiler_path = get_from_env_or_user_or_default(
581 environ_cp, 'CLANG_CUDA_COMPILER_PATH', ask_clang_path,
582 default_clang_path)
583 if os.path.exists(clang_cuda_compiler_path):
584 break
585
586 # Reset and retry
587 print('Invalid clang path: %s cannot be found.' % clang_cuda_compiler_path)
588 environ_cp['CLANG_CUDA_COMPILER_PATH'] = ''
589
590 # Set CLANG_CUDA_COMPILER_PATH
591 environ_cp['CLANG_CUDA_COMPILER_PATH'] = clang_cuda_compiler_path
592 write_action_env_to_bazelrc('CLANG_CUDA_COMPILER_PATH',
593 clang_cuda_compiler_path)
594
595
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700596def prompt_loop_or_load_from_env(environ_cp,
597 var_name,
598 var_default,
599 ask_for_var,
600 check_success,
601 error_msg,
602 suppress_default_error=False,
603 n_ask_attempts=_DEFAULT_PROMPT_ASK_ATTEMPTS):
Austin Anderson6afface2017-12-05 11:59:17 -0800604 """Loop over user prompts for an ENV param until receiving a valid response.
605
606 For the env param var_name, read from the environment or verify user input
607 until receiving valid input. When done, set var_name in the environ_cp to its
608 new value.
609
610 Args:
611 environ_cp: (Dict) copy of the os.environ.
612 var_name: (String) string for name of environment variable, e.g. "TF_MYVAR".
613 var_default: (String) default value string.
614 ask_for_var: (String) string for how to ask for user input.
615 check_success: (Function) function that takes one argument and returns a
616 boolean. Should return True if the value provided is considered valid. May
617 contain a complex error message if error_msg does not provide enough
618 information. In that case, set suppress_default_error to True.
619 error_msg: (String) String with one and only one '%s'. Formatted with each
620 invalid response upon check_success(input) failure.
621 suppress_default_error: (Bool) Suppress the above error message in favor of
622 one from the check_success function.
623 n_ask_attempts: (Integer) Number of times to query for valid input before
624 raising an error and quitting.
625
626 Returns:
627 [String] The value of var_name after querying for input.
628
629 Raises:
630 UserInputError: if a query has been attempted n_ask_attempts times without
Frank Chenc4ef9272018-01-10 11:36:52 -0800631 success, assume that the user has made a scripting error, and will
632 continue to provide invalid input. Raise the error to avoid infinitely
633 looping.
Austin Anderson6afface2017-12-05 11:59:17 -0800634 """
635 default = environ_cp.get(var_name) or var_default
636 full_query = '%s [Default is %s]: ' % (
637 ask_for_var,
638 default,
639 )
640
641 for _ in range(n_ask_attempts):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700642 val = get_from_env_or_user_or_default(environ_cp, var_name, full_query,
Austin Anderson6afface2017-12-05 11:59:17 -0800643 default)
644 if check_success(val):
645 break
646 if not suppress_default_error:
647 print(error_msg % val)
648 environ_cp[var_name] = ''
649 else:
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700650 raise UserInputError(
651 'Invalid %s setting was provided %d times in a row. '
652 'Assuming to be a scripting mistake.' % (var_name, n_ask_attempts))
Austin Anderson6afface2017-12-05 11:59:17 -0800653
654 environ_cp[var_name] = val
655 return val
656
657
658def create_android_ndk_rule(environ_cp):
659 """Set ANDROID_NDK_HOME and write Android NDK WORKSPACE rule."""
660 if is_windows() or is_cygwin():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700661 default_ndk_path = cygpath(
662 '%s/Android/Sdk/ndk-bundle' % environ_cp['APPDATA'])
Austin Anderson6afface2017-12-05 11:59:17 -0800663 elif is_macos():
664 default_ndk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
665 else:
666 default_ndk_path = '%s/Android/Sdk/ndk-bundle' % environ_cp['HOME']
667
668 def valid_ndk_path(path):
669 return (os.path.exists(path) and
670 os.path.exists(os.path.join(path, 'source.properties')))
671
672 android_ndk_home_path = prompt_loop_or_load_from_env(
673 environ_cp,
674 var_name='ANDROID_NDK_HOME',
675 var_default=default_ndk_path,
676 ask_for_var='Please specify the home path of the Android NDK to use.',
677 check_success=valid_ndk_path,
678 error_msg=('The path %s or its child file "source.properties" '
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700679 'does not exist.'))
Michael Case51053502018-06-05 17:47:19 -0700680 write_action_env_to_bazelrc('ANDROID_NDK_HOME', android_ndk_home_path)
681 write_action_env_to_bazelrc('ANDROID_NDK_API_LEVEL',
682 check_ndk_level(android_ndk_home_path))
Austin Anderson6afface2017-12-05 11:59:17 -0800683
684
685def create_android_sdk_rule(environ_cp):
686 """Set Android variables and write Android SDK WORKSPACE rule."""
687 if is_windows() or is_cygwin():
688 default_sdk_path = cygpath('%s/Android/Sdk' % environ_cp['APPDATA'])
689 elif is_macos():
Shashi Shekharc0ff0cc2018-07-17 09:00:24 -0700690 default_sdk_path = '%s/library/Android/Sdk' % environ_cp['HOME']
Austin Anderson6afface2017-12-05 11:59:17 -0800691 else:
692 default_sdk_path = '%s/Android/Sdk' % environ_cp['HOME']
693
694 def valid_sdk_path(path):
695 return (os.path.exists(path) and
696 os.path.exists(os.path.join(path, 'platforms')) and
697 os.path.exists(os.path.join(path, 'build-tools')))
698
699 android_sdk_home_path = prompt_loop_or_load_from_env(
700 environ_cp,
701 var_name='ANDROID_SDK_HOME',
702 var_default=default_sdk_path,
703 ask_for_var='Please specify the home path of the Android SDK to use.',
704 check_success=valid_sdk_path,
705 error_msg=('Either %s does not exist, or it does not contain the '
706 'subdirectories "platforms" and "build-tools".'))
707
708 platforms = os.path.join(android_sdk_home_path, 'platforms')
709 api_levels = sorted(os.listdir(platforms))
710 api_levels = [x.replace('android-', '') for x in api_levels]
711
712 def valid_api_level(api_level):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700713 return os.path.exists(
714 os.path.join(android_sdk_home_path, 'platforms',
715 'android-' + api_level))
Austin Anderson6afface2017-12-05 11:59:17 -0800716
717 android_api_level = prompt_loop_or_load_from_env(
718 environ_cp,
719 var_name='ANDROID_API_LEVEL',
720 var_default=api_levels[-1],
721 ask_for_var=('Please specify the Android SDK API level to use. '
722 '[Available levels: %s]') % api_levels,
723 check_success=valid_api_level,
724 error_msg='Android-%s is not present in the SDK path.')
725
726 build_tools = os.path.join(android_sdk_home_path, 'build-tools')
727 versions = sorted(os.listdir(build_tools))
728
729 def valid_build_tools(version):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700730 return os.path.exists(
731 os.path.join(android_sdk_home_path, 'build-tools', version))
Austin Anderson6afface2017-12-05 11:59:17 -0800732
733 android_build_tools_version = prompt_loop_or_load_from_env(
734 environ_cp,
735 var_name='ANDROID_BUILD_TOOLS_VERSION',
736 var_default=versions[-1],
737 ask_for_var=('Please specify an Android build tools version to use. '
738 '[Available versions: %s]') % versions,
739 check_success=valid_build_tools,
740 error_msg=('The selected SDK does not have build-tools version %s '
741 'available.'))
742
Michael Case51053502018-06-05 17:47:19 -0700743 write_action_env_to_bazelrc('ANDROID_BUILD_TOOLS_VERSION',
744 android_build_tools_version)
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700745 write_action_env_to_bazelrc('ANDROID_SDK_API_LEVEL', android_api_level)
746 write_action_env_to_bazelrc('ANDROID_SDK_HOME', android_sdk_home_path)
Austin Anderson6afface2017-12-05 11:59:17 -0800747
748
749def check_ndk_level(android_ndk_home_path):
750 """Check the revision number of an Android NDK path."""
751 properties_path = '%s/source.properties' % android_ndk_home_path
752 if is_windows() or is_cygwin():
753 properties_path = cygpath(properties_path)
754 with open(properties_path, 'r') as f:
755 filedata = f.read()
756
757 revision = re.search(r'Pkg.Revision = (\d+)', filedata)
758 if revision:
Michael Case51053502018-06-05 17:47:19 -0700759 ndk_api_level = revision.group(1)
760 else:
761 raise Exception('Unable to parse NDK revision.')
762 if int(ndk_api_level) not in _SUPPORTED_ANDROID_NDK_VERSIONS:
763 print('WARNING: The API level of the NDK in %s is %s, which is not '
764 'supported by Bazel (officially supported versions: %s). Please use '
765 'another version. Compiling Android targets may result in confusing '
766 'errors.\n' % (android_ndk_home_path, ndk_api_level,
767 _SUPPORTED_ANDROID_NDK_VERSIONS))
768 return ndk_api_level
Austin Anderson6afface2017-12-05 11:59:17 -0800769
770
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700771def set_gcc_host_compiler_path(environ_cp):
772 """Set GCC_HOST_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700773 default_gcc_host_compiler_path = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700774 cuda_bin_symlink = '%s/bin/gcc' % environ_cp.get('CUDA_TOOLKIT_PATH')
775
776 if os.path.islink(cuda_bin_symlink):
777 # os.readlink is only available in linux
Jonathan Hseu008910f2017-08-25 14:01:05 -0700778 default_gcc_host_compiler_path = os.path.realpath(cuda_bin_symlink)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700779
Austin Anderson6afface2017-12-05 11:59:17 -0800780 gcc_host_compiler_path = prompt_loop_or_load_from_env(
781 environ_cp,
782 var_name='GCC_HOST_COMPILER_PATH',
783 var_default=default_gcc_host_compiler_path,
784 ask_for_var=
785 'Please specify which gcc should be used by nvcc as the host compiler.',
786 check_success=os.path.exists,
787 error_msg='Invalid gcc path. %s cannot be found.',
788 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700789
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700790 write_action_env_to_bazelrc('GCC_HOST_COMPILER_PATH', gcc_host_compiler_path)
791
792
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800793def reformat_version_sequence(version_str, sequence_count):
794 """Reformat the version string to have the given number of sequences.
795
796 For example:
797 Given (7, 2) -> 7.0
798 (7.0.1, 2) -> 7.0
799 (5, 1) -> 5
800 (5.0.3.2, 1) -> 5
801
802 Args:
803 version_str: String, the version string.
804 sequence_count: int, an integer.
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700805
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800806 Returns:
807 string, reformatted version string.
808 """
809 v = version_str.split('.')
810 if len(v) < sequence_count:
811 v = v + (['0'] * (sequence_count - len(v)))
812
813 return '.'.join(v[:sequence_count])
814
815
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700816def set_tf_cuda_version(environ_cp):
817 """Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION."""
818 ask_cuda_version = (
A. Unique TensorFlowerb15500b2018-05-08 12:04:38 -0700819 'Please specify the CUDA SDK version you want to use. '
820 '[Leave empty to default to CUDA %s]: ') % _DEFAULT_CUDA_VERSION
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700821
Austin Andersonf9a88f82017-12-13 11:49:40 -0800822 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700823 # Configure the Cuda SDK version to use.
824 tf_cuda_version = get_from_env_or_user_or_default(
825 environ_cp, 'TF_CUDA_VERSION', ask_cuda_version, _DEFAULT_CUDA_VERSION)
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800826 tf_cuda_version = reformat_version_sequence(str(tf_cuda_version), 2)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700827
828 # Find out where the CUDA toolkit is installed
829 default_cuda_path = _DEFAULT_CUDA_PATH
Martin Wicked57572e2017-09-02 19:21:45 -0700830 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700831 default_cuda_path = cygpath(
832 environ_cp.get('CUDA_PATH', _DEFAULT_CUDA_PATH_WIN))
833 elif is_linux():
834 # If the default doesn't exist, try an alternative default.
835 if (not os.path.exists(default_cuda_path)
836 ) and os.path.exists(_DEFAULT_CUDA_PATH_LINUX):
837 default_cuda_path = _DEFAULT_CUDA_PATH_LINUX
838 ask_cuda_path = ('Please specify the location where CUDA %s toolkit is'
839 ' installed. Refer to README.md for more details. '
840 '[Default is %s]: ') % (tf_cuda_version, default_cuda_path)
841 cuda_toolkit_path = get_from_env_or_user_or_default(
842 environ_cp, 'CUDA_TOOLKIT_PATH', ask_cuda_path, default_cuda_path)
A. Unique TensorFlower02f17fe2018-07-07 06:59:19 -0700843 if is_windows() or is_cygwin():
844 cuda_toolkit_path = cygpath(cuda_toolkit_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700845
846 if is_windows():
Niall Moranb7d97e82018-08-09 00:29:49 +0100847 cuda_rt_lib_paths = ['lib/x64/cudart.lib']
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700848 elif is_linux():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700849 cuda_rt_lib_paths = [
850 '%s/libcudart.so.%s' % (x, tf_cuda_version) for x in [
851 'lib64',
852 'lib/powerpc64le-linux-gnu',
853 'lib/x86_64-linux-gnu',
854 ]
855 ]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700856 elif is_macos():
Niall Moranb7d97e82018-08-09 00:29:49 +0100857 cuda_rt_lib_paths = ['lib/libcudart.%s.dylib' % tf_cuda_version]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700858
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700859 cuda_toolkit_paths_full = [
860 os.path.join(cuda_toolkit_path, x) for x in cuda_rt_lib_paths
861 ]
Niall Moranb7d97e82018-08-09 00:29:49 +0100862 if any([os.path.exists(x) for x in cuda_toolkit_paths_full]):
Yifei Feng5198cb82018-08-17 13:53:06 -0700863 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700864
865 # Reset and retry
866 print('Invalid path to CUDA %s toolkit. %s cannot be found' %
hellcom9a13fc32018-09-12 10:58:24 +0300867 (tf_cuda_version, cuda_toolkit_paths_full))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700868 environ_cp['TF_CUDA_VERSION'] = ''
869 environ_cp['CUDA_TOOLKIT_PATH'] = ''
870
Austin Andersonf9a88f82017-12-13 11:49:40 -0800871 else:
872 raise UserInputError('Invalid TF_CUDA_SETTING setting was provided %d '
873 'times in a row. Assuming to be a scripting mistake.' %
874 _DEFAULT_PROMPT_ASK_ATTEMPTS)
875
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700876 # Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION
877 environ_cp['CUDA_TOOLKIT_PATH'] = cuda_toolkit_path
878 write_action_env_to_bazelrc('CUDA_TOOLKIT_PATH', cuda_toolkit_path)
879 environ_cp['TF_CUDA_VERSION'] = tf_cuda_version
880 write_action_env_to_bazelrc('TF_CUDA_VERSION', tf_cuda_version)
881
882
Yifei Fengb1d8c592017-11-22 13:42:21 -0800883def set_tf_cudnn_version(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700884 """Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION."""
885 ask_cudnn_version = (
Jonathan Hseu008910f2017-08-25 14:01:05 -0700886 'Please specify the cuDNN version you want to use. '
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700887 '[Leave empty to default to cuDNN %s.0]: ') % _DEFAULT_CUDNN_VERSION
888
Austin Andersonf9a88f82017-12-13 11:49:40 -0800889 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700890 tf_cudnn_version = get_from_env_or_user_or_default(
891 environ_cp, 'TF_CUDNN_VERSION', ask_cudnn_version,
892 _DEFAULT_CUDNN_VERSION)
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800893 tf_cudnn_version = reformat_version_sequence(str(tf_cudnn_version), 1)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700894
895 default_cudnn_path = environ_cp.get('CUDA_TOOLKIT_PATH')
896 ask_cudnn_path = (r'Please specify the location where cuDNN %s library is '
897 'installed. Refer to README.md for more details. [Default'
A. Unique TensorFlower1b212352018-07-19 13:48:50 -0700898 ' is %s]: ') % (tf_cudnn_version, default_cudnn_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700899 cudnn_install_path = get_from_env_or_user_or_default(
900 environ_cp, 'CUDNN_INSTALL_PATH', ask_cudnn_path, default_cudnn_path)
901
902 # Result returned from "read" will be used unexpanded. That make "~"
903 # unusable. Going through one more level of expansion to handle that.
904 cudnn_install_path = os.path.realpath(
905 os.path.expanduser(cudnn_install_path))
Martin Wicked57572e2017-09-02 19:21:45 -0700906 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700907 cudnn_install_path = cygpath(cudnn_install_path)
908
909 if is_windows():
910 cuda_dnn_lib_path = 'lib/x64/cudnn.lib'
911 cuda_dnn_lib_alt_path = 'lib/x64/cudnn.lib'
912 elif is_linux():
913 cuda_dnn_lib_path = 'lib64/libcudnn.so.%s' % tf_cudnn_version
914 cuda_dnn_lib_alt_path = 'libcudnn.so.%s' % tf_cudnn_version
915 elif is_macos():
916 cuda_dnn_lib_path = 'lib/libcudnn.%s.dylib' % tf_cudnn_version
917 cuda_dnn_lib_alt_path = 'libcudnn.%s.dylib' % tf_cudnn_version
918
919 cuda_dnn_lib_path_full = os.path.join(cudnn_install_path, cuda_dnn_lib_path)
920 cuda_dnn_lib_alt_path_full = os.path.join(cudnn_install_path,
921 cuda_dnn_lib_alt_path)
922 if os.path.exists(cuda_dnn_lib_path_full) or os.path.exists(
923 cuda_dnn_lib_alt_path_full):
924 break
925
926 # Try another alternative for Linux
927 if is_linux():
Jonathan Hseu008910f2017-08-25 14:01:05 -0700928 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
929 cudnn_path_from_ldconfig = run_shell([ldconfig_bin, '-p'])
930 cudnn_path_from_ldconfig = re.search('.*libcudnn.so .* => (.*)',
A. Unique TensorFlowere7223582017-09-06 17:57:04 -0700931 cudnn_path_from_ldconfig)
932 if cudnn_path_from_ldconfig:
933 cudnn_path_from_ldconfig = cudnn_path_from_ldconfig.group(1)
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700934 if os.path.exists(
935 '%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version)):
A. Unique TensorFlowere7223582017-09-06 17:57:04 -0700936 cudnn_install_path = os.path.dirname(cudnn_path_from_ldconfig)
937 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700938
939 # Reset and Retry
940 print(
941 'Invalid path to cuDNN %s toolkit. None of the following files can be '
942 'found:' % tf_cudnn_version)
943 print(cuda_dnn_lib_path_full)
944 print(cuda_dnn_lib_alt_path_full)
945 if is_linux():
946 print('%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version))
947
948 environ_cp['TF_CUDNN_VERSION'] = ''
Austin Andersonf9a88f82017-12-13 11:49:40 -0800949 else:
950 raise UserInputError('Invalid TF_CUDNN setting was provided %d '
951 'times in a row. Assuming to be a scripting mistake.' %
952 _DEFAULT_PROMPT_ASK_ATTEMPTS)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700953
954 # Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION
955 environ_cp['CUDNN_INSTALL_PATH'] = cudnn_install_path
956 write_action_env_to_bazelrc('CUDNN_INSTALL_PATH', cudnn_install_path)
957 environ_cp['TF_CUDNN_VERSION'] = tf_cudnn_version
958 write_action_env_to_bazelrc('TF_CUDNN_VERSION', tf_cudnn_version)
959
960
Mingxing Tan1e7b0e42018-06-28 19:13:20 -0700961def is_cuda_compatible(lib, cuda_ver, cudnn_ver):
962 """Check compatibility between given library and cudnn/cudart libraries."""
963 ldd_bin = which('ldd') or '/usr/bin/ldd'
964 ldd_out = run_shell([ldd_bin, lib], True)
965 ldd_out = ldd_out.split(os.linesep)
966 cudnn_pattern = re.compile('.*libcudnn.so\\.?(.*) =>.*$')
967 cuda_pattern = re.compile('.*libcudart.so\\.?(.*) =>.*$')
968 cudnn = None
969 cudart = None
970 cudnn_ok = True # assume no cudnn dependency by default
971 cuda_ok = True # assume no cuda dependency by default
972 for line in ldd_out:
973 if 'libcudnn.so' in line:
974 cudnn = cudnn_pattern.search(line)
975 cudnn_ok = False
976 elif 'libcudart.so' in line:
977 cudart = cuda_pattern.search(line)
978 cuda_ok = False
979 if cudnn and len(cudnn.group(1)):
980 cudnn = convert_version_to_int(cudnn.group(1))
981 if cudart and len(cudart.group(1)):
982 cudart = convert_version_to_int(cudart.group(1))
983 if cudnn is not None:
984 cudnn_ok = (cudnn == cudnn_ver)
985 if cudart is not None:
986 cuda_ok = (cudart == cuda_ver)
987 return cudnn_ok and cuda_ok
988
989
Guangda Lai76f69382018-01-25 23:59:19 -0800990def set_tf_tensorrt_install_path(environ_cp):
991 """Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION.
992
993 Adapted from code contributed by Sami Kama (https://github.com/samikama).
994
995 Args:
996 environ_cp: copy of the os.environ.
997
998 Raises:
999 ValueError: if this method was called under non-Linux platform.
1000 UserInputError: if user has provided invalid input multiple times.
1001 """
1002 if not is_linux():
1003 raise ValueError('Currently TensorRT is only supported on Linux platform.')
1004
1005 # Ask user whether to add TensorRT support.
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001006 if str(int(get_var(environ_cp, 'TF_NEED_TENSORRT', 'TensorRT',
1007 False))) != '1':
Guangda Lai76f69382018-01-25 23:59:19 -08001008 return
1009
1010 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
1011 ask_tensorrt_path = (r'Please specify the location where TensorRT is '
1012 'installed. [Default is %s]:') % (
1013 _DEFAULT_TENSORRT_PATH_LINUX)
1014 trt_install_path = get_from_env_or_user_or_default(
1015 environ_cp, 'TENSORRT_INSTALL_PATH', ask_tensorrt_path,
1016 _DEFAULT_TENSORRT_PATH_LINUX)
1017
1018 # Result returned from "read" will be used unexpanded. That make "~"
1019 # unusable. Going through one more level of expansion to handle that.
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001020 trt_install_path = os.path.realpath(os.path.expanduser(trt_install_path))
Guangda Lai76f69382018-01-25 23:59:19 -08001021
1022 def find_libs(search_path):
1023 """Search for libnvinfer.so in "search_path"."""
1024 fl = set()
1025 if os.path.exists(search_path) and os.path.isdir(search_path):
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001026 fl.update([
1027 os.path.realpath(os.path.join(search_path, x))
1028 for x in os.listdir(search_path)
1029 if 'libnvinfer.so' in x
1030 ])
Guangda Lai76f69382018-01-25 23:59:19 -08001031 return fl
1032
1033 possible_files = find_libs(trt_install_path)
1034 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib')))
1035 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib64')))
Guangda Lai76f69382018-01-25 23:59:19 -08001036 cuda_ver = convert_version_to_int(environ_cp['TF_CUDA_VERSION'])
1037 cudnn_ver = convert_version_to_int(environ_cp['TF_CUDNN_VERSION'])
1038 nvinfer_pattern = re.compile('.*libnvinfer.so.?(.*)$')
1039 highest_ver = [0, None, None]
1040
1041 for lib_file in possible_files:
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001042 if is_cuda_compatible(lib_file, cuda_ver, cudnn_ver):
Jacques Pienaar2d0531d2018-03-21 12:07:51 -07001043 matches = nvinfer_pattern.search(lib_file)
1044 if len(matches.groups()) == 0:
1045 continue
1046 ver_str = matches.group(1)
Guangda Lai76f69382018-01-25 23:59:19 -08001047 ver = convert_version_to_int(ver_str) if len(ver_str) else 0
1048 if ver > highest_ver[0]:
1049 highest_ver = [ver, ver_str, lib_file]
1050 if highest_ver[1] is not None:
1051 trt_install_path = os.path.dirname(highest_ver[2])
1052 tf_tensorrt_version = highest_ver[1]
1053 break
1054
1055 # Try another alternative from ldconfig.
1056 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
1057 ldconfig_output = run_shell([ldconfig_bin, '-p'])
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001058 search_result = re.search('.*libnvinfer.so\\.?([0-9.]*).* => (.*)',
1059 ldconfig_output)
Guangda Lai76f69382018-01-25 23:59:19 -08001060 if search_result:
1061 libnvinfer_path_from_ldconfig = search_result.group(2)
1062 if os.path.exists(libnvinfer_path_from_ldconfig):
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001063 if is_cuda_compatible(libnvinfer_path_from_ldconfig, cuda_ver,
1064 cudnn_ver):
Guangda Lai76f69382018-01-25 23:59:19 -08001065 trt_install_path = os.path.dirname(libnvinfer_path_from_ldconfig)
1066 tf_tensorrt_version = search_result.group(1)
1067 break
1068
1069 # Reset and Retry
Yifei Fengdce9a492018-02-22 14:24:57 -08001070 if possible_files:
1071 print('TensorRT libraries found in one the following directories',
1072 'are not compatible with selected cuda and cudnn installations')
1073 print(trt_install_path)
1074 print(os.path.join(trt_install_path, 'lib'))
1075 print(os.path.join(trt_install_path, 'lib64'))
1076 if search_result:
1077 print(libnvinfer_path_from_ldconfig)
1078 else:
1079 print(
1080 'Invalid path to TensorRT. None of the following files can be found:')
1081 print(trt_install_path)
1082 print(os.path.join(trt_install_path, 'lib'))
1083 print(os.path.join(trt_install_path, 'lib64'))
1084 if search_result:
1085 print(libnvinfer_path_from_ldconfig)
Guangda Lai76f69382018-01-25 23:59:19 -08001086
1087 else:
1088 raise UserInputError('Invalid TF_TENSORRT setting was provided %d '
1089 'times in a row. Assuming to be a scripting mistake.' %
1090 _DEFAULT_PROMPT_ASK_ATTEMPTS)
1091
1092 # Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION
1093 environ_cp['TENSORRT_INSTALL_PATH'] = trt_install_path
1094 write_action_env_to_bazelrc('TENSORRT_INSTALL_PATH', trt_install_path)
1095 environ_cp['TF_TENSORRT_VERSION'] = tf_tensorrt_version
1096 write_action_env_to_bazelrc('TF_TENSORRT_VERSION', tf_tensorrt_version)
1097
1098
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001099def set_tf_nccl_install_path(environ_cp):
1100 """Set NCCL_INSTALL_PATH and TF_NCCL_VERSION.
1101
1102 Args:
1103 environ_cp: copy of the os.environ.
1104
1105 Raises:
1106 ValueError: if this method was called under non-Linux platform.
1107 UserInputError: if user has provided invalid input multiple times.
1108 """
1109 if not is_linux():
1110 raise ValueError('Currently NCCL is only supported on Linux platforms.')
1111
1112 ask_nccl_version = (
Smit Hinsu63e6b9b2018-07-13 12:46:24 -07001113 'Please specify the NCCL version you want to use. If NCCL %s is not '
1114 'installed, then you can use version 1.3 that can be fetched '
1115 'automatically but it may have worse performance with multiple GPUs. '
1116 '[Default is %s]: ') % (_DEFAULT_NCCL_VERSION, _DEFAULT_NCCL_VERSION)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001117
1118 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
1119 tf_nccl_version = get_from_env_or_user_or_default(
1120 environ_cp, 'TF_NCCL_VERSION', ask_nccl_version, _DEFAULT_NCCL_VERSION)
1121 tf_nccl_version = reformat_version_sequence(str(tf_nccl_version), 1)
1122
1123 if tf_nccl_version == '1':
1124 break # No need to get install path, NCCL 1 is a GitHub repo.
1125
1126 # TODO(csigg): Look with ldconfig first if we can find the library in paths
1127 # like /usr/lib/x86_64-linux-gnu and the header file in the corresponding
1128 # include directory. This is where the NCCL .deb packages install them.
1129 # Then ask the user if we should use that. Instead of a single
1130 # NCCL_INSTALL_PATH, pass separate NCCL_LIB_PATH and NCCL_HDR_PATH to
1131 # nccl_configure.bzl
1132 default_nccl_path = environ_cp.get('CUDA_TOOLKIT_PATH')
1133 ask_nccl_path = (r'Please specify the location where NCCL %s library is '
1134 'installed. Refer to README.md for more details. [Default '
1135 'is %s]:') % (tf_nccl_version, default_nccl_path)
1136 nccl_install_path = get_from_env_or_user_or_default(
1137 environ_cp, 'NCCL_INSTALL_PATH', ask_nccl_path, default_nccl_path)
1138
1139 # Result returned from "read" will be used unexpanded. That make "~"
1140 # unusable. Going through one more level of expansion to handle that.
1141 nccl_install_path = os.path.realpath(os.path.expanduser(nccl_install_path))
1142 if is_windows() or is_cygwin():
1143 nccl_install_path = cygpath(nccl_install_path)
1144
1145 if is_windows():
1146 nccl_lib_path = 'lib/x64/nccl.lib'
1147 elif is_linux():
1148 nccl_lib_path = 'lib/libnccl.so.%s' % tf_nccl_version
1149 elif is_macos():
1150 nccl_lib_path = 'lib/libnccl.%s.dylib' % tf_nccl_version
1151
1152 nccl_lib_path = os.path.join(nccl_install_path, nccl_lib_path)
1153 nccl_hdr_path = os.path.join(nccl_install_path, 'include/nccl.h')
1154 if os.path.exists(nccl_lib_path) and os.path.exists(nccl_hdr_path):
1155 # Set NCCL_INSTALL_PATH
1156 environ_cp['NCCL_INSTALL_PATH'] = nccl_install_path
1157 write_action_env_to_bazelrc('NCCL_INSTALL_PATH', nccl_install_path)
1158 break
1159
1160 # Reset and Retry
1161 print('Invalid path to NCCL %s toolkit, %s or %s not found. Please use the '
1162 'O/S agnostic package of NCCL 2' % (tf_nccl_version, nccl_lib_path,
1163 nccl_hdr_path))
1164
1165 environ_cp['TF_NCCL_VERSION'] = ''
1166 else:
1167 raise UserInputError('Invalid TF_NCCL setting was provided %d '
1168 'times in a row. Assuming to be a scripting mistake.' %
1169 _DEFAULT_PROMPT_ASK_ATTEMPTS)
1170
1171 # Set TF_NCCL_VERSION
1172 environ_cp['TF_NCCL_VERSION'] = tf_nccl_version
1173 write_action_env_to_bazelrc('TF_NCCL_VERSION', tf_nccl_version)
1174
1175
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001176def get_native_cuda_compute_capabilities(environ_cp):
1177 """Get native cuda compute capabilities.
1178
1179 Args:
1180 environ_cp: copy of the os.environ.
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001181
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001182 Returns:
1183 string of native cuda compute capabilities, separated by comma.
1184 """
1185 device_query_bin = os.path.join(
1186 environ_cp.get('CUDA_TOOLKIT_PATH'), 'extras/demo_suite/deviceQuery')
Jonathan Hseu008910f2017-08-25 14:01:05 -07001187 if os.path.isfile(device_query_bin) and os.access(device_query_bin, os.X_OK):
1188 try:
1189 output = run_shell(device_query_bin).split('\n')
1190 pattern = re.compile('[0-9]*\\.[0-9]*')
1191 output = [pattern.search(x) for x in output if 'Capability' in x]
1192 output = ','.join(x.group() for x in output if x is not None)
1193 except subprocess.CalledProcessError:
1194 output = ''
1195 else:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001196 output = ''
1197 return output
1198
1199
1200def set_tf_cuda_compute_capabilities(environ_cp):
1201 """Set TF_CUDA_COMPUTE_CAPABILITIES."""
1202 while True:
1203 native_cuda_compute_capabilities = get_native_cuda_compute_capabilities(
1204 environ_cp)
1205 if not native_cuda_compute_capabilities:
1206 default_cuda_compute_capabilities = _DEFAULT_CUDA_COMPUTE_CAPABILITIES
1207 else:
1208 default_cuda_compute_capabilities = native_cuda_compute_capabilities
1209
1210 ask_cuda_compute_capabilities = (
1211 'Please specify a list of comma-separated '
1212 'Cuda compute capabilities you want to '
1213 'build with.\nYou can find the compute '
1214 'capability of your device at: '
1215 'https://developer.nvidia.com/cuda-gpus.\nPlease'
1216 ' note that each additional compute '
1217 'capability significantly increases your '
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001218 'build time and binary size. [Default is: %s]: ' %
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001219 default_cuda_compute_capabilities)
1220 tf_cuda_compute_capabilities = get_from_env_or_user_or_default(
1221 environ_cp, 'TF_CUDA_COMPUTE_CAPABILITIES',
1222 ask_cuda_compute_capabilities, default_cuda_compute_capabilities)
1223 # Check whether all capabilities from the input is valid
1224 all_valid = True
Maciejd0f5bc12018-04-30 22:30:58 -05001225 # Remove all whitespace characters before splitting the string
Michael Case51053502018-06-05 17:47:19 -07001226 # that users may insert by accident, as this will result in error
Maciejd0f5bc12018-04-30 22:30:58 -05001227 tf_cuda_compute_capabilities = ''.join(tf_cuda_compute_capabilities.split())
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001228 for compute_capability in tf_cuda_compute_capabilities.split(','):
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001229 m = re.match('[0-9]+.[0-9]+', compute_capability)
1230 if not m:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001231 print('Invalid compute capability: ' % compute_capability)
1232 all_valid = False
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001233 else:
1234 ver = int(m.group(0).split('.')[0])
1235 if ver < 3:
1236 print('Only compute capabilities 3.0 or higher are supported.')
1237 all_valid = False
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001238
1239 if all_valid:
1240 break
1241
1242 # Reset and Retry
1243 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = ''
1244
1245 # Set TF_CUDA_COMPUTE_CAPABILITIES
1246 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = tf_cuda_compute_capabilities
1247 write_action_env_to_bazelrc('TF_CUDA_COMPUTE_CAPABILITIES',
1248 tf_cuda_compute_capabilities)
1249
1250
1251def set_other_cuda_vars(environ_cp):
1252 """Set other CUDA related variables."""
A. Unique TensorFlowerab391982018-07-11 04:52:49 -07001253 # If CUDA is enabled, always use GPU during build and test.
1254 if environ_cp.get('TF_CUDA_CLANG') == '1':
1255 write_to_bazelrc('build --config=cuda_clang')
1256 write_to_bazelrc('test --config=cuda_clang')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001257 else:
A. Unique TensorFlowerab391982018-07-11 04:52:49 -07001258 write_to_bazelrc('build --config=cuda')
1259 write_to_bazelrc('test --config=cuda')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001260
1261
1262def set_host_cxx_compiler(environ_cp):
1263 """Set HOST_CXX_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001264 default_cxx_host_compiler = which('g++') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001265
Austin Anderson6afface2017-12-05 11:59:17 -08001266 host_cxx_compiler = prompt_loop_or_load_from_env(
1267 environ_cp,
1268 var_name='HOST_CXX_COMPILER',
1269 var_default=default_cxx_host_compiler,
1270 ask_for_var=('Please specify which C++ compiler should be used as the '
1271 'host C++ compiler.'),
1272 check_success=os.path.exists,
1273 error_msg='Invalid C++ compiler path. %s cannot be found.',
1274 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001275
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001276 write_action_env_to_bazelrc('HOST_CXX_COMPILER', host_cxx_compiler)
1277
1278
1279def set_host_c_compiler(environ_cp):
1280 """Set HOST_C_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001281 default_c_host_compiler = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001282
Austin Anderson6afface2017-12-05 11:59:17 -08001283 host_c_compiler = prompt_loop_or_load_from_env(
1284 environ_cp,
1285 var_name='HOST_C_COMPILER',
1286 var_default=default_c_host_compiler,
Shanqing Cai71445712018-03-12 19:33:52 -07001287 ask_for_var=('Please specify which C compiler should be used as the host '
Austin Anderson6afface2017-12-05 11:59:17 -08001288 'C compiler.'),
1289 check_success=os.path.exists,
1290 error_msg='Invalid C compiler path. %s cannot be found.',
1291 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001292
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001293 write_action_env_to_bazelrc('HOST_C_COMPILER', host_c_compiler)
1294
1295
1296def set_computecpp_toolkit_path(environ_cp):
1297 """Set COMPUTECPP_TOOLKIT_PATH."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001298
Austin Anderson6afface2017-12-05 11:59:17 -08001299 def toolkit_exists(toolkit_path):
1300 """Check if a computecpp toolkit path is valid."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001301 if is_linux():
1302 sycl_rt_lib_path = 'lib/libComputeCpp.so'
1303 else:
1304 sycl_rt_lib_path = ''
1305
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001306 sycl_rt_lib_path_full = os.path.join(toolkit_path, sycl_rt_lib_path)
Austin Anderson6afface2017-12-05 11:59:17 -08001307 exists = os.path.exists(sycl_rt_lib_path_full)
1308 if not exists:
1309 print('Invalid SYCL %s library path. %s cannot be found' %
1310 (_TF_OPENCL_VERSION, sycl_rt_lib_path_full))
1311 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001312
Austin Anderson6afface2017-12-05 11:59:17 -08001313 computecpp_toolkit_path = prompt_loop_or_load_from_env(
1314 environ_cp,
1315 var_name='COMPUTECPP_TOOLKIT_PATH',
1316 var_default=_DEFAULT_COMPUTECPP_TOOLKIT_PATH,
1317 ask_for_var=(
1318 'Please specify the location where ComputeCpp for SYCL %s is '
1319 'installed.' % _TF_OPENCL_VERSION),
1320 check_success=toolkit_exists,
1321 error_msg='Invalid SYCL compiler path. %s cannot be found.',
1322 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001323
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001324 write_action_env_to_bazelrc('COMPUTECPP_TOOLKIT_PATH',
1325 computecpp_toolkit_path)
1326
Michael Cased31531a2018-01-05 14:09:41 -08001327
Dandelion Man?90e42f32017-12-15 18:15:07 -08001328def set_trisycl_include_dir(environ_cp):
Michael Cased31531a2018-01-05 14:09:41 -08001329 """Set TRISYCL_INCLUDE_DIR."""
Frank Chenc4ef9272018-01-10 11:36:52 -08001330
Dandelion Man?90e42f32017-12-15 18:15:07 -08001331 ask_trisycl_include_dir = ('Please specify the location of the triSYCL '
1332 'include directory. (Use --config=sycl_trisycl '
1333 'when building with Bazel) '
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001334 '[Default is %s]: ') % (
1335 _DEFAULT_TRISYCL_INCLUDE_DIR)
Frank Chenc4ef9272018-01-10 11:36:52 -08001336
Dandelion Man?90e42f32017-12-15 18:15:07 -08001337 while True:
1338 trisycl_include_dir = get_from_env_or_user_or_default(
Michael Cased31531a2018-01-05 14:09:41 -08001339 environ_cp, 'TRISYCL_INCLUDE_DIR', ask_trisycl_include_dir,
1340 _DEFAULT_TRISYCL_INCLUDE_DIR)
Dandelion Man?90e42f32017-12-15 18:15:07 -08001341 if os.path.exists(trisycl_include_dir):
1342 break
1343
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001344 print('Invalid triSYCL include directory, %s cannot be found' %
1345 (trisycl_include_dir))
Dandelion Man?90e42f32017-12-15 18:15:07 -08001346
1347 # Set TRISYCL_INCLUDE_DIR
1348 environ_cp['TRISYCL_INCLUDE_DIR'] = trisycl_include_dir
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001349 write_action_env_to_bazelrc('TRISYCL_INCLUDE_DIR', trisycl_include_dir)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001350
Yifei Fengb1d8c592017-11-22 13:42:21 -08001351
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001352def set_mpi_home(environ_cp):
1353 """Set MPI_HOME."""
Austin Anderson6afface2017-12-05 11:59:17 -08001354
Jonathan Hseu008910f2017-08-25 14:01:05 -07001355 default_mpi_home = which('mpirun') or which('mpiexec') or ''
1356 default_mpi_home = os.path.dirname(os.path.dirname(default_mpi_home))
1357
Austin Anderson6afface2017-12-05 11:59:17 -08001358 def valid_mpi_path(mpi_home):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001359 exists = (
1360 os.path.exists(os.path.join(mpi_home, 'include')) and
1361 os.path.exists(os.path.join(mpi_home, 'lib')))
Austin Anderson6afface2017-12-05 11:59:17 -08001362 if not exists:
1363 print('Invalid path to the MPI Toolkit. %s or %s cannot be found' %
1364 (os.path.join(mpi_home, 'include'),
1365 os.path.exists(os.path.join(mpi_home, 'lib'))))
1366 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001367
Austin Anderson6afface2017-12-05 11:59:17 -08001368 _ = prompt_loop_or_load_from_env(
1369 environ_cp,
1370 var_name='MPI_HOME',
1371 var_default=default_mpi_home,
1372 ask_for_var='Please specify the MPI toolkit folder.',
1373 check_success=valid_mpi_path,
1374 error_msg='',
1375 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001376
1377
1378def set_other_mpi_vars(environ_cp):
1379 """Set other MPI related variables."""
1380 # Link the MPI header files
1381 mpi_home = environ_cp.get('MPI_HOME')
1382 symlink_force('%s/include/mpi.h' % mpi_home, 'third_party/mpi/mpi.h')
1383
1384 # Determine if we use OpenMPI or MVAPICH, these require different header files
1385 # to be included here to make bazel dependency checker happy
1386 if os.path.exists(os.path.join(mpi_home, 'include/mpi_portable_platform.h')):
1387 symlink_force(
1388 os.path.join(mpi_home, 'include/mpi_portable_platform.h'),
1389 'third_party/mpi/mpi_portable_platform.h')
1390 # TODO(gunan): avoid editing files in configure
1391 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=False',
1392 'MPI_LIB_IS_OPENMPI=True')
1393 else:
1394 # MVAPICH / MPICH
1395 symlink_force(
1396 os.path.join(mpi_home, 'include/mpio.h'), 'third_party/mpi/mpio.h')
1397 symlink_force(
1398 os.path.join(mpi_home, 'include/mpicxx.h'), 'third_party/mpi/mpicxx.h')
1399 # TODO(gunan): avoid editing files in configure
1400 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=True',
1401 'MPI_LIB_IS_OPENMPI=False')
1402
1403 if os.path.exists(os.path.join(mpi_home, 'lib/libmpi.so')):
1404 symlink_force(
1405 os.path.join(mpi_home, 'lib/libmpi.so'), 'third_party/mpi/libmpi.so')
1406 else:
1407 raise ValueError('Cannot find the MPI library file in %s/lib' % mpi_home)
1408
1409
Yifei Feng5198cb82018-08-17 13:53:06 -07001410def set_system_libs_flag(environ_cp):
1411 syslibs = environ_cp.get('TF_SYSTEM_LIBS', '')
Yifei Feng5198cb82018-08-17 13:53:06 -07001412 if syslibs and syslibs != '':
Jason Zaman5fc39bd2018-09-16 01:38:55 +08001413 if ',' in syslibs:
1414 syslibs = ','.join(sorted(syslibs.split(',')))
1415 else:
1416 syslibs = ','.join(sorted(syslibs.split()))
Yifei Feng5198cb82018-08-17 13:53:06 -07001417 write_action_env_to_bazelrc('TF_SYSTEM_LIBS', syslibs)
1418
Jason Zaman5fc39bd2018-09-16 01:38:55 +08001419 if 'PREFIX' in environ_cp:
1420 write_to_bazelrc('build --define=PREFIX=%s' % environ_cp['PREFIX'])
1421 if 'LIBDIR' in environ_cp:
1422 write_to_bazelrc('build --define=LIBDIR=%s' % environ_cp['LIBDIR'])
1423 if 'INCLUDEDIR' in environ_cp:
1424 write_to_bazelrc('build --define=INCLUDEDIR=%s' % environ_cp['INCLUDEDIR'])
1425
Yifei Feng5198cb82018-08-17 13:53:06 -07001426
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001427def set_windows_build_flags(environ_cp):
1428 """Set Windows specific build options."""
1429 # The non-monolithic build is not supported yet
1430 write_to_bazelrc('build --config monolithic')
1431 # Suppress warning messages
1432 write_to_bazelrc('build --copt=-w --host_copt=-w')
1433 # Output more verbose information when something goes wrong
1434 write_to_bazelrc('build --verbose_failures')
1435 # The host and target platforms are the same in Windows build. So we don't
1436 # have to distinct them. This avoids building the same targets twice.
1437 write_to_bazelrc('build --distinct_host_configuration=false')
1438 # Enable short object file path to avoid long path issue on Windows.
1439 # TODO(pcloudy): Remove this flag when upgrading Bazel to 0.16.0
1440 # Short object file path will be enabled by default.
1441 write_to_bazelrc('build --experimental_shortened_obj_file_path=true')
A. Unique TensorFlower77e26862018-09-27 06:19:58 -07001442 # When building zip file for some py_binary and py_test targets, don't
1443 # include its dependencies. This is for:
1444 # 1. Running python tests against the system installed TF pip package.
1445 # 2. Avoiding redundant files in
1446 # //tensorflow/tools/pip_package:simple_console_windows,
1447 # which is a py_binary used during creating TF pip package.
1448 # See https://github.com/tensorflow/tensorflow/issues/22390
1449 write_to_bazelrc('build --define=no_tensorflow_py_deps=true')
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001450
1451 if get_var(
1452 environ_cp, 'TF_OVERRIDE_EIGEN_STRONG_INLINE', 'Eigen strong inline',
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001453 True, ('Would you like to override eigen strong inline for some C++ '
1454 'compilation to reduce the compilation time?'),
1455 'Eigen strong inline overridden.', 'Not overriding eigen strong inline, '
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001456 'some compilations could take more than 20 mins.'):
1457 # Due to a known MSVC compiler issue
1458 # https://github.com/tensorflow/tensorflow/issues/10521
1459 # Overriding eigen strong inline speeds up the compiling of
1460 # conv_grad_ops_3d.cc and conv_ops_3d.cc by 20 minutes,
1461 # but this also hurts the performance. Let users decide what they want.
1462 write_to_bazelrc('build --define=override_eigen_strong_inline=true')
Dandelion Man?90e42f32017-12-15 18:15:07 -08001463
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001464
Michael Cased31531a2018-01-05 14:09:41 -08001465def config_info_line(name, help_text):
1466 """Helper function to print formatted help text for Bazel config options."""
1467 print('\t--config=%-12s\t# %s' % (name, help_text))
1468
1469
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001470def main():
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001471 global _TF_WORKSPACE_ROOT
1472 global _TF_BAZELRC
1473
Shanqing Cai71445712018-03-12 19:33:52 -07001474 parser = argparse.ArgumentParser()
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001475 parser.add_argument(
1476 '--workspace',
1477 type=str,
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001478 default=os.path.abspath(os.path.dirname(__file__)),
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001479 help='The absolute path to your active Bazel workspace.')
Shanqing Cai71445712018-03-12 19:33:52 -07001480 args = parser.parse_args()
1481
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001482 _TF_WORKSPACE_ROOT = args.workspace
1483 _TF_BAZELRC = os.path.join(_TF_WORKSPACE_ROOT, _TF_BAZELRC_FILENAME)
1484
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001485 # Make a copy of os.environ to be clear when functions and getting and setting
1486 # environment variables.
1487 environ_cp = dict(os.environ)
1488
Yifei Fengbb384112018-07-24 13:12:54 -07001489 check_bazel_version('0.15.0')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001490
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001491 reset_tf_configure_bazelrc()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001492 cleanup_makefile()
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -07001493 setup_python(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001494
1495 if is_windows():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001496 environ_cp['TF_NEED_JEMALLOC'] = '0'
Yifei Fengb1d8c592017-11-22 13:42:21 -08001497 environ_cp['TF_NEED_OPENCL_SYCL'] = '0'
1498 environ_cp['TF_NEED_COMPUTECPP'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001499 environ_cp['TF_NEED_OPENCL'] = '0'
1500 environ_cp['TF_CUDA_CLANG'] = '0'
Guangda Lai76f69382018-01-25 23:59:19 -08001501 environ_cp['TF_NEED_TENSORRT'] = '0'
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001502 # TODO(ibiryukov): Investigate using clang as a cpu or cuda compiler on
1503 # Windows.
1504 environ_cp['TF_DOWNLOAD_CLANG'] = '0'
A. Unique TensorFlower6e97fb32018-07-16 14:07:29 -07001505 environ_cp['TF_ENABLE_XLA'] = '0'
A. Unique TensorFlower6e97fb32018-07-16 14:07:29 -07001506 environ_cp['TF_NEED_MPI'] = '0'
1507 environ_cp['TF_SET_ANDROID_WORKSPACE'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001508
1509 if is_macos():
1510 environ_cp['TF_NEED_JEMALLOC'] = '0'
Guangda Lai76f69382018-01-25 23:59:19 -08001511 environ_cp['TF_NEED_TENSORRT'] = '0'
Todd Wang35459cb2018-09-28 08:56:06 -07001512 environ_cp['TF_ENABLE_XLA'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001513
Jon Triebenbach6896a742018-06-27 13:29:53 -05001514 # The numpy package on ppc64le uses OpenBLAS which has multi-threading
1515 # issues that lead to incorrect answers. Set OMP_NUM_THREADS=1 at
1516 # runtime to allow the Tensorflow testcases which compare numpy
1517 # results to Tensorflow results to succeed.
1518 if is_ppc64le():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001519 write_action_env_to_bazelrc('OMP_NUM_THREADS', 1)
Jon Triebenbach6896a742018-06-27 13:29:53 -05001520
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001521 set_build_var(environ_cp, 'TF_ENABLE_XLA', 'XLA JIT', 'with_xla_support',
Todd Wang35459cb2018-09-28 08:56:06 -07001522 True, 'xla')
Gunhan Gulsoy3da0dff2018-09-26 11:55:50 -07001523
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001524
Yifei Fengb1d8c592017-11-22 13:42:21 -08001525 set_action_env_var(environ_cp, 'TF_NEED_OPENCL_SYCL', 'OpenCL SYCL', False)
1526 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001527 set_host_cxx_compiler(environ_cp)
1528 set_host_c_compiler(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001529 set_action_env_var(environ_cp, 'TF_NEED_COMPUTECPP', 'ComputeCPP', True)
1530 if environ_cp.get('TF_NEED_COMPUTECPP') == '1':
1531 set_computecpp_toolkit_path(environ_cp)
1532 else:
1533 set_trisycl_include_dir(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001534
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001535 set_action_env_var(environ_cp, 'TF_NEED_ROCM', 'ROCm', False)
1536 if (environ_cp.get('TF_NEED_ROCM') == '1' and
TensorFlower Gardener62e60162018-09-27 10:22:55 -07001537 'LD_LIBRARY_PATH' in environ_cp and
1538 environ_cp.get('LD_LIBRARY_PATH') != '1'):
1539 write_action_env_to_bazelrc('LD_LIBRARY_PATH',
1540 environ_cp.get('LD_LIBRARY_PATH'))
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001541
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001542 set_action_env_var(environ_cp, 'TF_NEED_CUDA', 'CUDA', False)
A. Unique TensorFlower24cbb2a2017-09-08 07:45:44 -07001543 if (environ_cp.get('TF_NEED_CUDA') == '1' and
1544 'TF_CUDA_CONFIG_REPO' not in environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001545 set_tf_cuda_version(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001546 set_tf_cudnn_version(environ_cp)
Guangda Lai76f69382018-01-25 23:59:19 -08001547 if is_linux():
1548 set_tf_tensorrt_install_path(environ_cp)
Michael Case0073d132018-04-11 09:34:44 -07001549 set_tf_nccl_install_path(environ_cp)
1550
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001551 set_tf_cuda_compute_capabilities(environ_cp)
Ankur Taly0e6f39d2018-02-16 18:22:55 -08001552 if 'LD_LIBRARY_PATH' in environ_cp and environ_cp.get(
1553 'LD_LIBRARY_PATH') != '1':
1554 write_action_env_to_bazelrc('LD_LIBRARY_PATH',
1555 environ_cp.get('LD_LIBRARY_PATH'))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001556
1557 set_tf_cuda_clang(environ_cp)
1558 if environ_cp.get('TF_CUDA_CLANG') == '1':
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001559 # Ask whether we should download the clang toolchain.
1560 set_tf_download_clang(environ_cp)
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -08001561 if environ_cp.get('TF_DOWNLOAD_CLANG') != '1':
1562 # Set up which clang we should use as the cuda / host compiler.
1563 set_clang_cuda_compiler_path(environ_cp)
Ilya Biryukov1c3d02e2018-09-04 03:09:52 -07001564 else:
1565 # Use downloaded LLD for linking.
1566 write_to_bazelrc('build:cuda_clang --config=download_clang_use_lld')
1567 write_to_bazelrc('test:cuda_clang --config=download_clang_use_lld')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001568 else:
1569 # Set up which gcc nvcc should use as the host compiler
1570 # No need to set this on Windows
1571 if not is_windows():
1572 set_gcc_host_compiler_path(environ_cp)
1573 set_other_cuda_vars(environ_cp)
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001574 else:
1575 # CUDA not required. Ask whether we should download the clang toolchain and
1576 # use it for the CPU build.
1577 set_tf_download_clang(environ_cp)
1578 if environ_cp.get('TF_DOWNLOAD_CLANG') == '1':
1579 write_to_bazelrc('build --config=download_clang')
1580 write_to_bazelrc('test --config=download_clang')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001581
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001582 # SYCL / ROCm / CUDA are mutually exclusive.
1583 # At most 1 GPU platform can be configured.
1584 gpu_platform_count = 0
1585 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
1586 gpu_platform_count += 1
1587 if environ_cp.get('TF_NEED_ROCM') == '1':
1588 gpu_platform_count += 1
1589 if environ_cp.get('TF_NEED_CUDA') == '1':
1590 gpu_platform_count += 1
1591 if gpu_platform_count >= 2:
1592 raise UserInputError('SYCL / CUDA / ROCm are mututally exclusive. '
1593 'At most 1 GPU platform can be configured.')
1594
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001595 set_build_var(environ_cp, 'TF_NEED_MPI', 'MPI', 'with_mpi_support', False)
1596 if environ_cp.get('TF_NEED_MPI') == '1':
1597 set_mpi_home(environ_cp)
1598 set_other_mpi_vars(environ_cp)
1599
1600 set_cc_opt_flags(environ_cp)
Yifei Feng5198cb82018-08-17 13:53:06 -07001601 set_system_libs_flag(environ_cp)
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001602 if is_windows():
1603 set_windows_build_flags(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001604
Anna Ra9a1d5a2018-09-14 12:44:31 -07001605 # Add a config option to build TensorFlow 2.0 API.
1606 write_to_bazelrc('build:v2 --define=tf_api_version=2')
1607
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001608 if get_var(environ_cp, 'TF_SET_ANDROID_WORKSPACE', 'android workspace', False,
1609 ('Would you like to interactively configure ./WORKSPACE for '
1610 'Android builds?'), 'Searching for NDK and SDK installations.',
1611 'Not configuring the WORKSPACE for Android builds.'):
Michael Case51053502018-06-05 17:47:19 -07001612 create_android_ndk_rule(environ_cp)
1613 create_android_sdk_rule(environ_cp)
Austin Anderson6afface2017-12-05 11:59:17 -08001614
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001615 # On Windows, we don't have MKL support and the build is always monolithic.
1616 # So no need to print the following message.
1617 # TODO(pcloudy): remove the following if check when they make sense on Windows
1618 if not is_windows():
1619 print('Preconfigured Bazel build configs. You can use any of the below by '
1620 'adding "--config=<>" to your build command. See tools/bazel.rc for '
1621 'more details.')
1622 config_info_line('mkl', 'Build with MKL support.')
1623 config_info_line('monolithic', 'Config for mostly static monolithic build.')
Gunhan Gulsoy3da0dff2018-09-26 11:55:50 -07001624 config_info_line('gdr', 'Build with GDR support.')
1625 config_info_line('verbs', 'Build with libverbs support.')
avijit-nervanaf172c522018-09-27 12:57:24 -07001626 config_info_line('ngraph', 'Build with Intel nGraph support.')
Austin Anderson6afface2017-12-05 11:59:17 -08001627
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001628
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001629if __name__ == '__main__':
1630 main()