blob: cf16ef483763733cc12c838ea92b144c6493f0b1 [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.
Frank Chenc4ef9272018-01-10 11:36:52 -0800305
306 Raises:
307 UserInputError: if an environment variable is set, but it cannot be
308 interpreted as a boolean indicator, assume that the user has made a
309 scripting error, and will continue to provide invalid input.
310 Raise the error to avoid infinitely looping.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700311 """
312 if not question:
313 question = 'Do you wish to build TensorFlow with %s support?' % query_item
314 if not yes_reply:
315 yes_reply = '%s support will be enabled for TensorFlow.' % query_item
316 if not no_reply:
317 no_reply = 'No %s' % yes_reply
318
319 yes_reply += '\n'
320 no_reply += '\n'
321
322 if enabled_by_default:
323 question += ' [Y/n]: '
324 else:
325 question += ' [y/N]: '
326
327 var = environ_cp.get(var_name)
Frank Chenc4ef9272018-01-10 11:36:52 -0800328 if var is not None:
329 var_content = var.strip().lower()
330 true_strings = ('1', 't', 'true', 'y', 'yes')
331 false_strings = ('0', 'f', 'false', 'n', 'no')
332 if var_content in true_strings:
333 var = True
334 elif var_content in false_strings:
335 var = False
336 else:
337 raise UserInputError(
338 'Environment variable %s must be set as a boolean indicator.\n'
339 'The following are accepted as TRUE : %s.\n'
340 'The following are accepted as FALSE: %s.\n'
341 'Current value is %s.' % (
342 var_name, ', '.join(true_strings), ', '.join(false_strings),
343 var))
344
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700345 while var is None:
346 user_input_origin = get_input(question)
347 user_input = user_input_origin.strip().lower()
348 if user_input == 'y':
349 print(yes_reply)
350 var = True
351 elif user_input == 'n':
352 print(no_reply)
353 var = False
354 elif not user_input:
355 if enabled_by_default:
356 print(yes_reply)
357 var = True
358 else:
359 print(no_reply)
360 var = False
361 else:
362 print('Invalid selection: %s' % user_input_origin)
363 return var
364
365
366def set_build_var(environ_cp, var_name, query_item, option_name,
Michael Case98850a52017-09-14 13:35:57 -0700367 enabled_by_default, bazel_config_name=None):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700368 """Set if query_item will be enabled for the build.
369
370 Ask user if query_item will be enabled. Default is used if no input is given.
371 Set subprocess environment variable and write to .bazelrc if enabled.
372
373 Args:
374 environ_cp: copy of the os.environ.
375 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
376 query_item: string for feature related to the variable, e.g. "Hadoop File
377 System".
378 option_name: string for option to define in .bazelrc.
379 enabled_by_default: boolean for default behavior.
Michael Case98850a52017-09-14 13:35:57 -0700380 bazel_config_name: Name for Bazel --config argument to enable build feature.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700381 """
382
383 var = str(int(get_var(environ_cp, var_name, query_item, enabled_by_default)))
384 environ_cp[var_name] = var
385 if var == '1':
386 write_to_bazelrc('build --define %s=true' % option_name)
Michael Case98850a52017-09-14 13:35:57 -0700387 elif bazel_config_name is not None:
388 # TODO(mikecase): Migrate all users of configure.py to use --config Bazel
389 # options and not to set build configs through environment variables.
390 write_to_bazelrc('build:%s --define %s=true'
391 % (bazel_config_name, option_name))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700392
393
394def set_action_env_var(environ_cp,
395 var_name,
396 query_item,
397 enabled_by_default,
398 question=None,
399 yes_reply=None,
400 no_reply=None):
401 """Set boolean action_env variable.
402
403 Ask user if query_item will be enabled. Default is used if no input is given.
404 Set environment variable and write to .bazelrc.
405
406 Args:
407 environ_cp: copy of the os.environ.
408 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
409 query_item: string for feature related to the variable, e.g. "Hadoop File
410 System".
411 enabled_by_default: boolean for default behavior.
412 question: optional string for how to ask for user input.
413 yes_reply: optionanl string for reply when feature is enabled.
414 no_reply: optional string for reply when feature is disabled.
415 """
416 var = int(
417 get_var(environ_cp, var_name, query_item, enabled_by_default, question,
418 yes_reply, no_reply))
419
420 write_action_env_to_bazelrc(var_name, var)
421 environ_cp[var_name] = str(var)
422
423
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700424def convert_version_to_int(version):
425 """Convert a version number to a integer that can be used to compare.
426
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700427 Version strings of the form X.YZ and X.Y.Z-xxxxx are supported. The
428 'xxxxx' part, for instance 'homebrew' on OS/X, is ignored.
429
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700430 Args:
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700431 version: a version to be converted
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700432
433 Returns:
434 An integer if converted successfully, otherwise return None.
435 """
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700436 version = version.split('-')[0]
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700437 version_segments = version.split('.')
438 for seg in version_segments:
439 if not seg.isdigit():
440 return None
441
442 version_str = ''.join(['%03d' % int(seg) for seg in version_segments])
443 return int(version_str)
444
445
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700446def check_bazel_version(min_version):
447 """Check installed bezel version is at least min_version.
448
449 Args:
450 min_version: string for minimum bazel version.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700451
452 Returns:
453 The bazel version detected.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700454 """
Jonathan Hseu008910f2017-08-25 14:01:05 -0700455 if which('bazel') is None:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700456 print('Cannot find bazel. Please install bazel.')
457 sys.exit(0)
Jonathan Hseu008910f2017-08-25 14:01:05 -0700458 curr_version = run_shell(['bazel', '--batch', 'version'])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700459
460 for line in curr_version.split('\n'):
461 if 'Build label: ' in line:
462 curr_version = line.split('Build label: ')[1]
463 break
464
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700465 min_version_int = convert_version_to_int(min_version)
466 curr_version_int = convert_version_to_int(curr_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700467
468 # Check if current bazel version can be detected properly.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700469 if not curr_version_int:
470 print('WARNING: current bazel installation is not a release version.')
471 print('Make sure you are running at least bazel %s' % min_version)
472 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700473
Michael Cased94271a2017-08-22 17:26:52 -0700474 print('You have bazel %s installed.' % curr_version)
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700475
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700476 if curr_version_int < min_version_int:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700477 print('Please upgrade your bazel installation to version %s or higher to '
478 'build TensorFlow!' % min_version)
479 sys.exit(0)
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700480 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700481
482
483def set_cc_opt_flags(environ_cp):
484 """Set up architecture-dependent optimization flags.
485
486 Also append CC optimization flags to bazel.rc..
487
488 Args:
489 environ_cp: copy of the os.environ.
490 """
491 if is_ppc64le():
492 # gcc on ppc64le does not support -march, use mcpu instead
493 default_cc_opt_flags = '-mcpu=native'
494 else:
495 default_cc_opt_flags = '-march=native'
496 question = ('Please specify optimization flags to use during compilation when'
497 ' bazel option "--config=opt" is specified [Default is %s]: '
498 ) % default_cc_opt_flags
499 cc_opt_flags = get_from_env_or_user_or_default(environ_cp, 'CC_OPT_FLAGS',
500 question, default_cc_opt_flags)
501 for opt in cc_opt_flags.split():
Michael Case00177422017-11-10 13:14:03 -0800502 write_to_bazelrc('build:opt --copt=%s' % opt)
503 # It should be safe on the same build host.
504 write_to_bazelrc('build:opt --host_copt=-march=native')
Michael Casebb3355d2017-11-09 08:46:31 -0800505 write_to_bazelrc('build:opt --define with_default_optimizations=true')
Michael Case00177422017-11-10 13:14:03 -0800506 # TODO(mikecase): Remove these default defines once we are able to get
507 # TF Lite targets building without them.
Andrew Selle0b154392017-11-10 10:35:35 -0800508 write_to_bazelrc('build --copt=-DGEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK')
509 write_to_bazelrc('build --host_copt=-DGEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700510
511
512def set_tf_cuda_clang(environ_cp):
513 """set TF_CUDA_CLANG action_env.
514
515 Args:
516 environ_cp: copy of the os.environ.
517 """
518 question = 'Do you want to use clang as CUDA compiler?'
519 yes_reply = 'Clang will be used as CUDA compiler.'
520 no_reply = 'nvcc will be used as CUDA compiler.'
521 set_action_env_var(
522 environ_cp,
523 'TF_CUDA_CLANG',
524 None,
525 False,
526 question=question,
527 yes_reply=yes_reply,
528 no_reply=no_reply)
529
530
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800531def set_tf_download_clang(environ_cp):
532 """Set TF_DOWNLOAD_CLANG action_env."""
533 question = 'Do you want to download a fresh release of clang? (Experimental)'
534 yes_reply = 'Clang will be downloaded and used to compile tensorflow.'
535 no_reply = 'Clang will not be downloaded.'
536 set_action_env_var(
537 environ_cp,
538 'TF_DOWNLOAD_CLANG',
539 None,
540 False,
541 question=question,
542 yes_reply=yes_reply,
543 no_reply=no_reply)
544
545
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700546def get_from_env_or_user_or_default(environ_cp, var_name, ask_for_var,
547 var_default):
548 """Get var_name either from env, or user or default.
549
550 If var_name has been set as environment variable, use the preset value, else
551 ask for user input. If no input is provided, the default is used.
552
553 Args:
554 environ_cp: copy of the os.environ.
555 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
556 ask_for_var: string for how to ask for user input.
557 var_default: default value string.
558
559 Returns:
560 string value for var_name
561 """
562 var = environ_cp.get(var_name)
563 if not var:
564 var = get_input(ask_for_var)
Michael Cased94271a2017-08-22 17:26:52 -0700565 print('\n')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700566 if not var:
567 var = var_default
568 return var
569
570
571def set_clang_cuda_compiler_path(environ_cp):
572 """Set CLANG_CUDA_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700573 default_clang_path = which('clang') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700574 ask_clang_path = ('Please specify which clang should be used as device and '
575 'host compiler. [Default is %s]: ') % default_clang_path
576
577 while True:
578 clang_cuda_compiler_path = get_from_env_or_user_or_default(
579 environ_cp, 'CLANG_CUDA_COMPILER_PATH', ask_clang_path,
580 default_clang_path)
581 if os.path.exists(clang_cuda_compiler_path):
582 break
583
584 # Reset and retry
585 print('Invalid clang path: %s cannot be found.' % clang_cuda_compiler_path)
586 environ_cp['CLANG_CUDA_COMPILER_PATH'] = ''
587
588 # Set CLANG_CUDA_COMPILER_PATH
589 environ_cp['CLANG_CUDA_COMPILER_PATH'] = clang_cuda_compiler_path
590 write_action_env_to_bazelrc('CLANG_CUDA_COMPILER_PATH',
591 clang_cuda_compiler_path)
592
593
Austin Anderson6afface2017-12-05 11:59:17 -0800594def prompt_loop_or_load_from_env(
595 environ_cp,
596 var_name,
597 var_default,
598 ask_for_var,
599 check_success,
600 error_msg,
601 suppress_default_error=False,
602 n_ask_attempts=_DEFAULT_PROMPT_ASK_ATTEMPTS
603):
604 """Loop over user prompts for an ENV param until receiving a valid response.
605
606 For the env param var_name, read from the environment or verify user input
607 until receiving valid input. When done, set var_name in the environ_cp to its
608 new value.
609
610 Args:
611 environ_cp: (Dict) copy of the os.environ.
612 var_name: (String) string for name of environment variable, e.g. "TF_MYVAR".
613 var_default: (String) default value string.
614 ask_for_var: (String) string for how to ask for user input.
615 check_success: (Function) function that takes one argument and returns a
616 boolean. Should return True if the value provided is considered valid. May
617 contain a complex error message if error_msg does not provide enough
618 information. In that case, set suppress_default_error to True.
619 error_msg: (String) String with one and only one '%s'. Formatted with each
620 invalid response upon check_success(input) failure.
621 suppress_default_error: (Bool) Suppress the above error message in favor of
622 one from the check_success function.
623 n_ask_attempts: (Integer) Number of times to query for valid input before
624 raising an error and quitting.
625
626 Returns:
627 [String] The value of var_name after querying for input.
628
629 Raises:
630 UserInputError: if a query has been attempted n_ask_attempts times without
Frank Chenc4ef9272018-01-10 11:36:52 -0800631 success, assume that the user has made a scripting error, and will
632 continue to provide invalid input. Raise the error to avoid infinitely
633 looping.
Austin Anderson6afface2017-12-05 11:59:17 -0800634 """
635 default = environ_cp.get(var_name) or var_default
636 full_query = '%s [Default is %s]: ' % (
637 ask_for_var,
638 default,
639 )
640
641 for _ in range(n_ask_attempts):
642 val = get_from_env_or_user_or_default(environ_cp,
643 var_name,
644 full_query,
645 default)
646 if check_success(val):
647 break
648 if not suppress_default_error:
649 print(error_msg % val)
650 environ_cp[var_name] = ''
651 else:
652 raise UserInputError('Invalid %s setting was provided %d times in a row. '
653 'Assuming to be a scripting mistake.' %
654 (var_name, n_ask_attempts))
655
656 environ_cp[var_name] = val
657 return val
658
659
660def create_android_ndk_rule(environ_cp):
661 """Set ANDROID_NDK_HOME and write Android NDK WORKSPACE rule."""
662 if is_windows() or is_cygwin():
663 default_ndk_path = cygpath('%s/Android/Sdk/ndk-bundle' %
664 environ_cp['APPDATA'])
665 elif is_macos():
666 default_ndk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
667 else:
668 default_ndk_path = '%s/Android/Sdk/ndk-bundle' % environ_cp['HOME']
669
670 def valid_ndk_path(path):
671 return (os.path.exists(path) and
672 os.path.exists(os.path.join(path, 'source.properties')))
673
674 android_ndk_home_path = prompt_loop_or_load_from_env(
675 environ_cp,
676 var_name='ANDROID_NDK_HOME',
677 var_default=default_ndk_path,
678 ask_for_var='Please specify the home path of the Android NDK to use.',
679 check_success=valid_ndk_path,
680 error_msg=('The path %s or its child file "source.properties" '
681 'does not exist.')
682 )
683
684 write_android_ndk_workspace_rule(android_ndk_home_path)
685
686
687def create_android_sdk_rule(environ_cp):
688 """Set Android variables and write Android SDK WORKSPACE rule."""
689 if is_windows() or is_cygwin():
690 default_sdk_path = cygpath('%s/Android/Sdk' % environ_cp['APPDATA'])
691 elif is_macos():
692 default_sdk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
693 else:
694 default_sdk_path = '%s/Android/Sdk' % environ_cp['HOME']
695
696 def valid_sdk_path(path):
697 return (os.path.exists(path) and
698 os.path.exists(os.path.join(path, 'platforms')) and
699 os.path.exists(os.path.join(path, 'build-tools')))
700
701 android_sdk_home_path = prompt_loop_or_load_from_env(
702 environ_cp,
703 var_name='ANDROID_SDK_HOME',
704 var_default=default_sdk_path,
705 ask_for_var='Please specify the home path of the Android SDK to use.',
706 check_success=valid_sdk_path,
707 error_msg=('Either %s does not exist, or it does not contain the '
708 'subdirectories "platforms" and "build-tools".'))
709
710 platforms = os.path.join(android_sdk_home_path, 'platforms')
711 api_levels = sorted(os.listdir(platforms))
712 api_levels = [x.replace('android-', '') for x in api_levels]
713
714 def valid_api_level(api_level):
715 return os.path.exists(os.path.join(android_sdk_home_path,
716 'platforms',
717 'android-' + api_level))
718
719 android_api_level = prompt_loop_or_load_from_env(
720 environ_cp,
721 var_name='ANDROID_API_LEVEL',
722 var_default=api_levels[-1],
723 ask_for_var=('Please specify the Android SDK API level to use. '
724 '[Available levels: %s]') % api_levels,
725 check_success=valid_api_level,
726 error_msg='Android-%s is not present in the SDK path.')
727
728 build_tools = os.path.join(android_sdk_home_path, 'build-tools')
729 versions = sorted(os.listdir(build_tools))
730
731 def valid_build_tools(version):
732 return os.path.exists(os.path.join(android_sdk_home_path,
733 'build-tools',
734 version))
735
736 android_build_tools_version = prompt_loop_or_load_from_env(
737 environ_cp,
738 var_name='ANDROID_BUILD_TOOLS_VERSION',
739 var_default=versions[-1],
740 ask_for_var=('Please specify an Android build tools version to use. '
741 '[Available versions: %s]') % versions,
742 check_success=valid_build_tools,
743 error_msg=('The selected SDK does not have build-tools version %s '
744 'available.'))
745
746 write_android_sdk_workspace_rule(android_sdk_home_path,
747 android_build_tools_version,
748 android_api_level)
749
750
751def write_android_sdk_workspace_rule(android_sdk_home_path,
752 android_build_tools_version,
753 android_api_level):
754 print('Writing android_sdk_workspace rule.\n')
755 with open(_TF_WORKSPACE, 'a') as f:
756 f.write("""
757android_sdk_repository(
758 name="androidsdk",
759 api_level=%s,
760 path="%s",
761 build_tools_version="%s")\n
762""" % (android_api_level, android_sdk_home_path, android_build_tools_version))
763
764
765def write_android_ndk_workspace_rule(android_ndk_home_path):
766 print('Writing android_ndk_workspace rule.')
767 ndk_api_level = check_ndk_level(android_ndk_home_path)
768 if int(ndk_api_level) not in _SUPPORTED_ANDROID_NDK_VERSIONS:
769 print('WARNING: The API level of the NDK in %s is %s, which is not '
770 'supported by Bazel (officially supported versions: %s). Please use '
771 'another version. Compiling Android targets may result in confusing '
772 'errors.\n' % (android_ndk_home_path, ndk_api_level,
773 _SUPPORTED_ANDROID_NDK_VERSIONS))
774 with open(_TF_WORKSPACE, 'a') as f:
775 f.write("""
776android_ndk_repository(
777 name="androidndk",
778 path="%s",
779 api_level=%s)\n
780""" % (android_ndk_home_path, ndk_api_level))
781
782
783def check_ndk_level(android_ndk_home_path):
784 """Check the revision number of an Android NDK path."""
785 properties_path = '%s/source.properties' % android_ndk_home_path
786 if is_windows() or is_cygwin():
787 properties_path = cygpath(properties_path)
788 with open(properties_path, 'r') as f:
789 filedata = f.read()
790
791 revision = re.search(r'Pkg.Revision = (\d+)', filedata)
792 if revision:
793 return revision.group(1)
794 return None
795
796
797def workspace_has_any_android_rule():
798 """Check the WORKSPACE for existing android_*_repository rules."""
799 with open(_TF_WORKSPACE, 'r') as f:
800 workspace = f.read()
801 has_any_rule = re.search(r'^android_[ns]dk_repository',
802 workspace,
803 re.MULTILINE)
804 return has_any_rule
805
806
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700807def set_gcc_host_compiler_path(environ_cp):
808 """Set GCC_HOST_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700809 default_gcc_host_compiler_path = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700810 cuda_bin_symlink = '%s/bin/gcc' % environ_cp.get('CUDA_TOOLKIT_PATH')
811
812 if os.path.islink(cuda_bin_symlink):
813 # os.readlink is only available in linux
Jonathan Hseu008910f2017-08-25 14:01:05 -0700814 default_gcc_host_compiler_path = os.path.realpath(cuda_bin_symlink)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700815
Austin Anderson6afface2017-12-05 11:59:17 -0800816 gcc_host_compiler_path = prompt_loop_or_load_from_env(
817 environ_cp,
818 var_name='GCC_HOST_COMPILER_PATH',
819 var_default=default_gcc_host_compiler_path,
820 ask_for_var=
821 'Please specify which gcc should be used by nvcc as the host compiler.',
822 check_success=os.path.exists,
823 error_msg='Invalid gcc path. %s cannot be found.',
824 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700825
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700826 write_action_env_to_bazelrc('GCC_HOST_COMPILER_PATH', gcc_host_compiler_path)
827
828
829def set_tf_cuda_version(environ_cp):
830 """Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION."""
831 ask_cuda_version = (
832 'Please specify the CUDA SDK version you want to use, '
833 'e.g. 7.0. [Leave empty to default to CUDA %s]: ') % _DEFAULT_CUDA_VERSION
834
Austin Andersonf9a88f82017-12-13 11:49:40 -0800835 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700836 # Configure the Cuda SDK version to use.
837 tf_cuda_version = get_from_env_or_user_or_default(
838 environ_cp, 'TF_CUDA_VERSION', ask_cuda_version, _DEFAULT_CUDA_VERSION)
839
840 # Find out where the CUDA toolkit is installed
841 default_cuda_path = _DEFAULT_CUDA_PATH
Martin Wicked57572e2017-09-02 19:21:45 -0700842 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700843 default_cuda_path = cygpath(
844 environ_cp.get('CUDA_PATH', _DEFAULT_CUDA_PATH_WIN))
845 elif is_linux():
846 # If the default doesn't exist, try an alternative default.
847 if (not os.path.exists(default_cuda_path)
848 ) and os.path.exists(_DEFAULT_CUDA_PATH_LINUX):
849 default_cuda_path = _DEFAULT_CUDA_PATH_LINUX
850 ask_cuda_path = ('Please specify the location where CUDA %s toolkit is'
851 ' installed. Refer to README.md for more details. '
852 '[Default is %s]: ') % (tf_cuda_version, default_cuda_path)
853 cuda_toolkit_path = get_from_env_or_user_or_default(
854 environ_cp, 'CUDA_TOOLKIT_PATH', ask_cuda_path, default_cuda_path)
855
856 if is_windows():
857 cuda_rt_lib_path = 'lib/x64/cudart.lib'
858 elif is_linux():
859 cuda_rt_lib_path = 'lib64/libcudart.so.%s' % tf_cuda_version
860 elif is_macos():
861 cuda_rt_lib_path = 'lib/libcudart.%s.dylib' % tf_cuda_version
862
863 cuda_toolkit_path_full = os.path.join(cuda_toolkit_path, cuda_rt_lib_path)
864 if os.path.exists(cuda_toolkit_path_full):
865 break
866
867 # Reset and retry
868 print('Invalid path to CUDA %s toolkit. %s cannot be found' %
869 (tf_cuda_version, cuda_toolkit_path_full))
870 environ_cp['TF_CUDA_VERSION'] = ''
871 environ_cp['CUDA_TOOLKIT_PATH'] = ''
872
Austin Andersonf9a88f82017-12-13 11:49:40 -0800873 else:
874 raise UserInputError('Invalid TF_CUDA_SETTING setting was provided %d '
875 'times in a row. Assuming to be a scripting mistake.' %
876 _DEFAULT_PROMPT_ASK_ATTEMPTS)
877
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700878 # Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION
879 environ_cp['CUDA_TOOLKIT_PATH'] = cuda_toolkit_path
880 write_action_env_to_bazelrc('CUDA_TOOLKIT_PATH', cuda_toolkit_path)
881 environ_cp['TF_CUDA_VERSION'] = tf_cuda_version
882 write_action_env_to_bazelrc('TF_CUDA_VERSION', tf_cuda_version)
883
884
Yifei Fengb1d8c592017-11-22 13:42:21 -0800885def set_tf_cudnn_version(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700886 """Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION."""
887 ask_cudnn_version = (
Jonathan Hseu008910f2017-08-25 14:01:05 -0700888 'Please specify the cuDNN version you want to use. '
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700889 '[Leave empty to default to cuDNN %s.0]: ') % _DEFAULT_CUDNN_VERSION
890
Austin Andersonf9a88f82017-12-13 11:49:40 -0800891 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700892 tf_cudnn_version = get_from_env_or_user_or_default(
893 environ_cp, 'TF_CUDNN_VERSION', ask_cudnn_version,
894 _DEFAULT_CUDNN_VERSION)
895
896 default_cudnn_path = environ_cp.get('CUDA_TOOLKIT_PATH')
897 ask_cudnn_path = (r'Please specify the location where cuDNN %s library is '
898 'installed. Refer to README.md for more details. [Default'
899 ' is %s]:') % (tf_cudnn_version, default_cudnn_path)
900 cudnn_install_path = get_from_env_or_user_or_default(
901 environ_cp, 'CUDNN_INSTALL_PATH', ask_cudnn_path, default_cudnn_path)
902
903 # Result returned from "read" will be used unexpanded. That make "~"
904 # unusable. Going through one more level of expansion to handle that.
905 cudnn_install_path = os.path.realpath(
906 os.path.expanduser(cudnn_install_path))
Martin Wicked57572e2017-09-02 19:21:45 -0700907 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700908 cudnn_install_path = cygpath(cudnn_install_path)
909
910 if is_windows():
911 cuda_dnn_lib_path = 'lib/x64/cudnn.lib'
912 cuda_dnn_lib_alt_path = 'lib/x64/cudnn.lib'
913 elif is_linux():
914 cuda_dnn_lib_path = 'lib64/libcudnn.so.%s' % tf_cudnn_version
915 cuda_dnn_lib_alt_path = 'libcudnn.so.%s' % tf_cudnn_version
916 elif is_macos():
917 cuda_dnn_lib_path = 'lib/libcudnn.%s.dylib' % tf_cudnn_version
918 cuda_dnn_lib_alt_path = 'libcudnn.%s.dylib' % tf_cudnn_version
919
920 cuda_dnn_lib_path_full = os.path.join(cudnn_install_path, cuda_dnn_lib_path)
921 cuda_dnn_lib_alt_path_full = os.path.join(cudnn_install_path,
922 cuda_dnn_lib_alt_path)
923 if os.path.exists(cuda_dnn_lib_path_full) or os.path.exists(
924 cuda_dnn_lib_alt_path_full):
925 break
926
927 # Try another alternative for Linux
928 if is_linux():
Jonathan Hseu008910f2017-08-25 14:01:05 -0700929 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
930 cudnn_path_from_ldconfig = run_shell([ldconfig_bin, '-p'])
931 cudnn_path_from_ldconfig = re.search('.*libcudnn.so .* => (.*)',
A. Unique TensorFlowere7223582017-09-06 17:57:04 -0700932 cudnn_path_from_ldconfig)
933 if cudnn_path_from_ldconfig:
934 cudnn_path_from_ldconfig = cudnn_path_from_ldconfig.group(1)
935 if os.path.exists('%s.%s' % (cudnn_path_from_ldconfig,
936 tf_cudnn_version)):
937 cudnn_install_path = os.path.dirname(cudnn_path_from_ldconfig)
938 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700939
940 # Reset and Retry
941 print(
942 'Invalid path to cuDNN %s toolkit. None of the following files can be '
943 'found:' % tf_cudnn_version)
944 print(cuda_dnn_lib_path_full)
945 print(cuda_dnn_lib_alt_path_full)
946 if is_linux():
947 print('%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version))
948
949 environ_cp['TF_CUDNN_VERSION'] = ''
Austin Andersonf9a88f82017-12-13 11:49:40 -0800950 else:
951 raise UserInputError('Invalid TF_CUDNN setting was provided %d '
952 'times in a row. Assuming to be a scripting mistake.' %
953 _DEFAULT_PROMPT_ASK_ATTEMPTS)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700954
955 # Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION
956 environ_cp['CUDNN_INSTALL_PATH'] = cudnn_install_path
957 write_action_env_to_bazelrc('CUDNN_INSTALL_PATH', cudnn_install_path)
958 environ_cp['TF_CUDNN_VERSION'] = tf_cudnn_version
959 write_action_env_to_bazelrc('TF_CUDNN_VERSION', tf_cudnn_version)
960
961
962def get_native_cuda_compute_capabilities(environ_cp):
963 """Get native cuda compute capabilities.
964
965 Args:
966 environ_cp: copy of the os.environ.
967 Returns:
968 string of native cuda compute capabilities, separated by comma.
969 """
970 device_query_bin = os.path.join(
971 environ_cp.get('CUDA_TOOLKIT_PATH'), 'extras/demo_suite/deviceQuery')
Jonathan Hseu008910f2017-08-25 14:01:05 -0700972 if os.path.isfile(device_query_bin) and os.access(device_query_bin, os.X_OK):
973 try:
974 output = run_shell(device_query_bin).split('\n')
975 pattern = re.compile('[0-9]*\\.[0-9]*')
976 output = [pattern.search(x) for x in output if 'Capability' in x]
977 output = ','.join(x.group() for x in output if x is not None)
978 except subprocess.CalledProcessError:
979 output = ''
980 else:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700981 output = ''
982 return output
983
984
985def set_tf_cuda_compute_capabilities(environ_cp):
986 """Set TF_CUDA_COMPUTE_CAPABILITIES."""
987 while True:
988 native_cuda_compute_capabilities = get_native_cuda_compute_capabilities(
989 environ_cp)
990 if not native_cuda_compute_capabilities:
991 default_cuda_compute_capabilities = _DEFAULT_CUDA_COMPUTE_CAPABILITIES
992 else:
993 default_cuda_compute_capabilities = native_cuda_compute_capabilities
994
995 ask_cuda_compute_capabilities = (
996 'Please specify a list of comma-separated '
997 'Cuda compute capabilities you want to '
998 'build with.\nYou can find the compute '
999 'capability of your device at: '
1000 'https://developer.nvidia.com/cuda-gpus.\nPlease'
1001 ' note that each additional compute '
1002 'capability significantly increases your '
1003 'build time and binary size. [Default is: %s]' %
1004 default_cuda_compute_capabilities)
1005 tf_cuda_compute_capabilities = get_from_env_or_user_or_default(
1006 environ_cp, 'TF_CUDA_COMPUTE_CAPABILITIES',
1007 ask_cuda_compute_capabilities, default_cuda_compute_capabilities)
1008 # Check whether all capabilities from the input is valid
1009 all_valid = True
1010 for compute_capability in tf_cuda_compute_capabilities.split(','):
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001011 m = re.match('[0-9]+.[0-9]+', compute_capability)
1012 if not m:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001013 print('Invalid compute capability: ' % compute_capability)
1014 all_valid = False
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001015 else:
1016 ver = int(m.group(0).split('.')[0])
1017 if ver < 3:
1018 print('Only compute capabilities 3.0 or higher are supported.')
1019 all_valid = False
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001020
1021 if all_valid:
1022 break
1023
1024 # Reset and Retry
1025 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = ''
1026
1027 # Set TF_CUDA_COMPUTE_CAPABILITIES
1028 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = tf_cuda_compute_capabilities
1029 write_action_env_to_bazelrc('TF_CUDA_COMPUTE_CAPABILITIES',
1030 tf_cuda_compute_capabilities)
1031
1032
1033def set_other_cuda_vars(environ_cp):
1034 """Set other CUDA related variables."""
1035 if is_windows():
1036 # The following three variables are needed for MSVC toolchain configuration
1037 # in Bazel
1038 environ_cp['CUDA_PATH'] = environ_cp.get('CUDA_TOOLKIT_PATH')
1039 environ_cp['CUDA_COMPUTE_CAPABILITIES'] = environ_cp.get(
1040 'TF_CUDA_COMPUTE_CAPABILITIES')
1041 environ_cp['NO_WHOLE_ARCHIVE_OPTION'] = 1
1042 write_action_env_to_bazelrc('CUDA_PATH', environ_cp.get('CUDA_PATH'))
1043 write_action_env_to_bazelrc('CUDA_COMPUTE_CAPABILITIE',
1044 environ_cp.get('CUDA_COMPUTE_CAPABILITIE'))
1045 write_action_env_to_bazelrc('NO_WHOLE_ARCHIVE_OPTION',
1046 environ_cp.get('NO_WHOLE_ARCHIVE_OPTION'))
1047 write_to_bazelrc('build --config=win-cuda')
1048 write_to_bazelrc('test --config=win-cuda')
1049 else:
1050 # If CUDA is enabled, always use GPU during build and test.
1051 if environ_cp.get('TF_CUDA_CLANG') == '1':
1052 write_to_bazelrc('build --config=cuda_clang')
1053 write_to_bazelrc('test --config=cuda_clang')
1054 else:
1055 write_to_bazelrc('build --config=cuda')
1056 write_to_bazelrc('test --config=cuda')
1057
1058
1059def set_host_cxx_compiler(environ_cp):
1060 """Set HOST_CXX_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001061 default_cxx_host_compiler = which('g++') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001062
Austin Anderson6afface2017-12-05 11:59:17 -08001063 host_cxx_compiler = prompt_loop_or_load_from_env(
1064 environ_cp,
1065 var_name='HOST_CXX_COMPILER',
1066 var_default=default_cxx_host_compiler,
1067 ask_for_var=('Please specify which C++ compiler should be used as the '
1068 'host C++ compiler.'),
1069 check_success=os.path.exists,
1070 error_msg='Invalid C++ compiler path. %s cannot be found.',
1071 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001072
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001073 write_action_env_to_bazelrc('HOST_CXX_COMPILER', host_cxx_compiler)
1074
1075
1076def set_host_c_compiler(environ_cp):
1077 """Set HOST_C_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001078 default_c_host_compiler = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001079
Austin Anderson6afface2017-12-05 11:59:17 -08001080 host_c_compiler = prompt_loop_or_load_from_env(
1081 environ_cp,
1082 var_name='HOST_C_COMPILER',
1083 var_default=default_c_host_compiler,
1084 ask_for_var=('Please specify which C compiler should be used as the host'
1085 'C compiler.'),
1086 check_success=os.path.exists,
1087 error_msg='Invalid C compiler path. %s cannot be found.',
1088 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001089
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001090 write_action_env_to_bazelrc('HOST_C_COMPILER', host_c_compiler)
1091
1092
1093def set_computecpp_toolkit_path(environ_cp):
1094 """Set COMPUTECPP_TOOLKIT_PATH."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001095
Austin Anderson6afface2017-12-05 11:59:17 -08001096 def toolkit_exists(toolkit_path):
1097 """Check if a computecpp toolkit path is valid."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001098 if is_linux():
1099 sycl_rt_lib_path = 'lib/libComputeCpp.so'
1100 else:
1101 sycl_rt_lib_path = ''
1102
Austin Anderson6afface2017-12-05 11:59:17 -08001103 sycl_rt_lib_path_full = os.path.join(toolkit_path,
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001104 sycl_rt_lib_path)
Austin Anderson6afface2017-12-05 11:59:17 -08001105 exists = os.path.exists(sycl_rt_lib_path_full)
1106 if not exists:
1107 print('Invalid SYCL %s library path. %s cannot be found' %
1108 (_TF_OPENCL_VERSION, sycl_rt_lib_path_full))
1109 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001110
Austin Anderson6afface2017-12-05 11:59:17 -08001111 computecpp_toolkit_path = prompt_loop_or_load_from_env(
1112 environ_cp,
1113 var_name='COMPUTECPP_TOOLKIT_PATH',
1114 var_default=_DEFAULT_COMPUTECPP_TOOLKIT_PATH,
1115 ask_for_var=(
1116 'Please specify the location where ComputeCpp for SYCL %s is '
1117 'installed.' % _TF_OPENCL_VERSION),
1118 check_success=toolkit_exists,
1119 error_msg='Invalid SYCL compiler path. %s cannot be found.',
1120 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001121
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001122 write_action_env_to_bazelrc('COMPUTECPP_TOOLKIT_PATH',
1123 computecpp_toolkit_path)
1124
Michael Cased31531a2018-01-05 14:09:41 -08001125
Dandelion Man?90e42f32017-12-15 18:15:07 -08001126def set_trisycl_include_dir(environ_cp):
Michael Cased31531a2018-01-05 14:09:41 -08001127 """Set TRISYCL_INCLUDE_DIR."""
Frank Chenc4ef9272018-01-10 11:36:52 -08001128
Dandelion Man?90e42f32017-12-15 18:15:07 -08001129 ask_trisycl_include_dir = ('Please specify the location of the triSYCL '
1130 'include directory. (Use --config=sycl_trisycl '
1131 'when building with Bazel) '
1132 '[Default is %s]: '
Michael Cased31531a2018-01-05 14:09:41 -08001133 ) % (_DEFAULT_TRISYCL_INCLUDE_DIR)
Frank Chenc4ef9272018-01-10 11:36:52 -08001134
Dandelion Man?90e42f32017-12-15 18:15:07 -08001135 while True:
1136 trisycl_include_dir = get_from_env_or_user_or_default(
Michael Cased31531a2018-01-05 14:09:41 -08001137 environ_cp, 'TRISYCL_INCLUDE_DIR', ask_trisycl_include_dir,
1138 _DEFAULT_TRISYCL_INCLUDE_DIR)
Dandelion Man?90e42f32017-12-15 18:15:07 -08001139 if os.path.exists(trisycl_include_dir):
1140 break
1141
1142 print('Invalid triSYCL include directory, %s cannot be found'
1143 % (trisycl_include_dir))
1144
1145 # Set TRISYCL_INCLUDE_DIR
1146 environ_cp['TRISYCL_INCLUDE_DIR'] = trisycl_include_dir
1147 write_action_env_to_bazelrc('TRISYCL_INCLUDE_DIR',
1148 trisycl_include_dir)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001149
Yifei Fengb1d8c592017-11-22 13:42:21 -08001150
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001151def set_mpi_home(environ_cp):
1152 """Set MPI_HOME."""
Austin Anderson6afface2017-12-05 11:59:17 -08001153
Jonathan Hseu008910f2017-08-25 14:01:05 -07001154 default_mpi_home = which('mpirun') or which('mpiexec') or ''
1155 default_mpi_home = os.path.dirname(os.path.dirname(default_mpi_home))
1156
Austin Anderson6afface2017-12-05 11:59:17 -08001157 def valid_mpi_path(mpi_home):
1158 exists = (os.path.exists(os.path.join(mpi_home, 'include')) and
1159 os.path.exists(os.path.join(mpi_home, 'lib')))
1160 if not exists:
1161 print('Invalid path to the MPI Toolkit. %s or %s cannot be found' %
1162 (os.path.join(mpi_home, 'include'),
1163 os.path.exists(os.path.join(mpi_home, 'lib'))))
1164 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001165
Austin Anderson6afface2017-12-05 11:59:17 -08001166 _ = prompt_loop_or_load_from_env(
1167 environ_cp,
1168 var_name='MPI_HOME',
1169 var_default=default_mpi_home,
1170 ask_for_var='Please specify the MPI toolkit folder.',
1171 check_success=valid_mpi_path,
1172 error_msg='',
1173 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001174
1175
1176def set_other_mpi_vars(environ_cp):
1177 """Set other MPI related variables."""
1178 # Link the MPI header files
1179 mpi_home = environ_cp.get('MPI_HOME')
1180 symlink_force('%s/include/mpi.h' % mpi_home, 'third_party/mpi/mpi.h')
1181
1182 # Determine if we use OpenMPI or MVAPICH, these require different header files
1183 # to be included here to make bazel dependency checker happy
1184 if os.path.exists(os.path.join(mpi_home, 'include/mpi_portable_platform.h')):
1185 symlink_force(
1186 os.path.join(mpi_home, 'include/mpi_portable_platform.h'),
1187 'third_party/mpi/mpi_portable_platform.h')
1188 # TODO(gunan): avoid editing files in configure
1189 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=False',
1190 'MPI_LIB_IS_OPENMPI=True')
1191 else:
1192 # MVAPICH / MPICH
1193 symlink_force(
1194 os.path.join(mpi_home, 'include/mpio.h'), 'third_party/mpi/mpio.h')
1195 symlink_force(
1196 os.path.join(mpi_home, 'include/mpicxx.h'), 'third_party/mpi/mpicxx.h')
1197 # TODO(gunan): avoid editing files in configure
1198 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=True',
1199 'MPI_LIB_IS_OPENMPI=False')
1200
1201 if os.path.exists(os.path.join(mpi_home, 'lib/libmpi.so')):
1202 symlink_force(
1203 os.path.join(mpi_home, 'lib/libmpi.so'), 'third_party/mpi/libmpi.so')
1204 else:
1205 raise ValueError('Cannot find the MPI library file in %s/lib' % mpi_home)
1206
1207
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001208def set_grpc_build_flags():
1209 write_to_bazelrc('build --define grpc_no_ares=true')
1210
Michael Cased31531a2018-01-05 14:09:41 -08001211
Dandelion Man?90e42f32017-12-15 18:15:07 -08001212def set_windows_build_flags():
1213 if is_windows():
1214 # The non-monolithic build is not supported yet
1215 write_to_bazelrc('build --config monolithic')
1216 # Suppress warning messages
1217 write_to_bazelrc('build --copt=-w --host_copt=-w')
1218 # Output more verbose information when something goes wrong
1219 write_to_bazelrc('build --verbose_failures')
1220
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001221
Michael Cased31531a2018-01-05 14:09:41 -08001222def config_info_line(name, help_text):
1223 """Helper function to print formatted help text for Bazel config options."""
1224 print('\t--config=%-12s\t# %s' % (name, help_text))
1225
1226
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001227def main():
1228 # Make a copy of os.environ to be clear when functions and getting and setting
1229 # environment variables.
1230 environ_cp = dict(os.environ)
1231
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -07001232 check_bazel_version('0.5.4')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001233
1234 reset_tf_configure_bazelrc()
1235 cleanup_makefile()
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -07001236 setup_python(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001237
1238 if is_windows():
Benoit Steiner355e25e2017-10-24 19:47:46 -07001239 environ_cp['TF_NEED_S3'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001240 environ_cp['TF_NEED_GCP'] = '0'
1241 environ_cp['TF_NEED_HDFS'] = '0'
1242 environ_cp['TF_NEED_JEMALLOC'] = '0'
Yifei Fengb1d8c592017-11-22 13:42:21 -08001243 environ_cp['TF_NEED_OPENCL_SYCL'] = '0'
1244 environ_cp['TF_NEED_COMPUTECPP'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001245 environ_cp['TF_NEED_OPENCL'] = '0'
1246 environ_cp['TF_CUDA_CLANG'] = '0'
1247
1248 if is_macos():
1249 environ_cp['TF_NEED_JEMALLOC'] = '0'
1250
1251 set_build_var(environ_cp, 'TF_NEED_JEMALLOC', 'jemalloc as malloc',
1252 'with_jemalloc', True)
1253 set_build_var(environ_cp, 'TF_NEED_GCP', 'Google Cloud Platform',
Benoit Steiner355e25e2017-10-24 19:47:46 -07001254 'with_gcp_support', True, 'gcp')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001255 set_build_var(environ_cp, 'TF_NEED_HDFS', 'Hadoop File System',
Benoit Steiner355e25e2017-10-24 19:47:46 -07001256 'with_hdfs_support', True, 'hdfs')
Michael Case7e4e3362017-10-09 13:31:15 -07001257 set_build_var(environ_cp, 'TF_NEED_S3', 'Amazon S3 File System',
1258 'with_s3_support', True, 's3')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001259 set_build_var(environ_cp, 'TF_ENABLE_XLA', 'XLA JIT', 'with_xla_support',
Michael Case98850a52017-09-14 13:35:57 -07001260 False, 'xla')
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -07001261 set_build_var(environ_cp, 'TF_NEED_GDR', 'GDR', 'with_gdr_support',
Michael Case98850a52017-09-14 13:35:57 -07001262 False, 'gdr')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001263 set_build_var(environ_cp, 'TF_NEED_VERBS', 'VERBS', 'with_verbs_support',
Michael Case98850a52017-09-14 13:35:57 -07001264 False, 'verbs')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001265
Yifei Fengb1d8c592017-11-22 13:42:21 -08001266 set_action_env_var(environ_cp, 'TF_NEED_OPENCL_SYCL', 'OpenCL SYCL', False)
1267 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001268 set_host_cxx_compiler(environ_cp)
1269 set_host_c_compiler(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001270 set_action_env_var(environ_cp, 'TF_NEED_COMPUTECPP', 'ComputeCPP', True)
1271 if environ_cp.get('TF_NEED_COMPUTECPP') == '1':
1272 set_computecpp_toolkit_path(environ_cp)
1273 else:
1274 set_trisycl_include_dir(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001275
1276 set_action_env_var(environ_cp, 'TF_NEED_CUDA', 'CUDA', False)
A. Unique TensorFlower24cbb2a2017-09-08 07:45:44 -07001277 if (environ_cp.get('TF_NEED_CUDA') == '1' and
1278 'TF_CUDA_CONFIG_REPO' not in environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001279 set_tf_cuda_version(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001280 set_tf_cudnn_version(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001281 set_tf_cuda_compute_capabilities(environ_cp)
1282
1283 set_tf_cuda_clang(environ_cp)
1284 if environ_cp.get('TF_CUDA_CLANG') == '1':
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -08001285 if not is_windows():
1286 # Ask if we want to download clang release while building.
1287 set_tf_download_clang(environ_cp)
1288 else:
1289 # We use bazel's generated crosstool on Windows and there is no
1290 # way to provide downloaded toolchain for that yet.
1291 # TODO(ibiryukov): Investigate using clang as a cuda compiler on
1292 # Windows.
1293 environ_cp['TF_DOWNLOAD_CLANG'] = '0'
1294
1295 if environ_cp.get('TF_DOWNLOAD_CLANG') != '1':
1296 # Set up which clang we should use as the cuda / host compiler.
1297 set_clang_cuda_compiler_path(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001298 else:
1299 # Set up which gcc nvcc should use as the host compiler
1300 # No need to set this on Windows
1301 if not is_windows():
1302 set_gcc_host_compiler_path(environ_cp)
1303 set_other_cuda_vars(environ_cp)
1304
1305 set_build_var(environ_cp, 'TF_NEED_MPI', 'MPI', 'with_mpi_support', False)
1306 if environ_cp.get('TF_NEED_MPI') == '1':
1307 set_mpi_home(environ_cp)
1308 set_other_mpi_vars(environ_cp)
1309
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001310 set_grpc_build_flags()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001311 set_cc_opt_flags(environ_cp)
Dandelion Man?90e42f32017-12-15 18:15:07 -08001312 set_windows_build_flags()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001313
Austin Anderson6afface2017-12-05 11:59:17 -08001314 if workspace_has_any_android_rule():
1315 print('The WORKSPACE file has at least one of ["android_sdk_repository", '
1316 '"android_ndk_repository"] already set. Will not ask to help '
1317 'configure the WORKSPACE. Please delete the existing rules to '
1318 'activate the helper.\n')
1319 else:
1320 if get_var(
1321 environ_cp, 'TF_SET_ANDROID_WORKSPACE', 'android workspace',
1322 False,
1323 ('Would you like to interactively configure ./WORKSPACE for '
1324 'Android builds?'),
1325 'Searching for NDK and SDK installations.',
1326 'Not configuring the WORKSPACE for Android builds.'):
1327 create_android_ndk_rule(environ_cp)
1328 create_android_sdk_rule(environ_cp)
1329
Michael Cased31531a2018-01-05 14:09:41 -08001330 print('Preconfigured Bazel build configs. You can use any of the below by '
1331 'adding "--config=<>" to your build command. See tools/bazel.rc for '
1332 'more details.')
1333 config_info_line('mkl', 'Build with MKL support.')
1334 config_info_line('monolithic', 'Config for mostly static monolithic build.')
Austin Anderson6afface2017-12-05 11:59:17 -08001335
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001336if __name__ == '__main__':
1337 main()