blob: da3f97ab300af0b6f0026cbb2dfb0e504724b124 [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'
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -070038_DEFAULT_NCCL_VERSION = '1.3'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070039_DEFAULT_CUDA_COMPUTE_CAPABILITIES = '3.5,5.2'
40_DEFAULT_CUDA_PATH = '/usr/local/cuda'
41_DEFAULT_CUDA_PATH_LINUX = '/opt/cuda'
42_DEFAULT_CUDA_PATH_WIN = ('C:/Program Files/NVIDIA GPU Computing '
43 'Toolkit/CUDA/v%s' % _DEFAULT_CUDA_VERSION)
Benoit Steiner0dadbfe2018-03-22 18:54:27 -070044_DEFAULT_TENSORRT_PATH_LINUX = '/usr/lib/%s-linux-gnu' % platform.machine()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070045_TF_OPENCL_VERSION = '1.2'
46_DEFAULT_COMPUTECPP_TOOLKIT_PATH = '/usr/local/computecpp'
Yifei Fengb1d8c592017-11-22 13:42:21 -080047_DEFAULT_TRISYCL_INCLUDE_DIR = '/usr/local/triSYCL/include'
Austin Anderson6afface2017-12-05 11:59:17 -080048_SUPPORTED_ANDROID_NDK_VERSIONS = [10, 11, 12, 13, 14, 15]
49
50_DEFAULT_PROMPT_ASK_ATTEMPTS = 10
51
Shanqing Cai71445712018-03-12 19:33:52 -070052_TF_WORKSPACE_ROOT = os.path.abspath(os.path.dirname(__file__))
53_TF_BAZELRC_FILENAME = '.tf_configure.bazelrc'
54_TF_BAZELRC = os.path.join(_TF_WORKSPACE_ROOT, _TF_BAZELRC_FILENAME)
55_TF_WORKSPACE = os.path.join(_TF_WORKSPACE_ROOT, 'WORKSPACE')
56
Austin Anderson6afface2017-12-05 11:59:17 -080057
58class UserInputError(Exception):
59 pass
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070060
61
62def is_windows():
63 return platform.system() == 'Windows'
64
65
66def is_linux():
67 return platform.system() == 'Linux'
68
69
70def is_macos():
71 return platform.system() == 'Darwin'
72
73
74def is_ppc64le():
75 return platform.machine() == 'ppc64le'
76
77
Jonathan Hseu008910f2017-08-25 14:01:05 -070078def is_cygwin():
79 return platform.system().startswith('CYGWIN_NT')
80
81
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070082def get_input(question):
83 try:
84 try:
85 answer = raw_input(question)
86 except NameError:
87 answer = input(question) # pylint: disable=bad-builtin
88 except EOFError:
89 answer = ''
90 return answer
91
92
93def symlink_force(target, link_name):
94 """Force symlink, equivalent of 'ln -sf'.
95
96 Args:
97 target: items to link to.
98 link_name: name of the link.
99 """
100 try:
101 os.symlink(target, link_name)
102 except OSError as e:
103 if e.errno == errno.EEXIST:
104 os.remove(link_name)
105 os.symlink(target, link_name)
106 else:
107 raise e
108
109
110def sed_in_place(filename, old, new):
111 """Replace old string with new string in file.
112
113 Args:
114 filename: string for filename.
115 old: string to replace.
116 new: new string to replace to.
117 """
118 with open(filename, 'r') as f:
119 filedata = f.read()
120 newdata = filedata.replace(old, new)
121 with open(filename, 'w') as f:
122 f.write(newdata)
123
124
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700125def write_to_bazelrc(line):
126 with open(_TF_BAZELRC, 'a') as f:
127 f.write(line + '\n')
128
129
130def write_action_env_to_bazelrc(var_name, var):
131 write_to_bazelrc('build --action_env %s="%s"' % (var_name, str(var)))
132
133
Jonathan Hseu008910f2017-08-25 14:01:05 -0700134def run_shell(cmd, allow_non_zero=False):
135 if allow_non_zero:
136 try:
137 output = subprocess.check_output(cmd)
138 except subprocess.CalledProcessError as e:
139 output = e.output
140 else:
141 output = subprocess.check_output(cmd)
142 return output.decode('UTF-8').strip()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700143
144
145def cygpath(path):
146 """Convert path from posix to windows."""
Martin Wicked57572e2017-09-02 19:21:45 -0700147 return os.path.abspath(path).replace('\\', '/')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700148
149
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700150def get_python_path(environ_cp, python_bin_path):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700151 """Get the python site package paths."""
152 python_paths = []
153 if environ_cp.get('PYTHONPATH'):
154 python_paths = environ_cp.get('PYTHONPATH').split(':')
155 try:
Jonathan Hseu008910f2017-08-25 14:01:05 -0700156 library_paths = run_shell(
157 [python_bin_path, '-c',
Austin Anderson6afface2017-12-05 11:59:17 -0800158 'import site; print("\\n".join(site.getsitepackages()))']).split('\n')
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700159 except subprocess.CalledProcessError:
Jonathan Hseu008910f2017-08-25 14:01:05 -0700160 library_paths = [run_shell(
161 [python_bin_path, '-c',
162 'from distutils.sysconfig import get_python_lib;'
163 'print(get_python_lib())'])]
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700164
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700165 all_paths = set(python_paths + library_paths)
166
167 paths = []
168 for path in all_paths:
169 if os.path.isdir(path):
170 paths.append(path)
171 return paths
172
173
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700174def get_python_major_version(python_bin_path):
175 """Get the python major version."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700176 return run_shell([python_bin_path, '-c', 'import sys; print(sys.version[0])'])
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700177
178
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700179def setup_python(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700180 """Setup python related env variables."""
181 # Get PYTHON_BIN_PATH, default is the current running python.
182 default_python_bin_path = sys.executable
183 ask_python_bin_path = ('Please specify the location of python. [Default is '
184 '%s]: ') % default_python_bin_path
185 while True:
186 python_bin_path = get_from_env_or_user_or_default(
187 environ_cp, 'PYTHON_BIN_PATH', ask_python_bin_path,
188 default_python_bin_path)
189 # Check if the path is valid
Jonathan Hseu008910f2017-08-25 14:01:05 -0700190 if os.path.isfile(python_bin_path) and os.access(
191 python_bin_path, os.X_OK):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700192 break
193 elif not os.path.exists(python_bin_path):
194 print('Invalid python path: %s cannot be found.' % python_bin_path)
195 else:
196 print('%s is not executable. Is it the python binary?' % python_bin_path)
197 environ_cp['PYTHON_BIN_PATH'] = ''
198
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700199 # Convert python path to Windows style before checking lib and version
Martin Wicked57572e2017-09-02 19:21:45 -0700200 if is_windows() or is_cygwin():
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700201 python_bin_path = cygpath(python_bin_path)
202
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700203 # Get PYTHON_LIB_PATH
204 python_lib_path = environ_cp.get('PYTHON_LIB_PATH')
205 if not python_lib_path:
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700206 python_lib_paths = get_python_path(environ_cp, python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700207 if environ_cp.get('USE_DEFAULT_PYTHON_LIB_PATH') == '1':
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700208 python_lib_path = python_lib_paths[0]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700209 else:
Jonathan Hseu008910f2017-08-25 14:01:05 -0700210 print('Found possible Python library paths:\n %s' %
211 '\n '.join(python_lib_paths))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700212 default_python_lib_path = python_lib_paths[0]
213 python_lib_path = get_input(
Jonathan Hseu008910f2017-08-25 14:01:05 -0700214 'Please input the desired Python library path to use. '
215 'Default is [%s]\n' % python_lib_paths[0])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700216 if not python_lib_path:
217 python_lib_path = default_python_lib_path
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700218 environ_cp['PYTHON_LIB_PATH'] = python_lib_path
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700219
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700220 python_major_version = get_python_major_version(python_bin_path)
221
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700222 # Convert python path to Windows style before writing into bazel.rc
Martin Wicked57572e2017-09-02 19:21:45 -0700223 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700224 python_lib_path = cygpath(python_lib_path)
225
226 # Set-up env variables used by python_configure.bzl
227 write_action_env_to_bazelrc('PYTHON_BIN_PATH', python_bin_path)
228 write_action_env_to_bazelrc('PYTHON_LIB_PATH', python_lib_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700229 write_to_bazelrc('build --force_python=py%s' % python_major_version)
230 write_to_bazelrc('build --host_force_python=py%s' % python_major_version)
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700231 write_to_bazelrc('build --python_path=\"%s"' % python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700232 environ_cp['PYTHON_BIN_PATH'] = python_bin_path
233
234 # Write tools/python_bin_path.sh
Shanqing Cai71445712018-03-12 19:33:52 -0700235 with open(os.path.join(
236 _TF_WORKSPACE_ROOT, 'tools', 'python_bin_path.sh'), 'w') as f:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700237 f.write('export PYTHON_BIN_PATH="%s"' % python_bin_path)
238
239
Shanqing Cai71445712018-03-12 19:33:52 -0700240def reset_tf_configure_bazelrc(workspace_path):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700241 """Reset file that contains customized config settings."""
242 open(_TF_BAZELRC, 'w').close()
Shanqing Cai71445712018-03-12 19:33:52 -0700243 bazelrc_path = os.path.join(workspace_path, '.bazelrc')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700244
Shanqing Cai71445712018-03-12 19:33:52 -0700245 data = []
246 if os.path.exists(bazelrc_path):
247 with open(bazelrc_path, 'r') as f:
248 data = f.read().splitlines()
249 with open(bazelrc_path, 'w') as f:
250 for l in data:
251 if _TF_BAZELRC_FILENAME in l:
252 continue
253 f.write('%s\n' % l)
254 if is_windows():
255 tf_bazelrc_path = _TF_BAZELRC.replace("\\", "/")
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700256 else:
Shanqing Cai71445712018-03-12 19:33:52 -0700257 tf_bazelrc_path = _TF_BAZELRC
258 f.write('import %s\n' % tf_bazelrc_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700259
260
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700261def cleanup_makefile():
262 """Delete any leftover BUILD files from the Makefile build.
263
264 These files could interfere with Bazel parsing.
265 """
Shanqing Cai71445712018-03-12 19:33:52 -0700266 makefile_download_dir = os.path.join(
267 _TF_WORKSPACE_ROOT, 'tensorflow', 'contrib', 'makefile', 'downloads')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700268 if os.path.isdir(makefile_download_dir):
269 for root, _, filenames in os.walk(makefile_download_dir):
270 for f in filenames:
271 if f.endswith('BUILD'):
272 os.remove(os.path.join(root, f))
273
274
275def get_var(environ_cp,
276 var_name,
277 query_item,
278 enabled_by_default,
279 question=None,
280 yes_reply=None,
281 no_reply=None):
282 """Get boolean input from user.
283
284 If var_name is not set in env, ask user to enable query_item or not. If the
285 response is empty, use the default.
286
287 Args:
288 environ_cp: copy of the os.environ.
289 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
290 query_item: string for feature related to the variable, e.g. "Hadoop File
291 System".
292 enabled_by_default: boolean for default behavior.
293 question: optional string for how to ask for user input.
Michael Cased90054e2018-02-07 14:36:00 -0800294 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700295 no_reply: optional string for reply when feature is disabled.
296
297 Returns:
298 boolean value of the variable.
Frank Chenc4ef9272018-01-10 11:36:52 -0800299
300 Raises:
301 UserInputError: if an environment variable is set, but it cannot be
302 interpreted as a boolean indicator, assume that the user has made a
303 scripting error, and will continue to provide invalid input.
304 Raise the error to avoid infinitely looping.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700305 """
306 if not question:
307 question = 'Do you wish to build TensorFlow with %s support?' % query_item
308 if not yes_reply:
309 yes_reply = '%s support will be enabled for TensorFlow.' % query_item
310 if not no_reply:
311 no_reply = 'No %s' % yes_reply
312
313 yes_reply += '\n'
314 no_reply += '\n'
315
316 if enabled_by_default:
317 question += ' [Y/n]: '
318 else:
319 question += ' [y/N]: '
320
321 var = environ_cp.get(var_name)
Frank Chenc4ef9272018-01-10 11:36:52 -0800322 if var is not None:
323 var_content = var.strip().lower()
324 true_strings = ('1', 't', 'true', 'y', 'yes')
325 false_strings = ('0', 'f', 'false', 'n', 'no')
326 if var_content in true_strings:
327 var = True
328 elif var_content in false_strings:
329 var = False
330 else:
331 raise UserInputError(
332 'Environment variable %s must be set as a boolean indicator.\n'
333 'The following are accepted as TRUE : %s.\n'
334 'The following are accepted as FALSE: %s.\n'
335 'Current value is %s.' % (
336 var_name, ', '.join(true_strings), ', '.join(false_strings),
337 var))
338
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700339 while var is None:
340 user_input_origin = get_input(question)
341 user_input = user_input_origin.strip().lower()
342 if user_input == 'y':
343 print(yes_reply)
344 var = True
345 elif user_input == 'n':
346 print(no_reply)
347 var = False
348 elif not user_input:
349 if enabled_by_default:
350 print(yes_reply)
351 var = True
352 else:
353 print(no_reply)
354 var = False
355 else:
356 print('Invalid selection: %s' % user_input_origin)
357 return var
358
359
360def set_build_var(environ_cp, var_name, query_item, option_name,
Michael Case98850a52017-09-14 13:35:57 -0700361 enabled_by_default, bazel_config_name=None):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700362 """Set if query_item will be enabled for the build.
363
364 Ask user if query_item will be enabled. Default is used if no input is given.
365 Set subprocess environment variable and write to .bazelrc if enabled.
366
367 Args:
368 environ_cp: copy of the os.environ.
369 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
370 query_item: string for feature related to the variable, e.g. "Hadoop File
371 System".
372 option_name: string for option to define in .bazelrc.
373 enabled_by_default: boolean for default behavior.
Michael Case98850a52017-09-14 13:35:57 -0700374 bazel_config_name: Name for Bazel --config argument to enable build feature.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700375 """
376
377 var = str(int(get_var(environ_cp, var_name, query_item, enabled_by_default)))
378 environ_cp[var_name] = var
379 if var == '1':
380 write_to_bazelrc('build --define %s=true' % option_name)
Michael Case98850a52017-09-14 13:35:57 -0700381 elif bazel_config_name is not None:
382 # TODO(mikecase): Migrate all users of configure.py to use --config Bazel
383 # options and not to set build configs through environment variables.
384 write_to_bazelrc('build:%s --define %s=true'
385 % (bazel_config_name, option_name))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700386
387
388def set_action_env_var(environ_cp,
389 var_name,
390 query_item,
391 enabled_by_default,
392 question=None,
393 yes_reply=None,
394 no_reply=None):
395 """Set boolean action_env variable.
396
397 Ask user if query_item will be enabled. Default is used if no input is given.
398 Set environment variable and write to .bazelrc.
399
400 Args:
401 environ_cp: copy of the os.environ.
402 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
403 query_item: string for feature related to the variable, e.g. "Hadoop File
404 System".
405 enabled_by_default: boolean for default behavior.
406 question: optional string for how to ask for user input.
Michael Cased90054e2018-02-07 14:36:00 -0800407 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700408 no_reply: optional string for reply when feature is disabled.
409 """
410 var = int(
411 get_var(environ_cp, var_name, query_item, enabled_by_default, question,
412 yes_reply, no_reply))
413
414 write_action_env_to_bazelrc(var_name, var)
415 environ_cp[var_name] = str(var)
416
417
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700418def convert_version_to_int(version):
419 """Convert a version number to a integer that can be used to compare.
420
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700421 Version strings of the form X.YZ and X.Y.Z-xxxxx are supported. The
422 'xxxxx' part, for instance 'homebrew' on OS/X, is ignored.
423
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700424 Args:
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700425 version: a version to be converted
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700426
427 Returns:
428 An integer if converted successfully, otherwise return None.
429 """
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700430 version = version.split('-')[0]
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700431 version_segments = version.split('.')
432 for seg in version_segments:
433 if not seg.isdigit():
434 return None
435
436 version_str = ''.join(['%03d' % int(seg) for seg in version_segments])
437 return int(version_str)
438
439
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700440def check_bazel_version(min_version):
Yifei Fengdce9a492018-02-22 14:24:57 -0800441 """Check installed bazel version is at least min_version.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700442
443 Args:
444 min_version: string for minimum bazel version.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700445
446 Returns:
447 The bazel version detected.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700448 """
Jonathan Hseu008910f2017-08-25 14:01:05 -0700449 if which('bazel') is None:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700450 print('Cannot find bazel. Please install bazel.')
451 sys.exit(0)
Shanqing Cai71445712018-03-12 19:33:52 -0700452 curr_version = run_shell(['bazel', '--batch', '--bazelrc=/dev/null', 'version'])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700453
454 for line in curr_version.split('\n'):
455 if 'Build label: ' in line:
456 curr_version = line.split('Build label: ')[1]
457 break
458
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700459 min_version_int = convert_version_to_int(min_version)
460 curr_version_int = convert_version_to_int(curr_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700461
462 # Check if current bazel version can be detected properly.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700463 if not curr_version_int:
464 print('WARNING: current bazel installation is not a release version.')
465 print('Make sure you are running at least bazel %s' % min_version)
466 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700467
Michael Cased94271a2017-08-22 17:26:52 -0700468 print('You have bazel %s installed.' % curr_version)
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700469
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700470 if curr_version_int < min_version_int:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700471 print('Please upgrade your bazel installation to version %s or higher to '
472 'build TensorFlow!' % min_version)
473 sys.exit(0)
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700474 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700475
476
477def set_cc_opt_flags(environ_cp):
478 """Set up architecture-dependent optimization flags.
479
480 Also append CC optimization flags to bazel.rc..
481
482 Args:
483 environ_cp: copy of the os.environ.
484 """
485 if is_ppc64le():
486 # gcc on ppc64le does not support -march, use mcpu instead
487 default_cc_opt_flags = '-mcpu=native'
A. Unique TensorFlower1bba94a2018-04-04 15:45:20 -0700488 elif is_windows():
489 default_cc_opt_flags = '/arch:AVX'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700490 else:
491 default_cc_opt_flags = '-march=native'
492 question = ('Please specify optimization flags to use during compilation when'
493 ' bazel option "--config=opt" is specified [Default is %s]: '
494 ) % default_cc_opt_flags
495 cc_opt_flags = get_from_env_or_user_or_default(environ_cp, 'CC_OPT_FLAGS',
496 question, default_cc_opt_flags)
497 for opt in cc_opt_flags.split():
Michael Case00177422017-11-10 13:14:03 -0800498 write_to_bazelrc('build:opt --copt=%s' % opt)
499 # It should be safe on the same build host.
A. Unique TensorFlower1bba94a2018-04-04 15:45:20 -0700500 if not is_ppc64le() and not is_windows():
Shanqing Cai71445712018-03-12 19:33:52 -0700501 write_to_bazelrc('build:opt --host_copt=-march=native')
Michael Casebb3355d2017-11-09 08:46:31 -0800502 write_to_bazelrc('build:opt --define with_default_optimizations=true')
Michael Case00177422017-11-10 13:14:03 -0800503 # TODO(mikecase): Remove these default defines once we are able to get
504 # TF Lite targets building without them.
Andrew Selle0b154392017-11-10 10:35:35 -0800505 write_to_bazelrc('build --copt=-DGEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK')
506 write_to_bazelrc('build --host_copt=-DGEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700507
508
509def set_tf_cuda_clang(environ_cp):
510 """set TF_CUDA_CLANG action_env.
511
512 Args:
513 environ_cp: copy of the os.environ.
514 """
515 question = 'Do you want to use clang as CUDA compiler?'
516 yes_reply = 'Clang will be used as CUDA compiler.'
517 no_reply = 'nvcc will be used as CUDA compiler.'
518 set_action_env_var(
519 environ_cp,
520 'TF_CUDA_CLANG',
521 None,
522 False,
523 question=question,
524 yes_reply=yes_reply,
525 no_reply=no_reply)
526
527
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800528def set_tf_download_clang(environ_cp):
529 """Set TF_DOWNLOAD_CLANG action_env."""
Ilya Biryukov9e651e42018-03-22 05:33:42 -0700530 question = 'Do you wish to download a fresh release of clang? (Experimental)'
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800531 yes_reply = 'Clang will be downloaded and used to compile tensorflow.'
532 no_reply = 'Clang will not be downloaded.'
533 set_action_env_var(
534 environ_cp,
535 'TF_DOWNLOAD_CLANG',
536 None,
537 False,
538 question=question,
539 yes_reply=yes_reply,
540 no_reply=no_reply)
541
542
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700543def get_from_env_or_user_or_default(environ_cp, var_name, ask_for_var,
544 var_default):
545 """Get var_name either from env, or user or default.
546
547 If var_name has been set as environment variable, use the preset value, else
548 ask for user input. If no input is provided, the default is used.
549
550 Args:
551 environ_cp: copy of the os.environ.
552 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
553 ask_for_var: string for how to ask for user input.
554 var_default: default value string.
555
556 Returns:
557 string value for var_name
558 """
559 var = environ_cp.get(var_name)
560 if not var:
561 var = get_input(ask_for_var)
Michael Cased94271a2017-08-22 17:26:52 -0700562 print('\n')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700563 if not var:
564 var = var_default
565 return var
566
567
568def set_clang_cuda_compiler_path(environ_cp):
569 """Set CLANG_CUDA_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700570 default_clang_path = which('clang') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700571 ask_clang_path = ('Please specify which clang should be used as device and '
572 'host compiler. [Default is %s]: ') % default_clang_path
573
574 while True:
575 clang_cuda_compiler_path = get_from_env_or_user_or_default(
576 environ_cp, 'CLANG_CUDA_COMPILER_PATH', ask_clang_path,
577 default_clang_path)
578 if os.path.exists(clang_cuda_compiler_path):
579 break
580
581 # Reset and retry
582 print('Invalid clang path: %s cannot be found.' % clang_cuda_compiler_path)
583 environ_cp['CLANG_CUDA_COMPILER_PATH'] = ''
584
585 # Set CLANG_CUDA_COMPILER_PATH
586 environ_cp['CLANG_CUDA_COMPILER_PATH'] = clang_cuda_compiler_path
587 write_action_env_to_bazelrc('CLANG_CUDA_COMPILER_PATH',
588 clang_cuda_compiler_path)
589
590
Austin Anderson6afface2017-12-05 11:59:17 -0800591def prompt_loop_or_load_from_env(
592 environ_cp,
593 var_name,
594 var_default,
595 ask_for_var,
596 check_success,
597 error_msg,
598 suppress_default_error=False,
599 n_ask_attempts=_DEFAULT_PROMPT_ASK_ATTEMPTS
600):
601 """Loop over user prompts for an ENV param until receiving a valid response.
602
603 For the env param var_name, read from the environment or verify user input
604 until receiving valid input. When done, set var_name in the environ_cp to its
605 new value.
606
607 Args:
608 environ_cp: (Dict) copy of the os.environ.
609 var_name: (String) string for name of environment variable, e.g. "TF_MYVAR".
610 var_default: (String) default value string.
611 ask_for_var: (String) string for how to ask for user input.
612 check_success: (Function) function that takes one argument and returns a
613 boolean. Should return True if the value provided is considered valid. May
614 contain a complex error message if error_msg does not provide enough
615 information. In that case, set suppress_default_error to True.
616 error_msg: (String) String with one and only one '%s'. Formatted with each
617 invalid response upon check_success(input) failure.
618 suppress_default_error: (Bool) Suppress the above error message in favor of
619 one from the check_success function.
620 n_ask_attempts: (Integer) Number of times to query for valid input before
621 raising an error and quitting.
622
623 Returns:
624 [String] The value of var_name after querying for input.
625
626 Raises:
627 UserInputError: if a query has been attempted n_ask_attempts times without
Frank Chenc4ef9272018-01-10 11:36:52 -0800628 success, assume that the user has made a scripting error, and will
629 continue to provide invalid input. Raise the error to avoid infinitely
630 looping.
Austin Anderson6afface2017-12-05 11:59:17 -0800631 """
632 default = environ_cp.get(var_name) or var_default
633 full_query = '%s [Default is %s]: ' % (
634 ask_for_var,
635 default,
636 )
637
638 for _ in range(n_ask_attempts):
639 val = get_from_env_or_user_or_default(environ_cp,
640 var_name,
641 full_query,
642 default)
643 if check_success(val):
644 break
645 if not suppress_default_error:
646 print(error_msg % val)
647 environ_cp[var_name] = ''
648 else:
649 raise UserInputError('Invalid %s setting was provided %d times in a row. '
650 'Assuming to be a scripting mistake.' %
651 (var_name, n_ask_attempts))
652
653 environ_cp[var_name] = val
654 return val
655
656
657def create_android_ndk_rule(environ_cp):
658 """Set ANDROID_NDK_HOME and write Android NDK WORKSPACE rule."""
659 if is_windows() or is_cygwin():
660 default_ndk_path = cygpath('%s/Android/Sdk/ndk-bundle' %
661 environ_cp['APPDATA'])
662 elif is_macos():
663 default_ndk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
664 else:
665 default_ndk_path = '%s/Android/Sdk/ndk-bundle' % environ_cp['HOME']
666
667 def valid_ndk_path(path):
668 return (os.path.exists(path) and
669 os.path.exists(os.path.join(path, 'source.properties')))
670
671 android_ndk_home_path = prompt_loop_or_load_from_env(
672 environ_cp,
673 var_name='ANDROID_NDK_HOME',
674 var_default=default_ndk_path,
675 ask_for_var='Please specify the home path of the Android NDK to use.',
676 check_success=valid_ndk_path,
677 error_msg=('The path %s or its child file "source.properties" '
678 'does not exist.')
679 )
680
681 write_android_ndk_workspace_rule(android_ndk_home_path)
682
683
684def create_android_sdk_rule(environ_cp):
685 """Set Android variables and write Android SDK WORKSPACE rule."""
686 if is_windows() or is_cygwin():
687 default_sdk_path = cygpath('%s/Android/Sdk' % environ_cp['APPDATA'])
688 elif is_macos():
689 default_sdk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
690 else:
691 default_sdk_path = '%s/Android/Sdk' % environ_cp['HOME']
692
693 def valid_sdk_path(path):
694 return (os.path.exists(path) and
695 os.path.exists(os.path.join(path, 'platforms')) and
696 os.path.exists(os.path.join(path, 'build-tools')))
697
698 android_sdk_home_path = prompt_loop_or_load_from_env(
699 environ_cp,
700 var_name='ANDROID_SDK_HOME',
701 var_default=default_sdk_path,
702 ask_for_var='Please specify the home path of the Android SDK to use.',
703 check_success=valid_sdk_path,
704 error_msg=('Either %s does not exist, or it does not contain the '
705 'subdirectories "platforms" and "build-tools".'))
706
707 platforms = os.path.join(android_sdk_home_path, 'platforms')
708 api_levels = sorted(os.listdir(platforms))
709 api_levels = [x.replace('android-', '') for x in api_levels]
710
711 def valid_api_level(api_level):
712 return os.path.exists(os.path.join(android_sdk_home_path,
713 'platforms',
714 'android-' + api_level))
715
716 android_api_level = prompt_loop_or_load_from_env(
717 environ_cp,
718 var_name='ANDROID_API_LEVEL',
719 var_default=api_levels[-1],
720 ask_for_var=('Please specify the Android SDK API level to use. '
721 '[Available levels: %s]') % api_levels,
722 check_success=valid_api_level,
723 error_msg='Android-%s is not present in the SDK path.')
724
725 build_tools = os.path.join(android_sdk_home_path, 'build-tools')
726 versions = sorted(os.listdir(build_tools))
727
728 def valid_build_tools(version):
729 return os.path.exists(os.path.join(android_sdk_home_path,
730 'build-tools',
731 version))
732
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
743 write_android_sdk_workspace_rule(android_sdk_home_path,
744 android_build_tools_version,
745 android_api_level)
746
747
748def write_android_sdk_workspace_rule(android_sdk_home_path,
749 android_build_tools_version,
750 android_api_level):
751 print('Writing android_sdk_workspace rule.\n')
752 with open(_TF_WORKSPACE, 'a') as f:
753 f.write("""
754android_sdk_repository(
755 name="androidsdk",
756 api_level=%s,
757 path="%s",
758 build_tools_version="%s")\n
759""" % (android_api_level, android_sdk_home_path, android_build_tools_version))
760
761
762def write_android_ndk_workspace_rule(android_ndk_home_path):
763 print('Writing android_ndk_workspace rule.')
764 ndk_api_level = check_ndk_level(android_ndk_home_path)
765 if int(ndk_api_level) not in _SUPPORTED_ANDROID_NDK_VERSIONS:
766 print('WARNING: The API level of the NDK in %s is %s, which is not '
767 'supported by Bazel (officially supported versions: %s). Please use '
768 'another version. Compiling Android targets may result in confusing '
769 'errors.\n' % (android_ndk_home_path, ndk_api_level,
770 _SUPPORTED_ANDROID_NDK_VERSIONS))
771 with open(_TF_WORKSPACE, 'a') as f:
772 f.write("""
773android_ndk_repository(
774 name="androidndk",
775 path="%s",
776 api_level=%s)\n
777""" % (android_ndk_home_path, ndk_api_level))
778
779
780def check_ndk_level(android_ndk_home_path):
781 """Check the revision number of an Android NDK path."""
782 properties_path = '%s/source.properties' % android_ndk_home_path
783 if is_windows() or is_cygwin():
784 properties_path = cygpath(properties_path)
785 with open(properties_path, 'r') as f:
786 filedata = f.read()
787
788 revision = re.search(r'Pkg.Revision = (\d+)', filedata)
789 if revision:
790 return revision.group(1)
791 return None
792
793
794def workspace_has_any_android_rule():
795 """Check the WORKSPACE for existing android_*_repository rules."""
796 with open(_TF_WORKSPACE, 'r') as f:
797 workspace = f.read()
798 has_any_rule = re.search(r'^android_[ns]dk_repository',
799 workspace,
800 re.MULTILINE)
801 return has_any_rule
802
803
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700804def set_gcc_host_compiler_path(environ_cp):
805 """Set GCC_HOST_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700806 default_gcc_host_compiler_path = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700807 cuda_bin_symlink = '%s/bin/gcc' % environ_cp.get('CUDA_TOOLKIT_PATH')
808
809 if os.path.islink(cuda_bin_symlink):
810 # os.readlink is only available in linux
Jonathan Hseu008910f2017-08-25 14:01:05 -0700811 default_gcc_host_compiler_path = os.path.realpath(cuda_bin_symlink)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700812
Austin Anderson6afface2017-12-05 11:59:17 -0800813 gcc_host_compiler_path = prompt_loop_or_load_from_env(
814 environ_cp,
815 var_name='GCC_HOST_COMPILER_PATH',
816 var_default=default_gcc_host_compiler_path,
817 ask_for_var=
818 'Please specify which gcc should be used by nvcc as the host compiler.',
819 check_success=os.path.exists,
820 error_msg='Invalid gcc path. %s cannot be found.',
821 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700822
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700823 write_action_env_to_bazelrc('GCC_HOST_COMPILER_PATH', gcc_host_compiler_path)
824
825
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800826def reformat_version_sequence(version_str, sequence_count):
827 """Reformat the version string to have the given number of sequences.
828
829 For example:
830 Given (7, 2) -> 7.0
831 (7.0.1, 2) -> 7.0
832 (5, 1) -> 5
833 (5.0.3.2, 1) -> 5
834
835 Args:
836 version_str: String, the version string.
837 sequence_count: int, an integer.
838 Returns:
839 string, reformatted version string.
840 """
841 v = version_str.split('.')
842 if len(v) < sequence_count:
843 v = v + (['0'] * (sequence_count - len(v)))
844
845 return '.'.join(v[:sequence_count])
846
847
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700848def set_tf_cuda_version(environ_cp):
849 """Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION."""
850 ask_cuda_version = (
851 'Please specify the CUDA SDK version you want to use, '
852 'e.g. 7.0. [Leave empty to default to CUDA %s]: ') % _DEFAULT_CUDA_VERSION
853
Austin Andersonf9a88f82017-12-13 11:49:40 -0800854 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700855 # Configure the Cuda SDK version to use.
856 tf_cuda_version = get_from_env_or_user_or_default(
857 environ_cp, 'TF_CUDA_VERSION', ask_cuda_version, _DEFAULT_CUDA_VERSION)
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800858 tf_cuda_version = reformat_version_sequence(str(tf_cuda_version), 2)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700859
860 # Find out where the CUDA toolkit is installed
861 default_cuda_path = _DEFAULT_CUDA_PATH
Martin Wicked57572e2017-09-02 19:21:45 -0700862 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700863 default_cuda_path = cygpath(
864 environ_cp.get('CUDA_PATH', _DEFAULT_CUDA_PATH_WIN))
865 elif is_linux():
866 # If the default doesn't exist, try an alternative default.
867 if (not os.path.exists(default_cuda_path)
868 ) and os.path.exists(_DEFAULT_CUDA_PATH_LINUX):
869 default_cuda_path = _DEFAULT_CUDA_PATH_LINUX
870 ask_cuda_path = ('Please specify the location where CUDA %s toolkit is'
871 ' installed. Refer to README.md for more details. '
872 '[Default is %s]: ') % (tf_cuda_version, default_cuda_path)
873 cuda_toolkit_path = get_from_env_or_user_or_default(
874 environ_cp, 'CUDA_TOOLKIT_PATH', ask_cuda_path, default_cuda_path)
875
876 if is_windows():
877 cuda_rt_lib_path = 'lib/x64/cudart.lib'
878 elif is_linux():
879 cuda_rt_lib_path = 'lib64/libcudart.so.%s' % tf_cuda_version
880 elif is_macos():
881 cuda_rt_lib_path = 'lib/libcudart.%s.dylib' % tf_cuda_version
882
883 cuda_toolkit_path_full = os.path.join(cuda_toolkit_path, cuda_rt_lib_path)
884 if os.path.exists(cuda_toolkit_path_full):
885 break
886
887 # Reset and retry
888 print('Invalid path to CUDA %s toolkit. %s cannot be found' %
889 (tf_cuda_version, cuda_toolkit_path_full))
890 environ_cp['TF_CUDA_VERSION'] = ''
891 environ_cp['CUDA_TOOLKIT_PATH'] = ''
892
Austin Andersonf9a88f82017-12-13 11:49:40 -0800893 else:
894 raise UserInputError('Invalid TF_CUDA_SETTING setting was provided %d '
895 'times in a row. Assuming to be a scripting mistake.' %
896 _DEFAULT_PROMPT_ASK_ATTEMPTS)
897
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700898 # Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION
899 environ_cp['CUDA_TOOLKIT_PATH'] = cuda_toolkit_path
900 write_action_env_to_bazelrc('CUDA_TOOLKIT_PATH', cuda_toolkit_path)
901 environ_cp['TF_CUDA_VERSION'] = tf_cuda_version
902 write_action_env_to_bazelrc('TF_CUDA_VERSION', tf_cuda_version)
903
904
Yifei Fengb1d8c592017-11-22 13:42:21 -0800905def set_tf_cudnn_version(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700906 """Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION."""
907 ask_cudnn_version = (
Jonathan Hseu008910f2017-08-25 14:01:05 -0700908 'Please specify the cuDNN version you want to use. '
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700909 '[Leave empty to default to cuDNN %s.0]: ') % _DEFAULT_CUDNN_VERSION
910
Austin Andersonf9a88f82017-12-13 11:49:40 -0800911 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700912 tf_cudnn_version = get_from_env_or_user_or_default(
913 environ_cp, 'TF_CUDNN_VERSION', ask_cudnn_version,
914 _DEFAULT_CUDNN_VERSION)
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800915 tf_cudnn_version = reformat_version_sequence(str(tf_cudnn_version), 1)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700916
917 default_cudnn_path = environ_cp.get('CUDA_TOOLKIT_PATH')
918 ask_cudnn_path = (r'Please specify the location where cuDNN %s library is '
919 'installed. Refer to README.md for more details. [Default'
920 ' is %s]:') % (tf_cudnn_version, default_cudnn_path)
921 cudnn_install_path = get_from_env_or_user_or_default(
922 environ_cp, 'CUDNN_INSTALL_PATH', ask_cudnn_path, default_cudnn_path)
923
924 # Result returned from "read" will be used unexpanded. That make "~"
925 # unusable. Going through one more level of expansion to handle that.
926 cudnn_install_path = os.path.realpath(
927 os.path.expanduser(cudnn_install_path))
Martin Wicked57572e2017-09-02 19:21:45 -0700928 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700929 cudnn_install_path = cygpath(cudnn_install_path)
930
931 if is_windows():
932 cuda_dnn_lib_path = 'lib/x64/cudnn.lib'
933 cuda_dnn_lib_alt_path = 'lib/x64/cudnn.lib'
934 elif is_linux():
935 cuda_dnn_lib_path = 'lib64/libcudnn.so.%s' % tf_cudnn_version
936 cuda_dnn_lib_alt_path = 'libcudnn.so.%s' % tf_cudnn_version
937 elif is_macos():
938 cuda_dnn_lib_path = 'lib/libcudnn.%s.dylib' % tf_cudnn_version
939 cuda_dnn_lib_alt_path = 'libcudnn.%s.dylib' % tf_cudnn_version
940
941 cuda_dnn_lib_path_full = os.path.join(cudnn_install_path, cuda_dnn_lib_path)
942 cuda_dnn_lib_alt_path_full = os.path.join(cudnn_install_path,
943 cuda_dnn_lib_alt_path)
944 if os.path.exists(cuda_dnn_lib_path_full) or os.path.exists(
945 cuda_dnn_lib_alt_path_full):
946 break
947
948 # Try another alternative for Linux
949 if is_linux():
Jonathan Hseu008910f2017-08-25 14:01:05 -0700950 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
951 cudnn_path_from_ldconfig = run_shell([ldconfig_bin, '-p'])
952 cudnn_path_from_ldconfig = re.search('.*libcudnn.so .* => (.*)',
A. Unique TensorFlowere7223582017-09-06 17:57:04 -0700953 cudnn_path_from_ldconfig)
954 if cudnn_path_from_ldconfig:
955 cudnn_path_from_ldconfig = cudnn_path_from_ldconfig.group(1)
956 if os.path.exists('%s.%s' % (cudnn_path_from_ldconfig,
957 tf_cudnn_version)):
958 cudnn_install_path = os.path.dirname(cudnn_path_from_ldconfig)
959 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700960
961 # Reset and Retry
962 print(
963 'Invalid path to cuDNN %s toolkit. None of the following files can be '
964 'found:' % tf_cudnn_version)
965 print(cuda_dnn_lib_path_full)
966 print(cuda_dnn_lib_alt_path_full)
967 if is_linux():
968 print('%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version))
969
970 environ_cp['TF_CUDNN_VERSION'] = ''
Austin Andersonf9a88f82017-12-13 11:49:40 -0800971 else:
972 raise UserInputError('Invalid TF_CUDNN setting was provided %d '
973 'times in a row. Assuming to be a scripting mistake.' %
974 _DEFAULT_PROMPT_ASK_ATTEMPTS)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700975
976 # Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION
977 environ_cp['CUDNN_INSTALL_PATH'] = cudnn_install_path
978 write_action_env_to_bazelrc('CUDNN_INSTALL_PATH', cudnn_install_path)
979 environ_cp['TF_CUDNN_VERSION'] = tf_cudnn_version
980 write_action_env_to_bazelrc('TF_CUDNN_VERSION', tf_cudnn_version)
981
982
Guangda Lai76f69382018-01-25 23:59:19 -0800983def set_tf_tensorrt_install_path(environ_cp):
984 """Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION.
985
986 Adapted from code contributed by Sami Kama (https://github.com/samikama).
987
988 Args:
989 environ_cp: copy of the os.environ.
990
991 Raises:
992 ValueError: if this method was called under non-Linux platform.
993 UserInputError: if user has provided invalid input multiple times.
994 """
995 if not is_linux():
996 raise ValueError('Currently TensorRT is only supported on Linux platform.')
997
998 # Ask user whether to add TensorRT support.
999 if str(int(get_var(
1000 environ_cp, 'TF_NEED_TENSORRT', 'TensorRT', False))) != '1':
1001 return
1002
1003 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
1004 ask_tensorrt_path = (r'Please specify the location where TensorRT is '
1005 'installed. [Default is %s]:') % (
1006 _DEFAULT_TENSORRT_PATH_LINUX)
1007 trt_install_path = get_from_env_or_user_or_default(
1008 environ_cp, 'TENSORRT_INSTALL_PATH', ask_tensorrt_path,
1009 _DEFAULT_TENSORRT_PATH_LINUX)
1010
1011 # Result returned from "read" will be used unexpanded. That make "~"
1012 # unusable. Going through one more level of expansion to handle that.
1013 trt_install_path = os.path.realpath(
1014 os.path.expanduser(trt_install_path))
1015
1016 def find_libs(search_path):
1017 """Search for libnvinfer.so in "search_path"."""
1018 fl = set()
1019 if os.path.exists(search_path) and os.path.isdir(search_path):
1020 fl.update([os.path.realpath(os.path.join(search_path, x))
1021 for x in os.listdir(search_path) if 'libnvinfer.so' in x])
1022 return fl
1023
1024 possible_files = find_libs(trt_install_path)
1025 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib')))
1026 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib64')))
1027
1028 def is_compatible(tensorrt_lib, cuda_ver, cudnn_ver):
1029 """Check the compatibility between tensorrt and cudnn/cudart libraries."""
1030 ldd_bin = which('ldd') or '/usr/bin/ldd'
1031 ldd_out = run_shell([ldd_bin, tensorrt_lib]).split(os.linesep)
1032 cudnn_pattern = re.compile('.*libcudnn.so\\.?(.*) =>.*$')
1033 cuda_pattern = re.compile('.*libcudart.so\\.?(.*) =>.*$')
1034 cudnn = None
1035 cudart = None
1036 for line in ldd_out:
1037 if 'libcudnn.so' in line:
1038 cudnn = cudnn_pattern.search(line)
1039 elif 'libcudart.so' in line:
1040 cudart = cuda_pattern.search(line)
1041 if cudnn and len(cudnn.group(1)):
1042 cudnn = convert_version_to_int(cudnn.group(1))
1043 if cudart and len(cudart.group(1)):
1044 cudart = convert_version_to_int(cudart.group(1))
1045 return (cudnn == cudnn_ver) and (cudart == cuda_ver)
1046
1047 cuda_ver = convert_version_to_int(environ_cp['TF_CUDA_VERSION'])
1048 cudnn_ver = convert_version_to_int(environ_cp['TF_CUDNN_VERSION'])
1049 nvinfer_pattern = re.compile('.*libnvinfer.so.?(.*)$')
1050 highest_ver = [0, None, None]
1051
1052 for lib_file in possible_files:
1053 if is_compatible(lib_file, cuda_ver, cudnn_ver):
Jacques Pienaar2d0531d2018-03-21 12:07:51 -07001054 matches = nvinfer_pattern.search(lib_file)
1055 if len(matches.groups()) == 0:
1056 continue
1057 ver_str = matches.group(1)
Guangda Lai76f69382018-01-25 23:59:19 -08001058 ver = convert_version_to_int(ver_str) if len(ver_str) else 0
1059 if ver > highest_ver[0]:
1060 highest_ver = [ver, ver_str, lib_file]
1061 if highest_ver[1] is not None:
1062 trt_install_path = os.path.dirname(highest_ver[2])
1063 tf_tensorrt_version = highest_ver[1]
1064 break
1065
1066 # Try another alternative from ldconfig.
1067 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
1068 ldconfig_output = run_shell([ldconfig_bin, '-p'])
1069 search_result = re.search(
1070 '.*libnvinfer.so\\.?([0-9.]*).* => (.*)', ldconfig_output)
1071 if search_result:
1072 libnvinfer_path_from_ldconfig = search_result.group(2)
1073 if os.path.exists(libnvinfer_path_from_ldconfig):
1074 if is_compatible(libnvinfer_path_from_ldconfig, cuda_ver, cudnn_ver):
1075 trt_install_path = os.path.dirname(libnvinfer_path_from_ldconfig)
1076 tf_tensorrt_version = search_result.group(1)
1077 break
1078
1079 # Reset and Retry
Yifei Fengdce9a492018-02-22 14:24:57 -08001080 if possible_files:
1081 print('TensorRT libraries found in one the following directories',
1082 'are not compatible with selected cuda and cudnn installations')
1083 print(trt_install_path)
1084 print(os.path.join(trt_install_path, 'lib'))
1085 print(os.path.join(trt_install_path, 'lib64'))
1086 if search_result:
1087 print(libnvinfer_path_from_ldconfig)
1088 else:
1089 print(
1090 'Invalid path to TensorRT. None of the following files can be found:')
1091 print(trt_install_path)
1092 print(os.path.join(trt_install_path, 'lib'))
1093 print(os.path.join(trt_install_path, 'lib64'))
1094 if search_result:
1095 print(libnvinfer_path_from_ldconfig)
Guangda Lai76f69382018-01-25 23:59:19 -08001096
1097 else:
1098 raise UserInputError('Invalid TF_TENSORRT setting was provided %d '
1099 'times in a row. Assuming to be a scripting mistake.' %
1100 _DEFAULT_PROMPT_ASK_ATTEMPTS)
1101
1102 # Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION
1103 environ_cp['TENSORRT_INSTALL_PATH'] = trt_install_path
1104 write_action_env_to_bazelrc('TENSORRT_INSTALL_PATH', trt_install_path)
1105 environ_cp['TF_TENSORRT_VERSION'] = tf_tensorrt_version
1106 write_action_env_to_bazelrc('TF_TENSORRT_VERSION', tf_tensorrt_version)
1107
1108
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001109def set_tf_nccl_install_path(environ_cp):
1110 """Set NCCL_INSTALL_PATH and TF_NCCL_VERSION.
1111
1112 Args:
1113 environ_cp: copy of the os.environ.
1114
1115 Raises:
1116 ValueError: if this method was called under non-Linux platform.
1117 UserInputError: if user has provided invalid input multiple times.
1118 """
1119 if not is_linux():
1120 raise ValueError('Currently NCCL is only supported on Linux platforms.')
1121
1122 ask_nccl_version = (
1123 'Please specify the NCCL version you want to use. '
1124 '[Leave empty to default to NCCL %s]: ') % _DEFAULT_NCCL_VERSION
1125
1126 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
1127 tf_nccl_version = get_from_env_or_user_or_default(
1128 environ_cp, 'TF_NCCL_VERSION', ask_nccl_version, _DEFAULT_NCCL_VERSION)
1129 tf_nccl_version = reformat_version_sequence(str(tf_nccl_version), 1)
1130
1131 if tf_nccl_version == '1':
1132 break # No need to get install path, NCCL 1 is a GitHub repo.
1133
1134 # TODO(csigg): Look with ldconfig first if we can find the library in paths
1135 # like /usr/lib/x86_64-linux-gnu and the header file in the corresponding
1136 # include directory. This is where the NCCL .deb packages install them.
1137 # Then ask the user if we should use that. Instead of a single
1138 # NCCL_INSTALL_PATH, pass separate NCCL_LIB_PATH and NCCL_HDR_PATH to
1139 # nccl_configure.bzl
1140 default_nccl_path = environ_cp.get('CUDA_TOOLKIT_PATH')
1141 ask_nccl_path = (r'Please specify the location where NCCL %s library is '
1142 'installed. Refer to README.md for more details. [Default '
1143 'is %s]:') % (tf_nccl_version, default_nccl_path)
1144 nccl_install_path = get_from_env_or_user_or_default(
1145 environ_cp, 'NCCL_INSTALL_PATH', ask_nccl_path, default_nccl_path)
1146
1147 # Result returned from "read" will be used unexpanded. That make "~"
1148 # unusable. Going through one more level of expansion to handle that.
1149 nccl_install_path = os.path.realpath(os.path.expanduser(nccl_install_path))
1150 if is_windows() or is_cygwin():
1151 nccl_install_path = cygpath(nccl_install_path)
1152
1153 if is_windows():
1154 nccl_lib_path = 'lib/x64/nccl.lib'
1155 elif is_linux():
1156 nccl_lib_path = 'lib/libnccl.so.%s' % tf_nccl_version
1157 elif is_macos():
1158 nccl_lib_path = 'lib/libnccl.%s.dylib' % tf_nccl_version
1159
1160 nccl_lib_path = os.path.join(nccl_install_path, nccl_lib_path)
1161 nccl_hdr_path = os.path.join(nccl_install_path, 'include/nccl.h')
1162 if os.path.exists(nccl_lib_path) and os.path.exists(nccl_hdr_path):
1163 # Set NCCL_INSTALL_PATH
1164 environ_cp['NCCL_INSTALL_PATH'] = nccl_install_path
1165 write_action_env_to_bazelrc('NCCL_INSTALL_PATH', nccl_install_path)
1166 break
1167
1168 # Reset and Retry
1169 print('Invalid path to NCCL %s toolkit, %s or %s not found. Please use the '
1170 'O/S agnostic package of NCCL 2' % (tf_nccl_version, nccl_lib_path,
1171 nccl_hdr_path))
1172
1173 environ_cp['TF_NCCL_VERSION'] = ''
1174 else:
1175 raise UserInputError('Invalid TF_NCCL setting was provided %d '
1176 'times in a row. Assuming to be a scripting mistake.' %
1177 _DEFAULT_PROMPT_ASK_ATTEMPTS)
1178
1179 # Set TF_NCCL_VERSION
1180 environ_cp['TF_NCCL_VERSION'] = tf_nccl_version
1181 write_action_env_to_bazelrc('TF_NCCL_VERSION', tf_nccl_version)
1182
1183
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001184def get_native_cuda_compute_capabilities(environ_cp):
1185 """Get native cuda compute capabilities.
1186
1187 Args:
1188 environ_cp: copy of the os.environ.
1189 Returns:
1190 string of native cuda compute capabilities, separated by comma.
1191 """
1192 device_query_bin = os.path.join(
1193 environ_cp.get('CUDA_TOOLKIT_PATH'), 'extras/demo_suite/deviceQuery')
Jonathan Hseu008910f2017-08-25 14:01:05 -07001194 if os.path.isfile(device_query_bin) and os.access(device_query_bin, os.X_OK):
1195 try:
1196 output = run_shell(device_query_bin).split('\n')
1197 pattern = re.compile('[0-9]*\\.[0-9]*')
1198 output = [pattern.search(x) for x in output if 'Capability' in x]
1199 output = ','.join(x.group() for x in output if x is not None)
1200 except subprocess.CalledProcessError:
1201 output = ''
1202 else:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001203 output = ''
1204 return output
1205
1206
1207def set_tf_cuda_compute_capabilities(environ_cp):
1208 """Set TF_CUDA_COMPUTE_CAPABILITIES."""
1209 while True:
1210 native_cuda_compute_capabilities = get_native_cuda_compute_capabilities(
1211 environ_cp)
1212 if not native_cuda_compute_capabilities:
1213 default_cuda_compute_capabilities = _DEFAULT_CUDA_COMPUTE_CAPABILITIES
1214 else:
1215 default_cuda_compute_capabilities = native_cuda_compute_capabilities
1216
1217 ask_cuda_compute_capabilities = (
1218 'Please specify a list of comma-separated '
1219 'Cuda compute capabilities you want to '
1220 'build with.\nYou can find the compute '
1221 'capability of your device at: '
1222 'https://developer.nvidia.com/cuda-gpus.\nPlease'
1223 ' note that each additional compute '
1224 'capability significantly increases your '
1225 'build time and binary size. [Default is: %s]' %
1226 default_cuda_compute_capabilities)
1227 tf_cuda_compute_capabilities = get_from_env_or_user_or_default(
1228 environ_cp, 'TF_CUDA_COMPUTE_CAPABILITIES',
1229 ask_cuda_compute_capabilities, default_cuda_compute_capabilities)
1230 # Check whether all capabilities from the input is valid
1231 all_valid = True
1232 for compute_capability in tf_cuda_compute_capabilities.split(','):
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001233 m = re.match('[0-9]+.[0-9]+', compute_capability)
1234 if not m:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001235 print('Invalid compute capability: ' % compute_capability)
1236 all_valid = False
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001237 else:
1238 ver = int(m.group(0).split('.')[0])
1239 if ver < 3:
1240 print('Only compute capabilities 3.0 or higher are supported.')
1241 all_valid = False
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001242
1243 if all_valid:
1244 break
1245
1246 # Reset and Retry
1247 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = ''
1248
1249 # Set TF_CUDA_COMPUTE_CAPABILITIES
1250 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = tf_cuda_compute_capabilities
1251 write_action_env_to_bazelrc('TF_CUDA_COMPUTE_CAPABILITIES',
1252 tf_cuda_compute_capabilities)
1253
1254
1255def set_other_cuda_vars(environ_cp):
1256 """Set other CUDA related variables."""
1257 if is_windows():
1258 # The following three variables are needed for MSVC toolchain configuration
1259 # in Bazel
1260 environ_cp['CUDA_PATH'] = environ_cp.get('CUDA_TOOLKIT_PATH')
1261 environ_cp['CUDA_COMPUTE_CAPABILITIES'] = environ_cp.get(
1262 'TF_CUDA_COMPUTE_CAPABILITIES')
1263 environ_cp['NO_WHOLE_ARCHIVE_OPTION'] = 1
1264 write_action_env_to_bazelrc('CUDA_PATH', environ_cp.get('CUDA_PATH'))
1265 write_action_env_to_bazelrc('CUDA_COMPUTE_CAPABILITIE',
1266 environ_cp.get('CUDA_COMPUTE_CAPABILITIE'))
1267 write_action_env_to_bazelrc('NO_WHOLE_ARCHIVE_OPTION',
1268 environ_cp.get('NO_WHOLE_ARCHIVE_OPTION'))
1269 write_to_bazelrc('build --config=win-cuda')
1270 write_to_bazelrc('test --config=win-cuda')
1271 else:
1272 # If CUDA is enabled, always use GPU during build and test.
1273 if environ_cp.get('TF_CUDA_CLANG') == '1':
1274 write_to_bazelrc('build --config=cuda_clang')
1275 write_to_bazelrc('test --config=cuda_clang')
1276 else:
1277 write_to_bazelrc('build --config=cuda')
1278 write_to_bazelrc('test --config=cuda')
1279
1280
1281def set_host_cxx_compiler(environ_cp):
1282 """Set HOST_CXX_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001283 default_cxx_host_compiler = which('g++') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001284
Austin Anderson6afface2017-12-05 11:59:17 -08001285 host_cxx_compiler = prompt_loop_or_load_from_env(
1286 environ_cp,
1287 var_name='HOST_CXX_COMPILER',
1288 var_default=default_cxx_host_compiler,
1289 ask_for_var=('Please specify which C++ compiler should be used as the '
1290 'host C++ compiler.'),
1291 check_success=os.path.exists,
1292 error_msg='Invalid C++ compiler path. %s cannot be found.',
1293 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001294
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001295 write_action_env_to_bazelrc('HOST_CXX_COMPILER', host_cxx_compiler)
1296
1297
1298def set_host_c_compiler(environ_cp):
1299 """Set HOST_C_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001300 default_c_host_compiler = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001301
Austin Anderson6afface2017-12-05 11:59:17 -08001302 host_c_compiler = prompt_loop_or_load_from_env(
1303 environ_cp,
1304 var_name='HOST_C_COMPILER',
1305 var_default=default_c_host_compiler,
Shanqing Cai71445712018-03-12 19:33:52 -07001306 ask_for_var=('Please specify which C compiler should be used as the host '
Austin Anderson6afface2017-12-05 11:59:17 -08001307 'C compiler.'),
1308 check_success=os.path.exists,
1309 error_msg='Invalid C compiler path. %s cannot be found.',
1310 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001311
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001312 write_action_env_to_bazelrc('HOST_C_COMPILER', host_c_compiler)
1313
1314
1315def set_computecpp_toolkit_path(environ_cp):
1316 """Set COMPUTECPP_TOOLKIT_PATH."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001317
Austin Anderson6afface2017-12-05 11:59:17 -08001318 def toolkit_exists(toolkit_path):
1319 """Check if a computecpp toolkit path is valid."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001320 if is_linux():
1321 sycl_rt_lib_path = 'lib/libComputeCpp.so'
1322 else:
1323 sycl_rt_lib_path = ''
1324
Austin Anderson6afface2017-12-05 11:59:17 -08001325 sycl_rt_lib_path_full = os.path.join(toolkit_path,
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001326 sycl_rt_lib_path)
Austin Anderson6afface2017-12-05 11:59:17 -08001327 exists = os.path.exists(sycl_rt_lib_path_full)
1328 if not exists:
1329 print('Invalid SYCL %s library path. %s cannot be found' %
1330 (_TF_OPENCL_VERSION, sycl_rt_lib_path_full))
1331 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001332
Austin Anderson6afface2017-12-05 11:59:17 -08001333 computecpp_toolkit_path = prompt_loop_or_load_from_env(
1334 environ_cp,
1335 var_name='COMPUTECPP_TOOLKIT_PATH',
1336 var_default=_DEFAULT_COMPUTECPP_TOOLKIT_PATH,
1337 ask_for_var=(
1338 'Please specify the location where ComputeCpp for SYCL %s is '
1339 'installed.' % _TF_OPENCL_VERSION),
1340 check_success=toolkit_exists,
1341 error_msg='Invalid SYCL compiler path. %s cannot be found.',
1342 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001343
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001344 write_action_env_to_bazelrc('COMPUTECPP_TOOLKIT_PATH',
1345 computecpp_toolkit_path)
1346
Michael Cased31531a2018-01-05 14:09:41 -08001347
Dandelion Man?90e42f32017-12-15 18:15:07 -08001348def set_trisycl_include_dir(environ_cp):
Michael Cased31531a2018-01-05 14:09:41 -08001349 """Set TRISYCL_INCLUDE_DIR."""
Frank Chenc4ef9272018-01-10 11:36:52 -08001350
Dandelion Man?90e42f32017-12-15 18:15:07 -08001351 ask_trisycl_include_dir = ('Please specify the location of the triSYCL '
1352 'include directory. (Use --config=sycl_trisycl '
1353 'when building with Bazel) '
1354 '[Default is %s]: '
Michael Cased31531a2018-01-05 14:09:41 -08001355 ) % (_DEFAULT_TRISYCL_INCLUDE_DIR)
Frank Chenc4ef9272018-01-10 11:36:52 -08001356
Dandelion Man?90e42f32017-12-15 18:15:07 -08001357 while True:
1358 trisycl_include_dir = get_from_env_or_user_or_default(
Michael Cased31531a2018-01-05 14:09:41 -08001359 environ_cp, 'TRISYCL_INCLUDE_DIR', ask_trisycl_include_dir,
1360 _DEFAULT_TRISYCL_INCLUDE_DIR)
Dandelion Man?90e42f32017-12-15 18:15:07 -08001361 if os.path.exists(trisycl_include_dir):
1362 break
1363
1364 print('Invalid triSYCL include directory, %s cannot be found'
1365 % (trisycl_include_dir))
1366
1367 # Set TRISYCL_INCLUDE_DIR
1368 environ_cp['TRISYCL_INCLUDE_DIR'] = trisycl_include_dir
1369 write_action_env_to_bazelrc('TRISYCL_INCLUDE_DIR',
1370 trisycl_include_dir)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001371
Yifei Fengb1d8c592017-11-22 13:42:21 -08001372
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001373def set_mpi_home(environ_cp):
1374 """Set MPI_HOME."""
Austin Anderson6afface2017-12-05 11:59:17 -08001375
Jonathan Hseu008910f2017-08-25 14:01:05 -07001376 default_mpi_home = which('mpirun') or which('mpiexec') or ''
1377 default_mpi_home = os.path.dirname(os.path.dirname(default_mpi_home))
1378
Austin Anderson6afface2017-12-05 11:59:17 -08001379 def valid_mpi_path(mpi_home):
1380 exists = (os.path.exists(os.path.join(mpi_home, 'include')) and
1381 os.path.exists(os.path.join(mpi_home, 'lib')))
1382 if not exists:
1383 print('Invalid path to the MPI Toolkit. %s or %s cannot be found' %
1384 (os.path.join(mpi_home, 'include'),
1385 os.path.exists(os.path.join(mpi_home, 'lib'))))
1386 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001387
Austin Anderson6afface2017-12-05 11:59:17 -08001388 _ = prompt_loop_or_load_from_env(
1389 environ_cp,
1390 var_name='MPI_HOME',
1391 var_default=default_mpi_home,
1392 ask_for_var='Please specify the MPI toolkit folder.',
1393 check_success=valid_mpi_path,
1394 error_msg='',
1395 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001396
1397
1398def set_other_mpi_vars(environ_cp):
1399 """Set other MPI related variables."""
1400 # Link the MPI header files
1401 mpi_home = environ_cp.get('MPI_HOME')
1402 symlink_force('%s/include/mpi.h' % mpi_home, 'third_party/mpi/mpi.h')
1403
1404 # Determine if we use OpenMPI or MVAPICH, these require different header files
1405 # to be included here to make bazel dependency checker happy
1406 if os.path.exists(os.path.join(mpi_home, 'include/mpi_portable_platform.h')):
1407 symlink_force(
1408 os.path.join(mpi_home, 'include/mpi_portable_platform.h'),
1409 'third_party/mpi/mpi_portable_platform.h')
1410 # TODO(gunan): avoid editing files in configure
1411 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=False',
1412 'MPI_LIB_IS_OPENMPI=True')
1413 else:
1414 # MVAPICH / MPICH
1415 symlink_force(
1416 os.path.join(mpi_home, 'include/mpio.h'), 'third_party/mpi/mpio.h')
1417 symlink_force(
1418 os.path.join(mpi_home, 'include/mpicxx.h'), 'third_party/mpi/mpicxx.h')
1419 # TODO(gunan): avoid editing files in configure
1420 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=True',
1421 'MPI_LIB_IS_OPENMPI=False')
1422
1423 if os.path.exists(os.path.join(mpi_home, 'lib/libmpi.so')):
1424 symlink_force(
1425 os.path.join(mpi_home, 'lib/libmpi.so'), 'third_party/mpi/libmpi.so')
1426 else:
1427 raise ValueError('Cannot find the MPI library file in %s/lib' % mpi_home)
1428
1429
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001430def set_grpc_build_flags():
1431 write_to_bazelrc('build --define grpc_no_ares=true')
1432
Michael Cased31531a2018-01-05 14:09:41 -08001433
Dandelion Man?90e42f32017-12-15 18:15:07 -08001434def set_windows_build_flags():
1435 if is_windows():
1436 # The non-monolithic build is not supported yet
1437 write_to_bazelrc('build --config monolithic')
1438 # Suppress warning messages
1439 write_to_bazelrc('build --copt=-w --host_copt=-w')
1440 # Output more verbose information when something goes wrong
1441 write_to_bazelrc('build --verbose_failures')
1442
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001443
Michael Cased31531a2018-01-05 14:09:41 -08001444def config_info_line(name, help_text):
1445 """Helper function to print formatted help text for Bazel config options."""
1446 print('\t--config=%-12s\t# %s' % (name, help_text))
1447
1448
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001449def main():
Shanqing Cai71445712018-03-12 19:33:52 -07001450 parser = argparse.ArgumentParser()
1451 parser.add_argument("--workspace",
1452 type=str,
1453 default=_TF_WORKSPACE_ROOT,
1454 help="The absolute path to your active Bazel workspace.")
1455 args = parser.parse_args()
1456
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001457 # Make a copy of os.environ to be clear when functions and getting and setting
1458 # environment variables.
1459 environ_cp = dict(os.environ)
1460
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001461 check_bazel_version('0.10.0')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001462
Shanqing Cai71445712018-03-12 19:33:52 -07001463 reset_tf_configure_bazelrc(args.workspace)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001464 cleanup_makefile()
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -07001465 setup_python(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001466
1467 if is_windows():
Benoit Steiner355e25e2017-10-24 19:47:46 -07001468 environ_cp['TF_NEED_S3'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001469 environ_cp['TF_NEED_GCP'] = '0'
1470 environ_cp['TF_NEED_HDFS'] = '0'
1471 environ_cp['TF_NEED_JEMALLOC'] = '0'
Michael Cased90054e2018-02-07 14:36:00 -08001472 environ_cp['TF_NEED_KAFKA'] = '0'
Yifei Fengb1d8c592017-11-22 13:42:21 -08001473 environ_cp['TF_NEED_OPENCL_SYCL'] = '0'
1474 environ_cp['TF_NEED_COMPUTECPP'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001475 environ_cp['TF_NEED_OPENCL'] = '0'
1476 environ_cp['TF_CUDA_CLANG'] = '0'
Guangda Lai76f69382018-01-25 23:59:19 -08001477 environ_cp['TF_NEED_TENSORRT'] = '0'
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001478 # TODO(ibiryukov): Investigate using clang as a cpu or cuda compiler on
1479 # Windows.
1480 environ_cp['TF_DOWNLOAD_CLANG'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001481
1482 if is_macos():
1483 environ_cp['TF_NEED_JEMALLOC'] = '0'
Guangda Lai76f69382018-01-25 23:59:19 -08001484 environ_cp['TF_NEED_TENSORRT'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001485
1486 set_build_var(environ_cp, 'TF_NEED_JEMALLOC', 'jemalloc as malloc',
1487 'with_jemalloc', True)
1488 set_build_var(environ_cp, 'TF_NEED_GCP', 'Google Cloud Platform',
Benoit Steiner355e25e2017-10-24 19:47:46 -07001489 'with_gcp_support', True, 'gcp')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001490 set_build_var(environ_cp, 'TF_NEED_HDFS', 'Hadoop File System',
Benoit Steiner355e25e2017-10-24 19:47:46 -07001491 'with_hdfs_support', True, 'hdfs')
Michael Case7e4e3362017-10-09 13:31:15 -07001492 set_build_var(environ_cp, 'TF_NEED_S3', 'Amazon S3 File System',
1493 'with_s3_support', True, 's3')
Michael Cased90054e2018-02-07 14:36:00 -08001494 set_build_var(environ_cp, 'TF_NEED_KAFKA', 'Apache Kafka Platform',
Jianwei Xie63dffd52018-03-29 10:50:46 -07001495 'with_kafka_support', True, 'kafka')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001496 set_build_var(environ_cp, 'TF_ENABLE_XLA', 'XLA JIT', 'with_xla_support',
Michael Case98850a52017-09-14 13:35:57 -07001497 False, 'xla')
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -07001498 set_build_var(environ_cp, 'TF_NEED_GDR', 'GDR', 'with_gdr_support',
Michael Case98850a52017-09-14 13:35:57 -07001499 False, 'gdr')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001500 set_build_var(environ_cp, 'TF_NEED_VERBS', 'VERBS', 'with_verbs_support',
Michael Case98850a52017-09-14 13:35:57 -07001501 False, 'verbs')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001502
Yifei Fengb1d8c592017-11-22 13:42:21 -08001503 set_action_env_var(environ_cp, 'TF_NEED_OPENCL_SYCL', 'OpenCL SYCL', False)
1504 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001505 set_host_cxx_compiler(environ_cp)
1506 set_host_c_compiler(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001507 set_action_env_var(environ_cp, 'TF_NEED_COMPUTECPP', 'ComputeCPP', True)
1508 if environ_cp.get('TF_NEED_COMPUTECPP') == '1':
1509 set_computecpp_toolkit_path(environ_cp)
1510 else:
1511 set_trisycl_include_dir(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001512
1513 set_action_env_var(environ_cp, 'TF_NEED_CUDA', 'CUDA', False)
A. Unique TensorFlower24cbb2a2017-09-08 07:45:44 -07001514 if (environ_cp.get('TF_NEED_CUDA') == '1' and
1515 'TF_CUDA_CONFIG_REPO' not in environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001516 set_tf_cuda_version(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001517 set_tf_cudnn_version(environ_cp)
Guangda Lai76f69382018-01-25 23:59:19 -08001518 if is_linux():
1519 set_tf_tensorrt_install_path(environ_cp)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001520 set_tf_nccl_install_path(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001521 set_tf_cuda_compute_capabilities(environ_cp)
Ankur Taly0e6f39d2018-02-16 18:22:55 -08001522 if 'LD_LIBRARY_PATH' in environ_cp and environ_cp.get(
1523 'LD_LIBRARY_PATH') != '1':
1524 write_action_env_to_bazelrc('LD_LIBRARY_PATH',
1525 environ_cp.get('LD_LIBRARY_PATH'))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001526
1527 set_tf_cuda_clang(environ_cp)
1528 if environ_cp.get('TF_CUDA_CLANG') == '1':
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001529 # Ask whether we should download the clang toolchain.
1530 set_tf_download_clang(environ_cp)
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -08001531 if environ_cp.get('TF_DOWNLOAD_CLANG') != '1':
1532 # Set up which clang we should use as the cuda / host compiler.
1533 set_clang_cuda_compiler_path(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001534 else:
1535 # Set up which gcc nvcc should use as the host compiler
1536 # No need to set this on Windows
1537 if not is_windows():
1538 set_gcc_host_compiler_path(environ_cp)
1539 set_other_cuda_vars(environ_cp)
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001540 else:
1541 # CUDA not required. Ask whether we should download the clang toolchain and
1542 # use it for the CPU build.
1543 set_tf_download_clang(environ_cp)
1544 if environ_cp.get('TF_DOWNLOAD_CLANG') == '1':
1545 write_to_bazelrc('build --config=download_clang')
1546 write_to_bazelrc('test --config=download_clang')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001547
1548 set_build_var(environ_cp, 'TF_NEED_MPI', 'MPI', 'with_mpi_support', False)
1549 if environ_cp.get('TF_NEED_MPI') == '1':
1550 set_mpi_home(environ_cp)
1551 set_other_mpi_vars(environ_cp)
1552
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001553 set_grpc_build_flags()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001554 set_cc_opt_flags(environ_cp)
Dandelion Man?90e42f32017-12-15 18:15:07 -08001555 set_windows_build_flags()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001556
Austin Anderson6afface2017-12-05 11:59:17 -08001557 if workspace_has_any_android_rule():
1558 print('The WORKSPACE file has at least one of ["android_sdk_repository", '
1559 '"android_ndk_repository"] already set. Will not ask to help '
1560 'configure the WORKSPACE. Please delete the existing rules to '
1561 'activate the helper.\n')
1562 else:
1563 if get_var(
1564 environ_cp, 'TF_SET_ANDROID_WORKSPACE', 'android workspace',
1565 False,
1566 ('Would you like to interactively configure ./WORKSPACE for '
1567 'Android builds?'),
1568 'Searching for NDK and SDK installations.',
1569 'Not configuring the WORKSPACE for Android builds.'):
1570 create_android_ndk_rule(environ_cp)
1571 create_android_sdk_rule(environ_cp)
1572
Michael Cased31531a2018-01-05 14:09:41 -08001573 print('Preconfigured Bazel build configs. You can use any of the below by '
1574 'adding "--config=<>" to your build command. See tools/bazel.rc for '
1575 'more details.')
1576 config_info_line('mkl', 'Build with MKL support.')
1577 config_info_line('monolithic', 'Config for mostly static monolithic build.')
Austin Anderson6afface2017-12-05 11:59:17 -08001578
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001579if __name__ == '__main__':
1580 main()