blob: 7537e308b5b5ae739190d1a10a9cbb8bf66c8146 [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
21import errno
22import os
23import platform
24import re
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070025import subprocess
26import sys
27
Andrew Sellec9885ea2017-11-06 09:37:03 -080028# pylint: disable=g-import-not-at-top
Jonathan Hseu008910f2017-08-25 14:01:05 -070029try:
30 from shutil import which
31except ImportError:
32 from distutils.spawn import find_executable as which
Andrew Sellec9885ea2017-11-06 09:37:03 -080033# pylint: enable=g-import-not-at-top
Jonathan Hseu008910f2017-08-25 14:01:05 -070034
Michael Casefe2c8d82017-10-02 13:54:34 -070035_TF_BAZELRC = os.path.join(os.path.dirname(os.path.abspath(__file__)),
36 '.tf_configure.bazelrc')
Austin Anderson6afface2017-12-05 11:59:17 -080037_TF_WORKSPACE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
38 'WORKSPACE')
Dandelion Man?90e42f32017-12-15 18:15:07 -080039_DEFAULT_CUDA_VERSION = '9.0'
40_DEFAULT_CUDNN_VERSION = '7'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070041_DEFAULT_CUDA_COMPUTE_CAPABILITIES = '3.5,5.2'
42_DEFAULT_CUDA_PATH = '/usr/local/cuda'
43_DEFAULT_CUDA_PATH_LINUX = '/opt/cuda'
44_DEFAULT_CUDA_PATH_WIN = ('C:/Program Files/NVIDIA GPU Computing '
45 'Toolkit/CUDA/v%s' % _DEFAULT_CUDA_VERSION)
46_TF_OPENCL_VERSION = '1.2'
47_DEFAULT_COMPUTECPP_TOOLKIT_PATH = '/usr/local/computecpp'
Yifei Fengb1d8c592017-11-22 13:42:21 -080048_DEFAULT_TRISYCL_INCLUDE_DIR = '/usr/local/triSYCL/include'
Austin Anderson6afface2017-12-05 11:59:17 -080049_SUPPORTED_ANDROID_NDK_VERSIONS = [10, 11, 12, 13, 14, 15]
50
51_DEFAULT_PROMPT_ASK_ATTEMPTS = 10
52
53
54class UserInputError(Exception):
55 pass
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070056
57
58def is_windows():
59 return platform.system() == 'Windows'
60
61
62def is_linux():
63 return platform.system() == 'Linux'
64
65
66def is_macos():
67 return platform.system() == 'Darwin'
68
69
70def is_ppc64le():
71 return platform.machine() == 'ppc64le'
72
73
Jonathan Hseu008910f2017-08-25 14:01:05 -070074def is_cygwin():
75 return platform.system().startswith('CYGWIN_NT')
76
77
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070078def get_input(question):
79 try:
80 try:
81 answer = raw_input(question)
82 except NameError:
83 answer = input(question) # pylint: disable=bad-builtin
84 except EOFError:
85 answer = ''
86 return answer
87
88
89def symlink_force(target, link_name):
90 """Force symlink, equivalent of 'ln -sf'.
91
92 Args:
93 target: items to link to.
94 link_name: name of the link.
95 """
96 try:
97 os.symlink(target, link_name)
98 except OSError as e:
99 if e.errno == errno.EEXIST:
100 os.remove(link_name)
101 os.symlink(target, link_name)
102 else:
103 raise e
104
105
106def sed_in_place(filename, old, new):
107 """Replace old string with new string in file.
108
109 Args:
110 filename: string for filename.
111 old: string to replace.
112 new: new string to replace to.
113 """
114 with open(filename, 'r') as f:
115 filedata = f.read()
116 newdata = filedata.replace(old, new)
117 with open(filename, 'w') as f:
118 f.write(newdata)
119
120
121def remove_line_with(filename, token):
122 """Remove lines that contain token from file.
123
124 Args:
125 filename: string for filename.
126 token: string token to check if to remove a line from file or not.
127 """
128 with open(filename, 'r') as f:
129 filedata = f.read()
130
131 with open(filename, 'w') as f:
132 for line in filedata.strip().split('\n'):
133 if token not in line:
134 f.write(line + '\n')
135
136
137def write_to_bazelrc(line):
138 with open(_TF_BAZELRC, 'a') as f:
139 f.write(line + '\n')
140
141
142def write_action_env_to_bazelrc(var_name, var):
143 write_to_bazelrc('build --action_env %s="%s"' % (var_name, str(var)))
144
145
Jonathan Hseu008910f2017-08-25 14:01:05 -0700146def run_shell(cmd, allow_non_zero=False):
147 if allow_non_zero:
148 try:
149 output = subprocess.check_output(cmd)
150 except subprocess.CalledProcessError as e:
151 output = e.output
152 else:
153 output = subprocess.check_output(cmd)
154 return output.decode('UTF-8').strip()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700155
156
157def cygpath(path):
158 """Convert path from posix to windows."""
Martin Wicked57572e2017-09-02 19:21:45 -0700159 return os.path.abspath(path).replace('\\', '/')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700160
161
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700162def get_python_path(environ_cp, python_bin_path):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700163 """Get the python site package paths."""
164 python_paths = []
165 if environ_cp.get('PYTHONPATH'):
166 python_paths = environ_cp.get('PYTHONPATH').split(':')
167 try:
Jonathan Hseu008910f2017-08-25 14:01:05 -0700168 library_paths = run_shell(
169 [python_bin_path, '-c',
Austin Anderson6afface2017-12-05 11:59:17 -0800170 'import site; print("\\n".join(site.getsitepackages()))']).split('\n')
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700171 except subprocess.CalledProcessError:
Jonathan Hseu008910f2017-08-25 14:01:05 -0700172 library_paths = [run_shell(
173 [python_bin_path, '-c',
174 'from distutils.sysconfig import get_python_lib;'
175 'print(get_python_lib())'])]
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700176
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700177 all_paths = set(python_paths + library_paths)
178
179 paths = []
180 for path in all_paths:
181 if os.path.isdir(path):
182 paths.append(path)
183 return paths
184
185
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700186def get_python_major_version(python_bin_path):
187 """Get the python major version."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700188 return run_shell([python_bin_path, '-c', 'import sys; print(sys.version[0])'])
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700189
190
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700191def setup_python(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700192 """Setup python related env variables."""
193 # Get PYTHON_BIN_PATH, default is the current running python.
194 default_python_bin_path = sys.executable
195 ask_python_bin_path = ('Please specify the location of python. [Default is '
196 '%s]: ') % default_python_bin_path
197 while True:
198 python_bin_path = get_from_env_or_user_or_default(
199 environ_cp, 'PYTHON_BIN_PATH', ask_python_bin_path,
200 default_python_bin_path)
201 # Check if the path is valid
Jonathan Hseu008910f2017-08-25 14:01:05 -0700202 if os.path.isfile(python_bin_path) and os.access(
203 python_bin_path, os.X_OK):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700204 break
205 elif not os.path.exists(python_bin_path):
206 print('Invalid python path: %s cannot be found.' % python_bin_path)
207 else:
208 print('%s is not executable. Is it the python binary?' % python_bin_path)
209 environ_cp['PYTHON_BIN_PATH'] = ''
210
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700211 # Convert python path to Windows style before checking lib and version
Martin Wicked57572e2017-09-02 19:21:45 -0700212 if is_windows() or is_cygwin():
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700213 python_bin_path = cygpath(python_bin_path)
214
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700215 # Get PYTHON_LIB_PATH
216 python_lib_path = environ_cp.get('PYTHON_LIB_PATH')
217 if not python_lib_path:
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700218 python_lib_paths = get_python_path(environ_cp, python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700219 if environ_cp.get('USE_DEFAULT_PYTHON_LIB_PATH') == '1':
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700220 python_lib_path = python_lib_paths[0]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700221 else:
Jonathan Hseu008910f2017-08-25 14:01:05 -0700222 print('Found possible Python library paths:\n %s' %
223 '\n '.join(python_lib_paths))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700224 default_python_lib_path = python_lib_paths[0]
225 python_lib_path = get_input(
Jonathan Hseu008910f2017-08-25 14:01:05 -0700226 'Please input the desired Python library path to use. '
227 'Default is [%s]\n' % python_lib_paths[0])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700228 if not python_lib_path:
229 python_lib_path = default_python_lib_path
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700230 environ_cp['PYTHON_LIB_PATH'] = python_lib_path
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700231
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700232 python_major_version = get_python_major_version(python_bin_path)
233
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700234 # Convert python path to Windows style before writing into bazel.rc
Martin Wicked57572e2017-09-02 19:21:45 -0700235 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700236 python_lib_path = cygpath(python_lib_path)
237
238 # Set-up env variables used by python_configure.bzl
239 write_action_env_to_bazelrc('PYTHON_BIN_PATH', python_bin_path)
240 write_action_env_to_bazelrc('PYTHON_LIB_PATH', python_lib_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700241 write_to_bazelrc('build --force_python=py%s' % python_major_version)
242 write_to_bazelrc('build --host_force_python=py%s' % python_major_version)
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700243 write_to_bazelrc('build --python_path=\"%s"' % python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700244 environ_cp['PYTHON_BIN_PATH'] = python_bin_path
245
246 # Write tools/python_bin_path.sh
247 with open('tools/python_bin_path.sh', 'w') as f:
248 f.write('export PYTHON_BIN_PATH="%s"' % python_bin_path)
249
250
251def reset_tf_configure_bazelrc():
252 """Reset file that contains customized config settings."""
253 open(_TF_BAZELRC, 'w').close()
254
255 home = os.path.expanduser('~')
256 if not os.path.exists('.bazelrc'):
257 if os.path.exists(os.path.join(home, '.bazelrc')):
258 with open('.bazelrc', 'a') as f:
Shanqing Caie2e3a942017-09-25 19:35:53 -0700259 f.write('import %s/.bazelrc\n' % home.replace('\\', '/'))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700260 else:
261 open('.bazelrc', 'w').close()
262
263 remove_line_with('.bazelrc', 'tf_configure')
264 with open('.bazelrc', 'a') as f:
265 f.write('import %workspace%/.tf_configure.bazelrc\n')
266
267
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700268def cleanup_makefile():
269 """Delete any leftover BUILD files from the Makefile build.
270
271 These files could interfere with Bazel parsing.
272 """
273 makefile_download_dir = 'tensorflow/contrib/makefile/downloads'
274 if os.path.isdir(makefile_download_dir):
275 for root, _, filenames in os.walk(makefile_download_dir):
276 for f in filenames:
277 if f.endswith('BUILD'):
278 os.remove(os.path.join(root, f))
279
280
281def get_var(environ_cp,
282 var_name,
283 query_item,
284 enabled_by_default,
285 question=None,
286 yes_reply=None,
287 no_reply=None):
288 """Get boolean input from user.
289
290 If var_name is not set in env, ask user to enable query_item or not. If the
291 response is empty, use the default.
292
293 Args:
294 environ_cp: copy of the os.environ.
295 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
296 query_item: string for feature related to the variable, e.g. "Hadoop File
297 System".
298 enabled_by_default: boolean for default behavior.
299 question: optional string for how to ask for user input.
300 yes_reply: optionanl string for reply when feature is enabled.
301 no_reply: optional string for reply when feature is disabled.
302
303 Returns:
304 boolean value of the variable.
305 """
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)
322 while var is None:
323 user_input_origin = get_input(question)
324 user_input = user_input_origin.strip().lower()
325 if user_input == 'y':
326 print(yes_reply)
327 var = True
328 elif user_input == 'n':
329 print(no_reply)
330 var = False
331 elif not user_input:
332 if enabled_by_default:
333 print(yes_reply)
334 var = True
335 else:
336 print(no_reply)
337 var = False
338 else:
339 print('Invalid selection: %s' % user_input_origin)
340 return var
341
342
343def set_build_var(environ_cp, var_name, query_item, option_name,
Michael Case98850a52017-09-14 13:35:57 -0700344 enabled_by_default, bazel_config_name=None):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700345 """Set if query_item will be enabled for the build.
346
347 Ask user if query_item will be enabled. Default is used if no input is given.
348 Set subprocess environment variable and write to .bazelrc if enabled.
349
350 Args:
351 environ_cp: copy of the os.environ.
352 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
353 query_item: string for feature related to the variable, e.g. "Hadoop File
354 System".
355 option_name: string for option to define in .bazelrc.
356 enabled_by_default: boolean for default behavior.
Michael Case98850a52017-09-14 13:35:57 -0700357 bazel_config_name: Name for Bazel --config argument to enable build feature.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700358 """
359
360 var = str(int(get_var(environ_cp, var_name, query_item, enabled_by_default)))
361 environ_cp[var_name] = var
362 if var == '1':
363 write_to_bazelrc('build --define %s=true' % option_name)
Michael Case98850a52017-09-14 13:35:57 -0700364 elif bazel_config_name is not None:
365 # TODO(mikecase): Migrate all users of configure.py to use --config Bazel
366 # options and not to set build configs through environment variables.
367 write_to_bazelrc('build:%s --define %s=true'
368 % (bazel_config_name, option_name))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700369
370
371def set_action_env_var(environ_cp,
372 var_name,
373 query_item,
374 enabled_by_default,
375 question=None,
376 yes_reply=None,
377 no_reply=None):
378 """Set boolean action_env variable.
379
380 Ask user if query_item will be enabled. Default is used if no input is given.
381 Set environment variable and write to .bazelrc.
382
383 Args:
384 environ_cp: copy of the os.environ.
385 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
386 query_item: string for feature related to the variable, e.g. "Hadoop File
387 System".
388 enabled_by_default: boolean for default behavior.
389 question: optional string for how to ask for user input.
390 yes_reply: optionanl string for reply when feature is enabled.
391 no_reply: optional string for reply when feature is disabled.
392 """
393 var = int(
394 get_var(environ_cp, var_name, query_item, enabled_by_default, question,
395 yes_reply, no_reply))
396
397 write_action_env_to_bazelrc(var_name, var)
398 environ_cp[var_name] = str(var)
399
400
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700401def convert_version_to_int(version):
402 """Convert a version number to a integer that can be used to compare.
403
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700404 Version strings of the form X.YZ and X.Y.Z-xxxxx are supported. The
405 'xxxxx' part, for instance 'homebrew' on OS/X, is ignored.
406
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700407 Args:
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700408 version: a version to be converted
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700409
410 Returns:
411 An integer if converted successfully, otherwise return None.
412 """
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700413 version = version.split('-')[0]
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700414 version_segments = version.split('.')
415 for seg in version_segments:
416 if not seg.isdigit():
417 return None
418
419 version_str = ''.join(['%03d' % int(seg) for seg in version_segments])
420 return int(version_str)
421
422
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700423def check_bazel_version(min_version):
424 """Check installed bezel version is at least min_version.
425
426 Args:
427 min_version: string for minimum bazel version.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700428
429 Returns:
430 The bazel version detected.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700431 """
Jonathan Hseu008910f2017-08-25 14:01:05 -0700432 if which('bazel') is None:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700433 print('Cannot find bazel. Please install bazel.')
434 sys.exit(0)
Jonathan Hseu008910f2017-08-25 14:01:05 -0700435 curr_version = run_shell(['bazel', '--batch', 'version'])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700436
437 for line in curr_version.split('\n'):
438 if 'Build label: ' in line:
439 curr_version = line.split('Build label: ')[1]
440 break
441
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700442 min_version_int = convert_version_to_int(min_version)
443 curr_version_int = convert_version_to_int(curr_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700444
445 # Check if current bazel version can be detected properly.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700446 if not curr_version_int:
447 print('WARNING: current bazel installation is not a release version.')
448 print('Make sure you are running at least bazel %s' % min_version)
449 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700450
Michael Cased94271a2017-08-22 17:26:52 -0700451 print('You have bazel %s installed.' % curr_version)
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700452
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700453 if curr_version_int < min_version_int:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700454 print('Please upgrade your bazel installation to version %s or higher to '
455 'build TensorFlow!' % min_version)
456 sys.exit(0)
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700457 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700458
459
460def set_cc_opt_flags(environ_cp):
461 """Set up architecture-dependent optimization flags.
462
463 Also append CC optimization flags to bazel.rc..
464
465 Args:
466 environ_cp: copy of the os.environ.
467 """
468 if is_ppc64le():
469 # gcc on ppc64le does not support -march, use mcpu instead
470 default_cc_opt_flags = '-mcpu=native'
471 else:
472 default_cc_opt_flags = '-march=native'
473 question = ('Please specify optimization flags to use during compilation when'
474 ' bazel option "--config=opt" is specified [Default is %s]: '
475 ) % default_cc_opt_flags
476 cc_opt_flags = get_from_env_or_user_or_default(environ_cp, 'CC_OPT_FLAGS',
477 question, default_cc_opt_flags)
478 for opt in cc_opt_flags.split():
Michael Case00177422017-11-10 13:14:03 -0800479 write_to_bazelrc('build:opt --copt=%s' % opt)
480 # It should be safe on the same build host.
481 write_to_bazelrc('build:opt --host_copt=-march=native')
Michael Casebb3355d2017-11-09 08:46:31 -0800482 write_to_bazelrc('build:opt --define with_default_optimizations=true')
Michael Case00177422017-11-10 13:14:03 -0800483 # TODO(mikecase): Remove these default defines once we are able to get
484 # TF Lite targets building without them.
Andrew Selle0b154392017-11-10 10:35:35 -0800485 write_to_bazelrc('build --copt=-DGEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK')
486 write_to_bazelrc('build --host_copt=-DGEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700487
488
489def set_tf_cuda_clang(environ_cp):
490 """set TF_CUDA_CLANG action_env.
491
492 Args:
493 environ_cp: copy of the os.environ.
494 """
495 question = 'Do you want to use clang as CUDA compiler?'
496 yes_reply = 'Clang will be used as CUDA compiler.'
497 no_reply = 'nvcc will be used as CUDA compiler.'
498 set_action_env_var(
499 environ_cp,
500 'TF_CUDA_CLANG',
501 None,
502 False,
503 question=question,
504 yes_reply=yes_reply,
505 no_reply=no_reply)
506
507
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800508def set_tf_download_clang(environ_cp):
509 """Set TF_DOWNLOAD_CLANG action_env."""
510 question = 'Do you want to download a fresh release of clang? (Experimental)'
511 yes_reply = 'Clang will be downloaded and used to compile tensorflow.'
512 no_reply = 'Clang will not be downloaded.'
513 set_action_env_var(
514 environ_cp,
515 'TF_DOWNLOAD_CLANG',
516 None,
517 False,
518 question=question,
519 yes_reply=yes_reply,
520 no_reply=no_reply)
521
522
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700523def get_from_env_or_user_or_default(environ_cp, var_name, ask_for_var,
524 var_default):
525 """Get var_name either from env, or user or default.
526
527 If var_name has been set as environment variable, use the preset value, else
528 ask for user input. If no input is provided, the default is used.
529
530 Args:
531 environ_cp: copy of the os.environ.
532 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
533 ask_for_var: string for how to ask for user input.
534 var_default: default value string.
535
536 Returns:
537 string value for var_name
538 """
539 var = environ_cp.get(var_name)
540 if not var:
541 var = get_input(ask_for_var)
Michael Cased94271a2017-08-22 17:26:52 -0700542 print('\n')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700543 if not var:
544 var = var_default
545 return var
546
547
548def set_clang_cuda_compiler_path(environ_cp):
549 """Set CLANG_CUDA_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700550 default_clang_path = which('clang') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700551 ask_clang_path = ('Please specify which clang should be used as device and '
552 'host compiler. [Default is %s]: ') % default_clang_path
553
554 while True:
555 clang_cuda_compiler_path = get_from_env_or_user_or_default(
556 environ_cp, 'CLANG_CUDA_COMPILER_PATH', ask_clang_path,
557 default_clang_path)
558 if os.path.exists(clang_cuda_compiler_path):
559 break
560
561 # Reset and retry
562 print('Invalid clang path: %s cannot be found.' % clang_cuda_compiler_path)
563 environ_cp['CLANG_CUDA_COMPILER_PATH'] = ''
564
565 # Set CLANG_CUDA_COMPILER_PATH
566 environ_cp['CLANG_CUDA_COMPILER_PATH'] = clang_cuda_compiler_path
567 write_action_env_to_bazelrc('CLANG_CUDA_COMPILER_PATH',
568 clang_cuda_compiler_path)
569
570
Austin Anderson6afface2017-12-05 11:59:17 -0800571def prompt_loop_or_load_from_env(
572 environ_cp,
573 var_name,
574 var_default,
575 ask_for_var,
576 check_success,
577 error_msg,
578 suppress_default_error=False,
579 n_ask_attempts=_DEFAULT_PROMPT_ASK_ATTEMPTS
580):
581 """Loop over user prompts for an ENV param until receiving a valid response.
582
583 For the env param var_name, read from the environment or verify user input
584 until receiving valid input. When done, set var_name in the environ_cp to its
585 new value.
586
587 Args:
588 environ_cp: (Dict) copy of the os.environ.
589 var_name: (String) string for name of environment variable, e.g. "TF_MYVAR".
590 var_default: (String) default value string.
591 ask_for_var: (String) string for how to ask for user input.
592 check_success: (Function) function that takes one argument and returns a
593 boolean. Should return True if the value provided is considered valid. May
594 contain a complex error message if error_msg does not provide enough
595 information. In that case, set suppress_default_error to True.
596 error_msg: (String) String with one and only one '%s'. Formatted with each
597 invalid response upon check_success(input) failure.
598 suppress_default_error: (Bool) Suppress the above error message in favor of
599 one from the check_success function.
600 n_ask_attempts: (Integer) Number of times to query for valid input before
601 raising an error and quitting.
602
603 Returns:
604 [String] The value of var_name after querying for input.
605
606 Raises:
607 UserInputError: if a query has been attempted n_ask_attempts times without
608 success, assume that the user has made a scripting error, and will continue
609 to provide invalid input. Raise the error to avoid infinitely looping.
610 """
611 default = environ_cp.get(var_name) or var_default
612 full_query = '%s [Default is %s]: ' % (
613 ask_for_var,
614 default,
615 )
616
617 for _ in range(n_ask_attempts):
618 val = get_from_env_or_user_or_default(environ_cp,
619 var_name,
620 full_query,
621 default)
622 if check_success(val):
623 break
624 if not suppress_default_error:
625 print(error_msg % val)
626 environ_cp[var_name] = ''
627 else:
628 raise UserInputError('Invalid %s setting was provided %d times in a row. '
629 'Assuming to be a scripting mistake.' %
630 (var_name, n_ask_attempts))
631
632 environ_cp[var_name] = val
633 return val
634
635
636def create_android_ndk_rule(environ_cp):
637 """Set ANDROID_NDK_HOME and write Android NDK WORKSPACE rule."""
638 if is_windows() or is_cygwin():
639 default_ndk_path = cygpath('%s/Android/Sdk/ndk-bundle' %
640 environ_cp['APPDATA'])
641 elif is_macos():
642 default_ndk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
643 else:
644 default_ndk_path = '%s/Android/Sdk/ndk-bundle' % environ_cp['HOME']
645
646 def valid_ndk_path(path):
647 return (os.path.exists(path) and
648 os.path.exists(os.path.join(path, 'source.properties')))
649
650 android_ndk_home_path = prompt_loop_or_load_from_env(
651 environ_cp,
652 var_name='ANDROID_NDK_HOME',
653 var_default=default_ndk_path,
654 ask_for_var='Please specify the home path of the Android NDK to use.',
655 check_success=valid_ndk_path,
656 error_msg=('The path %s or its child file "source.properties" '
657 'does not exist.')
658 )
659
660 write_android_ndk_workspace_rule(android_ndk_home_path)
661
662
663def create_android_sdk_rule(environ_cp):
664 """Set Android variables and write Android SDK WORKSPACE rule."""
665 if is_windows() or is_cygwin():
666 default_sdk_path = cygpath('%s/Android/Sdk' % environ_cp['APPDATA'])
667 elif is_macos():
668 default_sdk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
669 else:
670 default_sdk_path = '%s/Android/Sdk' % environ_cp['HOME']
671
672 def valid_sdk_path(path):
673 return (os.path.exists(path) and
674 os.path.exists(os.path.join(path, 'platforms')) and
675 os.path.exists(os.path.join(path, 'build-tools')))
676
677 android_sdk_home_path = prompt_loop_or_load_from_env(
678 environ_cp,
679 var_name='ANDROID_SDK_HOME',
680 var_default=default_sdk_path,
681 ask_for_var='Please specify the home path of the Android SDK to use.',
682 check_success=valid_sdk_path,
683 error_msg=('Either %s does not exist, or it does not contain the '
684 'subdirectories "platforms" and "build-tools".'))
685
686 platforms = os.path.join(android_sdk_home_path, 'platforms')
687 api_levels = sorted(os.listdir(platforms))
688 api_levels = [x.replace('android-', '') for x in api_levels]
689
690 def valid_api_level(api_level):
691 return os.path.exists(os.path.join(android_sdk_home_path,
692 'platforms',
693 'android-' + api_level))
694
695 android_api_level = prompt_loop_or_load_from_env(
696 environ_cp,
697 var_name='ANDROID_API_LEVEL',
698 var_default=api_levels[-1],
699 ask_for_var=('Please specify the Android SDK API level to use. '
700 '[Available levels: %s]') % api_levels,
701 check_success=valid_api_level,
702 error_msg='Android-%s is not present in the SDK path.')
703
704 build_tools = os.path.join(android_sdk_home_path, 'build-tools')
705 versions = sorted(os.listdir(build_tools))
706
707 def valid_build_tools(version):
708 return os.path.exists(os.path.join(android_sdk_home_path,
709 'build-tools',
710 version))
711
712 android_build_tools_version = prompt_loop_or_load_from_env(
713 environ_cp,
714 var_name='ANDROID_BUILD_TOOLS_VERSION',
715 var_default=versions[-1],
716 ask_for_var=('Please specify an Android build tools version to use. '
717 '[Available versions: %s]') % versions,
718 check_success=valid_build_tools,
719 error_msg=('The selected SDK does not have build-tools version %s '
720 'available.'))
721
722 write_android_sdk_workspace_rule(android_sdk_home_path,
723 android_build_tools_version,
724 android_api_level)
725
726
727def write_android_sdk_workspace_rule(android_sdk_home_path,
728 android_build_tools_version,
729 android_api_level):
730 print('Writing android_sdk_workspace rule.\n')
731 with open(_TF_WORKSPACE, 'a') as f:
732 f.write("""
733android_sdk_repository(
734 name="androidsdk",
735 api_level=%s,
736 path="%s",
737 build_tools_version="%s")\n
738""" % (android_api_level, android_sdk_home_path, android_build_tools_version))
739
740
741def write_android_ndk_workspace_rule(android_ndk_home_path):
742 print('Writing android_ndk_workspace rule.')
743 ndk_api_level = check_ndk_level(android_ndk_home_path)
744 if int(ndk_api_level) not in _SUPPORTED_ANDROID_NDK_VERSIONS:
745 print('WARNING: The API level of the NDK in %s is %s, which is not '
746 'supported by Bazel (officially supported versions: %s). Please use '
747 'another version. Compiling Android targets may result in confusing '
748 'errors.\n' % (android_ndk_home_path, ndk_api_level,
749 _SUPPORTED_ANDROID_NDK_VERSIONS))
750 with open(_TF_WORKSPACE, 'a') as f:
751 f.write("""
752android_ndk_repository(
753 name="androidndk",
754 path="%s",
755 api_level=%s)\n
756""" % (android_ndk_home_path, ndk_api_level))
757
758
759def check_ndk_level(android_ndk_home_path):
760 """Check the revision number of an Android NDK path."""
761 properties_path = '%s/source.properties' % android_ndk_home_path
762 if is_windows() or is_cygwin():
763 properties_path = cygpath(properties_path)
764 with open(properties_path, 'r') as f:
765 filedata = f.read()
766
767 revision = re.search(r'Pkg.Revision = (\d+)', filedata)
768 if revision:
769 return revision.group(1)
770 return None
771
772
773def workspace_has_any_android_rule():
774 """Check the WORKSPACE for existing android_*_repository rules."""
775 with open(_TF_WORKSPACE, 'r') as f:
776 workspace = f.read()
777 has_any_rule = re.search(r'^android_[ns]dk_repository',
778 workspace,
779 re.MULTILINE)
780 return has_any_rule
781
782
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700783def set_gcc_host_compiler_path(environ_cp):
784 """Set GCC_HOST_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700785 default_gcc_host_compiler_path = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700786 cuda_bin_symlink = '%s/bin/gcc' % environ_cp.get('CUDA_TOOLKIT_PATH')
787
788 if os.path.islink(cuda_bin_symlink):
789 # os.readlink is only available in linux
Jonathan Hseu008910f2017-08-25 14:01:05 -0700790 default_gcc_host_compiler_path = os.path.realpath(cuda_bin_symlink)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700791
Austin Anderson6afface2017-12-05 11:59:17 -0800792 gcc_host_compiler_path = prompt_loop_or_load_from_env(
793 environ_cp,
794 var_name='GCC_HOST_COMPILER_PATH',
795 var_default=default_gcc_host_compiler_path,
796 ask_for_var=
797 'Please specify which gcc should be used by nvcc as the host compiler.',
798 check_success=os.path.exists,
799 error_msg='Invalid gcc path. %s cannot be found.',
800 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700801
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700802 write_action_env_to_bazelrc('GCC_HOST_COMPILER_PATH', gcc_host_compiler_path)
803
804
805def set_tf_cuda_version(environ_cp):
806 """Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION."""
807 ask_cuda_version = (
808 'Please specify the CUDA SDK version you want to use, '
809 'e.g. 7.0. [Leave empty to default to CUDA %s]: ') % _DEFAULT_CUDA_VERSION
810
Austin Andersonf9a88f82017-12-13 11:49:40 -0800811 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700812 # Configure the Cuda SDK version to use.
813 tf_cuda_version = get_from_env_or_user_or_default(
814 environ_cp, 'TF_CUDA_VERSION', ask_cuda_version, _DEFAULT_CUDA_VERSION)
815
816 # Find out where the CUDA toolkit is installed
817 default_cuda_path = _DEFAULT_CUDA_PATH
Martin Wicked57572e2017-09-02 19:21:45 -0700818 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700819 default_cuda_path = cygpath(
820 environ_cp.get('CUDA_PATH', _DEFAULT_CUDA_PATH_WIN))
821 elif is_linux():
822 # If the default doesn't exist, try an alternative default.
823 if (not os.path.exists(default_cuda_path)
824 ) and os.path.exists(_DEFAULT_CUDA_PATH_LINUX):
825 default_cuda_path = _DEFAULT_CUDA_PATH_LINUX
826 ask_cuda_path = ('Please specify the location where CUDA %s toolkit is'
827 ' installed. Refer to README.md for more details. '
828 '[Default is %s]: ') % (tf_cuda_version, default_cuda_path)
829 cuda_toolkit_path = get_from_env_or_user_or_default(
830 environ_cp, 'CUDA_TOOLKIT_PATH', ask_cuda_path, default_cuda_path)
831
832 if is_windows():
833 cuda_rt_lib_path = 'lib/x64/cudart.lib'
834 elif is_linux():
835 cuda_rt_lib_path = 'lib64/libcudart.so.%s' % tf_cuda_version
836 elif is_macos():
837 cuda_rt_lib_path = 'lib/libcudart.%s.dylib' % tf_cuda_version
838
839 cuda_toolkit_path_full = os.path.join(cuda_toolkit_path, cuda_rt_lib_path)
840 if os.path.exists(cuda_toolkit_path_full):
841 break
842
843 # Reset and retry
844 print('Invalid path to CUDA %s toolkit. %s cannot be found' %
845 (tf_cuda_version, cuda_toolkit_path_full))
846 environ_cp['TF_CUDA_VERSION'] = ''
847 environ_cp['CUDA_TOOLKIT_PATH'] = ''
848
Austin Andersonf9a88f82017-12-13 11:49:40 -0800849 else:
850 raise UserInputError('Invalid TF_CUDA_SETTING setting was provided %d '
851 'times in a row. Assuming to be a scripting mistake.' %
852 _DEFAULT_PROMPT_ASK_ATTEMPTS)
853
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700854 # Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION
855 environ_cp['CUDA_TOOLKIT_PATH'] = cuda_toolkit_path
856 write_action_env_to_bazelrc('CUDA_TOOLKIT_PATH', cuda_toolkit_path)
857 environ_cp['TF_CUDA_VERSION'] = tf_cuda_version
858 write_action_env_to_bazelrc('TF_CUDA_VERSION', tf_cuda_version)
859
860
Yifei Fengb1d8c592017-11-22 13:42:21 -0800861def set_tf_cudnn_version(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700862 """Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION."""
863 ask_cudnn_version = (
Jonathan Hseu008910f2017-08-25 14:01:05 -0700864 'Please specify the cuDNN version you want to use. '
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700865 '[Leave empty to default to cuDNN %s.0]: ') % _DEFAULT_CUDNN_VERSION
866
Austin Andersonf9a88f82017-12-13 11:49:40 -0800867 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700868 tf_cudnn_version = get_from_env_or_user_or_default(
869 environ_cp, 'TF_CUDNN_VERSION', ask_cudnn_version,
870 _DEFAULT_CUDNN_VERSION)
871
872 default_cudnn_path = environ_cp.get('CUDA_TOOLKIT_PATH')
873 ask_cudnn_path = (r'Please specify the location where cuDNN %s library is '
874 'installed. Refer to README.md for more details. [Default'
875 ' is %s]:') % (tf_cudnn_version, default_cudnn_path)
876 cudnn_install_path = get_from_env_or_user_or_default(
877 environ_cp, 'CUDNN_INSTALL_PATH', ask_cudnn_path, default_cudnn_path)
878
879 # Result returned from "read" will be used unexpanded. That make "~"
880 # unusable. Going through one more level of expansion to handle that.
881 cudnn_install_path = os.path.realpath(
882 os.path.expanduser(cudnn_install_path))
Martin Wicked57572e2017-09-02 19:21:45 -0700883 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700884 cudnn_install_path = cygpath(cudnn_install_path)
885
886 if is_windows():
887 cuda_dnn_lib_path = 'lib/x64/cudnn.lib'
888 cuda_dnn_lib_alt_path = 'lib/x64/cudnn.lib'
889 elif is_linux():
890 cuda_dnn_lib_path = 'lib64/libcudnn.so.%s' % tf_cudnn_version
891 cuda_dnn_lib_alt_path = 'libcudnn.so.%s' % tf_cudnn_version
892 elif is_macos():
893 cuda_dnn_lib_path = 'lib/libcudnn.%s.dylib' % tf_cudnn_version
894 cuda_dnn_lib_alt_path = 'libcudnn.%s.dylib' % tf_cudnn_version
895
896 cuda_dnn_lib_path_full = os.path.join(cudnn_install_path, cuda_dnn_lib_path)
897 cuda_dnn_lib_alt_path_full = os.path.join(cudnn_install_path,
898 cuda_dnn_lib_alt_path)
899 if os.path.exists(cuda_dnn_lib_path_full) or os.path.exists(
900 cuda_dnn_lib_alt_path_full):
901 break
902
903 # Try another alternative for Linux
904 if is_linux():
Jonathan Hseu008910f2017-08-25 14:01:05 -0700905 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
906 cudnn_path_from_ldconfig = run_shell([ldconfig_bin, '-p'])
907 cudnn_path_from_ldconfig = re.search('.*libcudnn.so .* => (.*)',
A. Unique TensorFlowere7223582017-09-06 17:57:04 -0700908 cudnn_path_from_ldconfig)
909 if cudnn_path_from_ldconfig:
910 cudnn_path_from_ldconfig = cudnn_path_from_ldconfig.group(1)
911 if os.path.exists('%s.%s' % (cudnn_path_from_ldconfig,
912 tf_cudnn_version)):
913 cudnn_install_path = os.path.dirname(cudnn_path_from_ldconfig)
914 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700915
916 # Reset and Retry
917 print(
918 'Invalid path to cuDNN %s toolkit. None of the following files can be '
919 'found:' % tf_cudnn_version)
920 print(cuda_dnn_lib_path_full)
921 print(cuda_dnn_lib_alt_path_full)
922 if is_linux():
923 print('%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version))
924
925 environ_cp['TF_CUDNN_VERSION'] = ''
Austin Andersonf9a88f82017-12-13 11:49:40 -0800926 else:
927 raise UserInputError('Invalid TF_CUDNN setting was provided %d '
928 'times in a row. Assuming to be a scripting mistake.' %
929 _DEFAULT_PROMPT_ASK_ATTEMPTS)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700930
931 # Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION
932 environ_cp['CUDNN_INSTALL_PATH'] = cudnn_install_path
933 write_action_env_to_bazelrc('CUDNN_INSTALL_PATH', cudnn_install_path)
934 environ_cp['TF_CUDNN_VERSION'] = tf_cudnn_version
935 write_action_env_to_bazelrc('TF_CUDNN_VERSION', tf_cudnn_version)
936
937
938def get_native_cuda_compute_capabilities(environ_cp):
939 """Get native cuda compute capabilities.
940
941 Args:
942 environ_cp: copy of the os.environ.
943 Returns:
944 string of native cuda compute capabilities, separated by comma.
945 """
946 device_query_bin = os.path.join(
947 environ_cp.get('CUDA_TOOLKIT_PATH'), 'extras/demo_suite/deviceQuery')
Jonathan Hseu008910f2017-08-25 14:01:05 -0700948 if os.path.isfile(device_query_bin) and os.access(device_query_bin, os.X_OK):
949 try:
950 output = run_shell(device_query_bin).split('\n')
951 pattern = re.compile('[0-9]*\\.[0-9]*')
952 output = [pattern.search(x) for x in output if 'Capability' in x]
953 output = ','.join(x.group() for x in output if x is not None)
954 except subprocess.CalledProcessError:
955 output = ''
956 else:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700957 output = ''
958 return output
959
960
961def set_tf_cuda_compute_capabilities(environ_cp):
962 """Set TF_CUDA_COMPUTE_CAPABILITIES."""
963 while True:
964 native_cuda_compute_capabilities = get_native_cuda_compute_capabilities(
965 environ_cp)
966 if not native_cuda_compute_capabilities:
967 default_cuda_compute_capabilities = _DEFAULT_CUDA_COMPUTE_CAPABILITIES
968 else:
969 default_cuda_compute_capabilities = native_cuda_compute_capabilities
970
971 ask_cuda_compute_capabilities = (
972 'Please specify a list of comma-separated '
973 'Cuda compute capabilities you want to '
974 'build with.\nYou can find the compute '
975 'capability of your device at: '
976 'https://developer.nvidia.com/cuda-gpus.\nPlease'
977 ' note that each additional compute '
978 'capability significantly increases your '
979 'build time and binary size. [Default is: %s]' %
980 default_cuda_compute_capabilities)
981 tf_cuda_compute_capabilities = get_from_env_or_user_or_default(
982 environ_cp, 'TF_CUDA_COMPUTE_CAPABILITIES',
983 ask_cuda_compute_capabilities, default_cuda_compute_capabilities)
984 # Check whether all capabilities from the input is valid
985 all_valid = True
986 for compute_capability in tf_cuda_compute_capabilities.split(','):
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700987 m = re.match('[0-9]+.[0-9]+', compute_capability)
988 if not m:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700989 print('Invalid compute capability: ' % compute_capability)
990 all_valid = False
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700991 else:
992 ver = int(m.group(0).split('.')[0])
993 if ver < 3:
994 print('Only compute capabilities 3.0 or higher are supported.')
995 all_valid = False
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700996
997 if all_valid:
998 break
999
1000 # Reset and Retry
1001 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = ''
1002
1003 # Set TF_CUDA_COMPUTE_CAPABILITIES
1004 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = tf_cuda_compute_capabilities
1005 write_action_env_to_bazelrc('TF_CUDA_COMPUTE_CAPABILITIES',
1006 tf_cuda_compute_capabilities)
1007
1008
1009def set_other_cuda_vars(environ_cp):
1010 """Set other CUDA related variables."""
1011 if is_windows():
1012 # The following three variables are needed for MSVC toolchain configuration
1013 # in Bazel
1014 environ_cp['CUDA_PATH'] = environ_cp.get('CUDA_TOOLKIT_PATH')
1015 environ_cp['CUDA_COMPUTE_CAPABILITIES'] = environ_cp.get(
1016 'TF_CUDA_COMPUTE_CAPABILITIES')
1017 environ_cp['NO_WHOLE_ARCHIVE_OPTION'] = 1
1018 write_action_env_to_bazelrc('CUDA_PATH', environ_cp.get('CUDA_PATH'))
1019 write_action_env_to_bazelrc('CUDA_COMPUTE_CAPABILITIE',
1020 environ_cp.get('CUDA_COMPUTE_CAPABILITIE'))
1021 write_action_env_to_bazelrc('NO_WHOLE_ARCHIVE_OPTION',
1022 environ_cp.get('NO_WHOLE_ARCHIVE_OPTION'))
1023 write_to_bazelrc('build --config=win-cuda')
1024 write_to_bazelrc('test --config=win-cuda')
1025 else:
1026 # If CUDA is enabled, always use GPU during build and test.
1027 if environ_cp.get('TF_CUDA_CLANG') == '1':
1028 write_to_bazelrc('build --config=cuda_clang')
1029 write_to_bazelrc('test --config=cuda_clang')
1030 else:
1031 write_to_bazelrc('build --config=cuda')
1032 write_to_bazelrc('test --config=cuda')
1033
1034
1035def set_host_cxx_compiler(environ_cp):
1036 """Set HOST_CXX_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001037 default_cxx_host_compiler = which('g++') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001038
Austin Anderson6afface2017-12-05 11:59:17 -08001039 host_cxx_compiler = prompt_loop_or_load_from_env(
1040 environ_cp,
1041 var_name='HOST_CXX_COMPILER',
1042 var_default=default_cxx_host_compiler,
1043 ask_for_var=('Please specify which C++ compiler should be used as the '
1044 'host C++ compiler.'),
1045 check_success=os.path.exists,
1046 error_msg='Invalid C++ compiler path. %s cannot be found.',
1047 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001048
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001049 write_action_env_to_bazelrc('HOST_CXX_COMPILER', host_cxx_compiler)
1050
1051
1052def set_host_c_compiler(environ_cp):
1053 """Set HOST_C_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001054 default_c_host_compiler = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001055
Austin Anderson6afface2017-12-05 11:59:17 -08001056 host_c_compiler = prompt_loop_or_load_from_env(
1057 environ_cp,
1058 var_name='HOST_C_COMPILER',
1059 var_default=default_c_host_compiler,
1060 ask_for_var=('Please specify which C compiler should be used as the host'
1061 'C compiler.'),
1062 check_success=os.path.exists,
1063 error_msg='Invalid C compiler path. %s cannot be found.',
1064 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001065
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001066 write_action_env_to_bazelrc('HOST_C_COMPILER', host_c_compiler)
1067
1068
1069def set_computecpp_toolkit_path(environ_cp):
1070 """Set COMPUTECPP_TOOLKIT_PATH."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001071
Austin Anderson6afface2017-12-05 11:59:17 -08001072 def toolkit_exists(toolkit_path):
1073 """Check if a computecpp toolkit path is valid."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001074 if is_linux():
1075 sycl_rt_lib_path = 'lib/libComputeCpp.so'
1076 else:
1077 sycl_rt_lib_path = ''
1078
Austin Anderson6afface2017-12-05 11:59:17 -08001079 sycl_rt_lib_path_full = os.path.join(toolkit_path,
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001080 sycl_rt_lib_path)
Austin Anderson6afface2017-12-05 11:59:17 -08001081 exists = os.path.exists(sycl_rt_lib_path_full)
1082 if not exists:
1083 print('Invalid SYCL %s library path. %s cannot be found' %
1084 (_TF_OPENCL_VERSION, sycl_rt_lib_path_full))
1085 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001086
Austin Anderson6afface2017-12-05 11:59:17 -08001087 computecpp_toolkit_path = prompt_loop_or_load_from_env(
1088 environ_cp,
1089 var_name='COMPUTECPP_TOOLKIT_PATH',
1090 var_default=_DEFAULT_COMPUTECPP_TOOLKIT_PATH,
1091 ask_for_var=(
1092 'Please specify the location where ComputeCpp for SYCL %s is '
1093 'installed.' % _TF_OPENCL_VERSION),
1094 check_success=toolkit_exists,
1095 error_msg='Invalid SYCL compiler path. %s cannot be found.',
1096 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001097
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001098 write_action_env_to_bazelrc('COMPUTECPP_TOOLKIT_PATH',
1099 computecpp_toolkit_path)
1100
Michael Cased31531a2018-01-05 14:09:41 -08001101
Dandelion Man?90e42f32017-12-15 18:15:07 -08001102def set_trisycl_include_dir(environ_cp):
Michael Cased31531a2018-01-05 14:09:41 -08001103 """Set TRISYCL_INCLUDE_DIR."""
Dandelion Man?90e42f32017-12-15 18:15:07 -08001104 ask_trisycl_include_dir = ('Please specify the location of the triSYCL '
1105 'include directory. (Use --config=sycl_trisycl '
1106 'when building with Bazel) '
1107 '[Default is %s]: '
Michael Cased31531a2018-01-05 14:09:41 -08001108 ) % (_DEFAULT_TRISYCL_INCLUDE_DIR)
Dandelion Man?90e42f32017-12-15 18:15:07 -08001109 while True:
1110 trisycl_include_dir = get_from_env_or_user_or_default(
Michael Cased31531a2018-01-05 14:09:41 -08001111 environ_cp, 'TRISYCL_INCLUDE_DIR', ask_trisycl_include_dir,
1112 _DEFAULT_TRISYCL_INCLUDE_DIR)
Dandelion Man?90e42f32017-12-15 18:15:07 -08001113 if os.path.exists(trisycl_include_dir):
1114 break
1115
1116 print('Invalid triSYCL include directory, %s cannot be found'
1117 % (trisycl_include_dir))
1118
1119 # Set TRISYCL_INCLUDE_DIR
1120 environ_cp['TRISYCL_INCLUDE_DIR'] = trisycl_include_dir
1121 write_action_env_to_bazelrc('TRISYCL_INCLUDE_DIR',
1122 trisycl_include_dir)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001123
Yifei Fengb1d8c592017-11-22 13:42:21 -08001124
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001125def set_mpi_home(environ_cp):
1126 """Set MPI_HOME."""
Austin Anderson6afface2017-12-05 11:59:17 -08001127
Jonathan Hseu008910f2017-08-25 14:01:05 -07001128 default_mpi_home = which('mpirun') or which('mpiexec') or ''
1129 default_mpi_home = os.path.dirname(os.path.dirname(default_mpi_home))
1130
Austin Anderson6afface2017-12-05 11:59:17 -08001131 def valid_mpi_path(mpi_home):
1132 exists = (os.path.exists(os.path.join(mpi_home, 'include')) and
1133 os.path.exists(os.path.join(mpi_home, 'lib')))
1134 if not exists:
1135 print('Invalid path to the MPI Toolkit. %s or %s cannot be found' %
1136 (os.path.join(mpi_home, 'include'),
1137 os.path.exists(os.path.join(mpi_home, 'lib'))))
1138 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001139
Austin Anderson6afface2017-12-05 11:59:17 -08001140 _ = prompt_loop_or_load_from_env(
1141 environ_cp,
1142 var_name='MPI_HOME',
1143 var_default=default_mpi_home,
1144 ask_for_var='Please specify the MPI toolkit folder.',
1145 check_success=valid_mpi_path,
1146 error_msg='',
1147 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001148
1149
1150def set_other_mpi_vars(environ_cp):
1151 """Set other MPI related variables."""
1152 # Link the MPI header files
1153 mpi_home = environ_cp.get('MPI_HOME')
1154 symlink_force('%s/include/mpi.h' % mpi_home, 'third_party/mpi/mpi.h')
1155
1156 # Determine if we use OpenMPI or MVAPICH, these require different header files
1157 # to be included here to make bazel dependency checker happy
1158 if os.path.exists(os.path.join(mpi_home, 'include/mpi_portable_platform.h')):
1159 symlink_force(
1160 os.path.join(mpi_home, 'include/mpi_portable_platform.h'),
1161 'third_party/mpi/mpi_portable_platform.h')
1162 # TODO(gunan): avoid editing files in configure
1163 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=False',
1164 'MPI_LIB_IS_OPENMPI=True')
1165 else:
1166 # MVAPICH / MPICH
1167 symlink_force(
1168 os.path.join(mpi_home, 'include/mpio.h'), 'third_party/mpi/mpio.h')
1169 symlink_force(
1170 os.path.join(mpi_home, 'include/mpicxx.h'), 'third_party/mpi/mpicxx.h')
1171 # TODO(gunan): avoid editing files in configure
1172 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=True',
1173 'MPI_LIB_IS_OPENMPI=False')
1174
1175 if os.path.exists(os.path.join(mpi_home, 'lib/libmpi.so')):
1176 symlink_force(
1177 os.path.join(mpi_home, 'lib/libmpi.so'), 'third_party/mpi/libmpi.so')
1178 else:
1179 raise ValueError('Cannot find the MPI library file in %s/lib' % mpi_home)
1180
1181
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001182def set_grpc_build_flags():
1183 write_to_bazelrc('build --define grpc_no_ares=true')
1184
Michael Cased31531a2018-01-05 14:09:41 -08001185
Dandelion Man?90e42f32017-12-15 18:15:07 -08001186def set_windows_build_flags():
1187 if is_windows():
1188 # The non-monolithic build is not supported yet
1189 write_to_bazelrc('build --config monolithic')
1190 # Suppress warning messages
1191 write_to_bazelrc('build --copt=-w --host_copt=-w')
1192 # Output more verbose information when something goes wrong
1193 write_to_bazelrc('build --verbose_failures')
1194
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001195
Michael Cased31531a2018-01-05 14:09:41 -08001196def config_info_line(name, help_text):
1197 """Helper function to print formatted help text for Bazel config options."""
1198 print('\t--config=%-12s\t# %s' % (name, help_text))
1199
1200
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001201def main():
1202 # Make a copy of os.environ to be clear when functions and getting and setting
1203 # environment variables.
1204 environ_cp = dict(os.environ)
1205
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -07001206 check_bazel_version('0.5.4')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001207
1208 reset_tf_configure_bazelrc()
1209 cleanup_makefile()
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -07001210 setup_python(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001211
1212 if is_windows():
Benoit Steiner355e25e2017-10-24 19:47:46 -07001213 environ_cp['TF_NEED_S3'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001214 environ_cp['TF_NEED_GCP'] = '0'
1215 environ_cp['TF_NEED_HDFS'] = '0'
1216 environ_cp['TF_NEED_JEMALLOC'] = '0'
Yifei Fengb1d8c592017-11-22 13:42:21 -08001217 environ_cp['TF_NEED_OPENCL_SYCL'] = '0'
1218 environ_cp['TF_NEED_COMPUTECPP'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001219 environ_cp['TF_NEED_OPENCL'] = '0'
1220 environ_cp['TF_CUDA_CLANG'] = '0'
1221
1222 if is_macos():
1223 environ_cp['TF_NEED_JEMALLOC'] = '0'
1224
1225 set_build_var(environ_cp, 'TF_NEED_JEMALLOC', 'jemalloc as malloc',
1226 'with_jemalloc', True)
1227 set_build_var(environ_cp, 'TF_NEED_GCP', 'Google Cloud Platform',
Benoit Steiner355e25e2017-10-24 19:47:46 -07001228 'with_gcp_support', True, 'gcp')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001229 set_build_var(environ_cp, 'TF_NEED_HDFS', 'Hadoop File System',
Benoit Steiner355e25e2017-10-24 19:47:46 -07001230 'with_hdfs_support', True, 'hdfs')
Michael Case7e4e3362017-10-09 13:31:15 -07001231 set_build_var(environ_cp, 'TF_NEED_S3', 'Amazon S3 File System',
1232 'with_s3_support', True, 's3')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001233 set_build_var(environ_cp, 'TF_ENABLE_XLA', 'XLA JIT', 'with_xla_support',
Michael Case98850a52017-09-14 13:35:57 -07001234 False, 'xla')
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -07001235 set_build_var(environ_cp, 'TF_NEED_GDR', 'GDR', 'with_gdr_support',
Michael Case98850a52017-09-14 13:35:57 -07001236 False, 'gdr')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001237 set_build_var(environ_cp, 'TF_NEED_VERBS', 'VERBS', 'with_verbs_support',
Michael Case98850a52017-09-14 13:35:57 -07001238 False, 'verbs')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001239
Yifei Fengb1d8c592017-11-22 13:42:21 -08001240 set_action_env_var(environ_cp, 'TF_NEED_OPENCL_SYCL', 'OpenCL SYCL', False)
1241 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001242 set_host_cxx_compiler(environ_cp)
1243 set_host_c_compiler(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001244 set_action_env_var(environ_cp, 'TF_NEED_COMPUTECPP', 'ComputeCPP', True)
1245 if environ_cp.get('TF_NEED_COMPUTECPP') == '1':
1246 set_computecpp_toolkit_path(environ_cp)
1247 else:
1248 set_trisycl_include_dir(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001249
1250 set_action_env_var(environ_cp, 'TF_NEED_CUDA', 'CUDA', False)
A. Unique TensorFlower24cbb2a2017-09-08 07:45:44 -07001251 if (environ_cp.get('TF_NEED_CUDA') == '1' and
1252 'TF_CUDA_CONFIG_REPO' not in environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001253 set_tf_cuda_version(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001254 set_tf_cudnn_version(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001255 set_tf_cuda_compute_capabilities(environ_cp)
1256
1257 set_tf_cuda_clang(environ_cp)
1258 if environ_cp.get('TF_CUDA_CLANG') == '1':
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -08001259 if not is_windows():
1260 # Ask if we want to download clang release while building.
1261 set_tf_download_clang(environ_cp)
1262 else:
1263 # We use bazel's generated crosstool on Windows and there is no
1264 # way to provide downloaded toolchain for that yet.
1265 # TODO(ibiryukov): Investigate using clang as a cuda compiler on
1266 # Windows.
1267 environ_cp['TF_DOWNLOAD_CLANG'] = '0'
1268
1269 if environ_cp.get('TF_DOWNLOAD_CLANG') != '1':
1270 # Set up which clang we should use as the cuda / host compiler.
1271 set_clang_cuda_compiler_path(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001272 else:
1273 # Set up which gcc nvcc should use as the host compiler
1274 # No need to set this on Windows
1275 if not is_windows():
1276 set_gcc_host_compiler_path(environ_cp)
1277 set_other_cuda_vars(environ_cp)
1278
1279 set_build_var(environ_cp, 'TF_NEED_MPI', 'MPI', 'with_mpi_support', False)
1280 if environ_cp.get('TF_NEED_MPI') == '1':
1281 set_mpi_home(environ_cp)
1282 set_other_mpi_vars(environ_cp)
1283
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001284 set_grpc_build_flags()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001285 set_cc_opt_flags(environ_cp)
Dandelion Man?90e42f32017-12-15 18:15:07 -08001286 set_windows_build_flags()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001287
Austin Anderson6afface2017-12-05 11:59:17 -08001288 if workspace_has_any_android_rule():
1289 print('The WORKSPACE file has at least one of ["android_sdk_repository", '
1290 '"android_ndk_repository"] already set. Will not ask to help '
1291 'configure the WORKSPACE. Please delete the existing rules to '
1292 'activate the helper.\n')
1293 else:
1294 if get_var(
1295 environ_cp, 'TF_SET_ANDROID_WORKSPACE', 'android workspace',
1296 False,
1297 ('Would you like to interactively configure ./WORKSPACE for '
1298 'Android builds?'),
1299 'Searching for NDK and SDK installations.',
1300 'Not configuring the WORKSPACE for Android builds.'):
1301 create_android_ndk_rule(environ_cp)
1302 create_android_sdk_rule(environ_cp)
1303
Michael Cased31531a2018-01-05 14:09:41 -08001304 print('Preconfigured Bazel build configs. You can use any of the below by '
1305 'adding "--config=<>" to your build command. See tools/bazel.rc for '
1306 'more details.')
1307 config_info_line('mkl', 'Build with MKL support.')
1308 config_info_line('monolithic', 'Config for mostly static monolithic build.')
Austin Anderson6afface2017-12-05 11:59:17 -08001309
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001310if __name__ == '__main__':
1311 main()